llama.cpp 940 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490
  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_layers(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. // TODO (jmorganca): this should most likely be passed in as part of a batch
  2526. // and not set on the context for all batches.
  2527. bool cross_attn = false;
  2528. enum llama_pooling_type pooling_type;
  2529. ggml_backend_sched_eval_callback cb_eval;
  2530. void * cb_eval_user_data;
  2531. };
  2532. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2533. struct llama_layer {
  2534. // normalization
  2535. struct ggml_tensor * attn_norm;
  2536. struct ggml_tensor * attn_norm_b;
  2537. struct ggml_tensor * attn_norm_2;
  2538. struct ggml_tensor * attn_norm_2_b;
  2539. struct ggml_tensor * attn_q_norm;
  2540. struct ggml_tensor * attn_q_norm_b;
  2541. struct ggml_tensor * attn_k_norm;
  2542. struct ggml_tensor * attn_k_norm_b;
  2543. struct ggml_tensor * attn_out_norm;
  2544. struct ggml_tensor * attn_out_norm_b;
  2545. struct ggml_tensor * attn_q_a_norm;
  2546. struct ggml_tensor * attn_kv_a_norm;
  2547. struct ggml_tensor * attn_sub_norm;
  2548. struct ggml_tensor * attn_post_norm;
  2549. struct ggml_tensor * ffn_sub_norm;
  2550. struct ggml_tensor * attn_norm_cross;
  2551. struct ggml_tensor * attn_norm_enc;
  2552. // attention
  2553. struct ggml_tensor * wq;
  2554. struct ggml_tensor * wk;
  2555. struct ggml_tensor * wv;
  2556. struct ggml_tensor * wo;
  2557. struct ggml_tensor * wqkv;
  2558. struct ggml_tensor * wq_a;
  2559. struct ggml_tensor * wq_b;
  2560. struct ggml_tensor * wkv_a_mqa;
  2561. struct ggml_tensor * wkv_b;
  2562. struct ggml_tensor * wq_cross;
  2563. struct ggml_tensor * wk_cross;
  2564. struct ggml_tensor * wv_cross;
  2565. struct ggml_tensor * wo_cross;
  2566. struct ggml_tensor * wq_enc;
  2567. struct ggml_tensor * wk_enc;
  2568. struct ggml_tensor * wv_enc;
  2569. struct ggml_tensor * wo_enc;
  2570. // attention bias
  2571. struct ggml_tensor * bq;
  2572. struct ggml_tensor * bk;
  2573. struct ggml_tensor * bv;
  2574. struct ggml_tensor * bo;
  2575. struct ggml_tensor * bqkv;
  2576. // relative position bias
  2577. struct ggml_tensor * attn_rel_b;
  2578. struct ggml_tensor * attn_rel_b_enc;
  2579. struct ggml_tensor * attn_rel_b_cross;
  2580. // normalization
  2581. struct ggml_tensor * ffn_norm;
  2582. struct ggml_tensor * ffn_norm_b;
  2583. struct ggml_tensor * ffn_post_norm;
  2584. struct ggml_tensor * layer_out_norm;
  2585. struct ggml_tensor * layer_out_norm_b;
  2586. struct ggml_tensor * ffn_norm_exps;
  2587. struct ggml_tensor * ffn_norm_enc;
  2588. // ff
  2589. struct ggml_tensor * ffn_gate; // w1
  2590. struct ggml_tensor * ffn_down; // w2
  2591. struct ggml_tensor * ffn_up; // w3
  2592. struct ggml_tensor * ffn_gate_enc;
  2593. struct ggml_tensor * ffn_down_enc;
  2594. struct ggml_tensor * ffn_up_enc;
  2595. // ff MoE
  2596. struct ggml_tensor * ffn_gate_inp;
  2597. struct ggml_tensor * ffn_gate_exps;
  2598. struct ggml_tensor * ffn_down_exps;
  2599. struct ggml_tensor * ffn_up_exps ;
  2600. // ff shared expert (shexp)
  2601. struct ggml_tensor * ffn_gate_inp_shexp;
  2602. struct ggml_tensor * ffn_gate_shexp;
  2603. struct ggml_tensor * ffn_down_shexp;
  2604. struct ggml_tensor * ffn_up_shexp;
  2605. // ff bias
  2606. struct ggml_tensor * ffn_gate_b = nullptr;
  2607. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2608. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2609. struct ggml_tensor * ffn_act;
  2610. // mamba proj
  2611. struct ggml_tensor * ssm_in;
  2612. struct ggml_tensor * ssm_x;
  2613. struct ggml_tensor * ssm_dt;
  2614. struct ggml_tensor * ssm_out;
  2615. // mamba
  2616. struct ggml_tensor * ssm_conv1d;
  2617. struct ggml_tensor * ssm_a;
  2618. struct ggml_tensor * ssm_d;
  2619. // mamba bias
  2620. struct ggml_tensor * ssm_conv1d_b;
  2621. struct ggml_tensor * ssm_dt_b;
  2622. // rwkv
  2623. struct ggml_tensor * time_mix_w1;
  2624. struct ggml_tensor * time_mix_w2;
  2625. struct ggml_tensor * time_mix_lerp_x;
  2626. struct ggml_tensor * time_mix_lerp_w;
  2627. struct ggml_tensor * time_mix_lerp_k;
  2628. struct ggml_tensor * time_mix_lerp_v;
  2629. struct ggml_tensor * time_mix_lerp_r;
  2630. struct ggml_tensor * time_mix_lerp_g;
  2631. struct ggml_tensor * time_mix_first;
  2632. struct ggml_tensor * time_mix_decay;
  2633. struct ggml_tensor * time_mix_decay_w1;
  2634. struct ggml_tensor * time_mix_decay_w2;
  2635. struct ggml_tensor * time_mix_key;
  2636. struct ggml_tensor * time_mix_value;
  2637. struct ggml_tensor * time_mix_receptance;
  2638. struct ggml_tensor * time_mix_gate;
  2639. struct ggml_tensor * time_mix_ln;
  2640. struct ggml_tensor * time_mix_ln_b;
  2641. struct ggml_tensor * time_mix_output;
  2642. struct ggml_tensor * channel_mix_lerp_k;
  2643. struct ggml_tensor * channel_mix_lerp_r;
  2644. struct ggml_tensor * channel_mix_key;
  2645. struct ggml_tensor * channel_mix_receptance;
  2646. struct ggml_tensor * channel_mix_value;
  2647. // long rope factors
  2648. struct ggml_tensor * rope_long = nullptr;
  2649. struct ggml_tensor * rope_short = nullptr;
  2650. struct ggml_tensor * rope_freqs = nullptr;
  2651. // bitnet scale
  2652. struct ggml_tensor * wq_scale;
  2653. struct ggml_tensor * wk_scale;
  2654. struct ggml_tensor * wv_scale;
  2655. struct ggml_tensor * wo_scale;
  2656. struct ggml_tensor * ffn_gate_scale;
  2657. struct ggml_tensor * ffn_up_scale;
  2658. struct ggml_tensor * ffn_down_scale;
  2659. struct ggml_tensor * bskcn_tv;
  2660. // cross attention
  2661. struct ggml_tensor * cross_attn_k_norm;
  2662. struct ggml_tensor * cross_attn_k_proj;
  2663. struct ggml_tensor * cross_attn_o_proj;
  2664. struct ggml_tensor * cross_attn_q_norm;
  2665. struct ggml_tensor * cross_attn_q_proj;
  2666. struct ggml_tensor * cross_attn_v_proj;
  2667. struct ggml_tensor * cross_attn_attn_gate;
  2668. struct ggml_tensor * cross_attn_mlp_gate;
  2669. };
  2670. // very similar to llama_batch,
  2671. // but has more metadata about sequences
  2672. struct llama_ubatch {
  2673. bool equal_seqs;
  2674. // TODO: whole_seqs for embeddings?
  2675. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2676. uint32_t n_seq_tokens; // tokens per sequence
  2677. uint32_t n_seqs;
  2678. llama_token * token; // [n_tokens]
  2679. float * embd; // [n_embd, n_tokens]
  2680. llama_pos * pos; // [n_tokens]
  2681. int32_t * n_seq_id; // [n_seqs]
  2682. llama_seq_id ** seq_id; // [n_seqs]
  2683. int8_t * output; // [n_tokens]
  2684. };
  2685. struct llama_kv_cell {
  2686. llama_pos pos = -1;
  2687. llama_pos delta = 0;
  2688. int32_t src = -1; // used by recurrent state models to copy states
  2689. int32_t tail = -1;
  2690. std::set<llama_seq_id> seq_id;
  2691. bool has_seq_id(const llama_seq_id & id) const {
  2692. return seq_id.find(id) != seq_id.end();
  2693. }
  2694. bool is_empty() const {
  2695. return seq_id.empty();
  2696. }
  2697. bool is_same_seq(const llama_kv_cell & other) const {
  2698. return seq_id == other.seq_id;
  2699. }
  2700. };
  2701. // ring-buffer of cached KV data
  2702. struct llama_kv_cache {
  2703. bool has_shift = false;
  2704. bool do_defrag = false;
  2705. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2706. bool v_trans = true; // the value tensor is transposed
  2707. // Note: The value of head isn't only used to optimize searching
  2708. // for a free KV slot. llama_decode_internal also uses it, so it
  2709. // cannot be freely changed after a slot has been allocated.
  2710. uint32_t head = 0;
  2711. uint32_t size = 0;
  2712. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2713. // computed before each graph build
  2714. uint32_t n = 0;
  2715. ggml_type type_k = GGML_TYPE_F16;
  2716. ggml_type type_v = GGML_TYPE_F16;
  2717. std::vector<llama_kv_cell> cells;
  2718. std::vector<struct ggml_tensor *> k_l; // per layer
  2719. std::vector<struct ggml_tensor *> v_l;
  2720. std::vector<struct ggml_context *> ctxs;
  2721. std::vector<ggml_backend_buffer_t> bufs;
  2722. size_t total_size() const {
  2723. size_t size = 0;
  2724. for (ggml_backend_buffer_t buf : bufs) {
  2725. size += ggml_backend_buffer_get_size(buf);
  2726. }
  2727. return size;
  2728. }
  2729. ~llama_kv_cache() {
  2730. for (struct ggml_context * ctx : ctxs) {
  2731. ggml_free(ctx);
  2732. }
  2733. for (ggml_backend_buffer_t buf : bufs) {
  2734. ggml_backend_buffer_free(buf);
  2735. }
  2736. }
  2737. };
  2738. struct llama_control_vector {
  2739. std::vector<struct ggml_tensor *> tensors; // per layer
  2740. std::vector<struct ggml_context *> ctxs;
  2741. std::vector<ggml_backend_buffer_t> bufs;
  2742. int32_t layer_start = -1;
  2743. int32_t layer_end = -1;
  2744. struct ggml_tensor * tensor_for(int il) const {
  2745. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2746. return nullptr;
  2747. }
  2748. return tensors[il];
  2749. }
  2750. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2751. ggml_tensor * layer_dir = tensor_for(il);
  2752. if (layer_dir != nullptr) {
  2753. cur = ggml_add(ctx, cur, layer_dir);
  2754. }
  2755. return cur;
  2756. }
  2757. ~llama_control_vector() {
  2758. for (struct ggml_context * ctx : ctxs) {
  2759. ggml_free(ctx);
  2760. }
  2761. for (ggml_backend_buffer_t buf : bufs) {
  2762. ggml_backend_buffer_free(buf);
  2763. }
  2764. }
  2765. };
  2766. struct llama_model {
  2767. e_model type = MODEL_UNKNOWN;
  2768. llm_arch arch = LLM_ARCH_UNKNOWN;
  2769. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2770. std::string name = "n/a";
  2771. llama_hparams hparams = {};
  2772. llama_vocab vocab;
  2773. // TODO: should init all tensors to nullptr
  2774. struct ggml_tensor * tok_embd;
  2775. struct ggml_tensor * type_embd;
  2776. struct ggml_tensor * pos_embd;
  2777. struct ggml_tensor * tok_norm;
  2778. struct ggml_tensor * tok_norm_b;
  2779. struct ggml_tensor * output_norm;
  2780. struct ggml_tensor * output_norm_b;
  2781. struct ggml_tensor * output;
  2782. struct ggml_tensor * output_b;
  2783. struct ggml_tensor * output_norm_enc;
  2784. // classifier
  2785. struct ggml_tensor * cls;
  2786. struct ggml_tensor * cls_b;
  2787. struct ggml_tensor * cls_out = nullptr;
  2788. struct ggml_tensor * cls_out_b = nullptr;
  2789. std::vector<llama_layer> layers;
  2790. llama_split_mode split_mode;
  2791. int main_gpu;
  2792. int n_gpu_layers;
  2793. std::vector<std::string> rpc_servers;
  2794. // gguf metadata
  2795. std::unordered_map<std::string, std::string> gguf_kv;
  2796. // layer -> buffer type mapping
  2797. struct layer_buft {
  2798. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2799. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2800. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2801. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2802. ggml_backend_buffer_type_t buft; // everything else
  2803. };
  2804. layer_buft buft_input;
  2805. layer_buft buft_output;
  2806. std::vector<layer_buft> buft_layer;
  2807. // contexts where the model tensors metadata is stored
  2808. std::vector<struct ggml_context *> ctxs;
  2809. // the model memory buffers for the tensor data
  2810. std::vector<ggml_backend_buffer_t> bufs;
  2811. // model memory mapped files
  2812. llama_mmaps mappings;
  2813. // objects representing data potentially being locked in memory
  2814. llama_mlocks mlock_bufs;
  2815. llama_mlocks mlock_mmaps;
  2816. // for quantize-stats only
  2817. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2818. int64_t t_load_us = 0;
  2819. int64_t t_start_us = 0;
  2820. // keep track of loaded lora adapters
  2821. std::set<struct llama_lora_adapter *> lora_adapters;
  2822. ~llama_model() {
  2823. for (struct ggml_context * ctx : ctxs) {
  2824. ggml_free(ctx);
  2825. }
  2826. for (ggml_backend_buffer_t buf : bufs) {
  2827. #ifdef GGML_USE_CUDA
  2828. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2829. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2830. }
  2831. #endif
  2832. ggml_backend_buffer_free(buf);
  2833. }
  2834. while (!lora_adapters.empty()) {
  2835. llama_lora_adapter_free(*lora_adapters.begin());
  2836. }
  2837. }
  2838. };
  2839. struct llama_sbatch_seq {
  2840. int32_t n_seq_id;
  2841. llama_seq_id * seq_id;
  2842. size_t offset;
  2843. size_t length;
  2844. // helper for smoother batch API transition -- can be deprecated in the future
  2845. llama_seq_id all_seq_id; // used if seq_id == NULL
  2846. };
  2847. // sequence-length-aware batch splitting
  2848. struct llama_sbatch {
  2849. // tokens left in this batch
  2850. size_t n_tokens;
  2851. size_t n_embd;
  2852. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2853. // sorted indices into the batch
  2854. std::vector<size_t> ids;
  2855. // batch indices of the output
  2856. std::vector<size_t> out_ids;
  2857. std::vector<llama_sbatch_seq> seq;
  2858. const llama_batch * batch = nullptr;
  2859. // buffers for the ubatch
  2860. std::vector<llama_token> ubatch_token;
  2861. std::vector<float> ubatch_embd;
  2862. std::vector<llama_pos> ubatch_pos;
  2863. std::vector<int32_t> ubatch_n_seq_id;
  2864. std::vector<llama_seq_id *> ubatch_seq_id;
  2865. std::vector<int8_t> ubatch_output;
  2866. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2867. // clear empty sequences
  2868. // the previous ubatch is assumed to be gone,
  2869. // so nothing should refer to values in these sequences anymore.
  2870. for (size_t i = seq.size(); i-- > 0;) {
  2871. if (seq[i].length == 0) {
  2872. seq.pop_back();
  2873. } else {
  2874. break;
  2875. }
  2876. }
  2877. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2878. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2879. ubatch_pos.resize(n_ubatch);
  2880. ubatch_n_seq_id.resize(n_ubatch);
  2881. ubatch_seq_id.resize(n_ubatch);
  2882. ubatch_output.resize(n_ubatch);
  2883. llama_ubatch ubatch = {
  2884. /*equal_seqs =*/ true,
  2885. /*n_tokens =*/ 0,
  2886. /*n_seq_tokens =*/ 0,
  2887. /*n_seqs =*/ 0,
  2888. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2889. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2890. /*pos =*/ ubatch_pos.data(),
  2891. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2892. /*seq_id =*/ ubatch_seq_id.data(),
  2893. /*output =*/ ubatch_output.data(),
  2894. };
  2895. return ubatch;
  2896. }
  2897. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2898. GGML_ASSERT(batch != nullptr);
  2899. GGML_ASSERT(length <= seq.length);
  2900. // Can only add sequences of equal lengths to a batch,
  2901. // otherwise it isn't clear to which sequence a token belongs
  2902. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2903. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2904. // NOTE: loops are separated for cache-friendliness
  2905. if (batch->token) {
  2906. if (ubatch.equal_seqs) {
  2907. for (size_t i = 0; i < length; ++i) {
  2908. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2909. }
  2910. } else {
  2911. // simple split
  2912. ubatch.token = batch->token + seq.offset;
  2913. }
  2914. } else {
  2915. ubatch.token = nullptr;
  2916. }
  2917. if (batch->embd) {
  2918. if (ubatch.equal_seqs) {
  2919. for (size_t i = 0; i < length; ++i) {
  2920. memcpy(
  2921. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2922. batch->embd + n_embd * ids[seq.offset + i],
  2923. n_embd * sizeof(float)
  2924. );
  2925. }
  2926. } else {
  2927. // simple split
  2928. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2929. }
  2930. } else {
  2931. ubatch.embd = nullptr;
  2932. }
  2933. // from here on, the else branches are deprecated;
  2934. // they are helpers for smoother batch API transition
  2935. if (batch->pos) {
  2936. if (ubatch.equal_seqs) {
  2937. for (size_t i = 0; i < length; ++i) {
  2938. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2939. }
  2940. } else {
  2941. // simple split
  2942. ubatch.pos = batch->pos + seq.offset;
  2943. }
  2944. } else {
  2945. for (size_t i = 0; i < length; ++i) {
  2946. llama_pos bi = ids[seq.offset + i];
  2947. ubatch.pos[ubatch.n_tokens + i] = batch->all_pos_0 + (bi * batch->all_pos_1);
  2948. }
  2949. }
  2950. if (ubatch.equal_seqs) {
  2951. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2952. if (seq.seq_id) {
  2953. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2954. } else {
  2955. GGML_ASSERT(seq.n_seq_id == 1);
  2956. ubatch.seq_id[ubatch.n_seqs] = &seq.all_seq_id;
  2957. }
  2958. } else {
  2959. // simple split
  2960. if (batch->n_seq_id) {
  2961. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  2962. } else {
  2963. for (size_t i = 0; i < length; ++i) {
  2964. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  2965. }
  2966. }
  2967. if (batch->seq_id) {
  2968. ubatch.seq_id = batch->seq_id + seq.offset;
  2969. } else {
  2970. for (size_t i = 0; i < length; ++i) {
  2971. ubatch.seq_id[ubatch.n_seqs + i] = &seq.all_seq_id;
  2972. }
  2973. }
  2974. }
  2975. if (logits_all) {
  2976. for (size_t i = 0; i < length; ++i) {
  2977. ubatch.output[ubatch.n_tokens + i] = 1;
  2978. out_ids.push_back(ids[seq.offset + i]);
  2979. }
  2980. } else if (batch->logits) {
  2981. if (ubatch.equal_seqs) {
  2982. for (size_t i = 0; i < length; ++i) {
  2983. size_t id = ids[seq.offset + i];
  2984. int8_t is_output = batch->logits[id];
  2985. ubatch.output[ubatch.n_tokens + i] = is_output;
  2986. if (is_output) { out_ids.push_back(id); }
  2987. }
  2988. } else {
  2989. // simple split
  2990. ubatch.output = batch->logits + seq.offset;
  2991. for (size_t i = 0; i < length; ++i) {
  2992. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  2993. }
  2994. }
  2995. } else {
  2996. // only get last output
  2997. for (size_t i = 0; i < length; ++i) {
  2998. size_t id = ids[seq.offset + i];
  2999. int8_t is_last = id == ids.size() - 1;
  3000. ubatch.output[ubatch.n_tokens + i] = is_last;
  3001. if (is_last) { out_ids.push_back(id); }
  3002. }
  3003. }
  3004. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  3005. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  3006. }
  3007. ubatch.n_tokens += length;
  3008. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  3009. seq.offset += length;
  3010. seq.length -= length;
  3011. n_tokens -= length;
  3012. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  3013. }
  3014. // simple split, unknown number of sequences of unequal lengths
  3015. llama_ubatch split_simple(size_t n_ubatch) {
  3016. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3017. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3018. ubatch.equal_seqs = false;
  3019. if (!seq.empty()) {
  3020. llama_sbatch_seq & s = seq[0];
  3021. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3022. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  3023. add_seq_to_ubatch(ubatch, s, length);
  3024. }
  3025. return ubatch;
  3026. }
  3027. // make batches of equal-length sequences
  3028. llama_ubatch split_equal(size_t n_ubatch) {
  3029. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3030. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3031. if (!seq.empty()) {
  3032. size_t length = 0;
  3033. size_t n_tokens_in_ubatch = 0;
  3034. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  3035. // smallest first, because it's easier to split this way;
  3036. // starting from the end to pop in constant time.
  3037. for (size_t i = seq.size(); i-- > 0;) {
  3038. llama_sbatch_seq & s = seq[i];
  3039. GGML_ASSERT(s.length > 0);
  3040. if (length == 0) {
  3041. length = s.length < n_ubatch ? s.length : n_ubatch;
  3042. }
  3043. add_seq_to_ubatch(ubatch, s, length);
  3044. n_tokens_in_ubatch += length;
  3045. // shared prompts can't be mixed with any of their sequences,
  3046. // so it's safer to compute them in their own ubatch
  3047. if (s.n_seq_id > 1) { break; }
  3048. // stop when there isn't enough space for another sequence
  3049. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  3050. }
  3051. }
  3052. return ubatch;
  3053. }
  3054. // sequence-wise split
  3055. llama_ubatch split_seq(size_t n_ubatch) {
  3056. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  3057. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  3058. if (!seq.empty()) {
  3059. llama_sbatch_seq & s = seq[seq.size() - 1];
  3060. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  3061. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  3062. add_seq_to_ubatch(ubatch, s, length);
  3063. }
  3064. return ubatch;
  3065. }
  3066. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  3067. GGML_ASSERT(batch.n_tokens >= 0);
  3068. this->batch = &batch;
  3069. this->n_embd = n_embd;
  3070. this->logits_all = logits_all;
  3071. n_tokens = batch.n_tokens;
  3072. ids.resize(n_tokens);
  3073. out_ids.clear();
  3074. // TODO: reserve out_ids and seq
  3075. for (size_t i = 0; i < n_tokens; ++i) {
  3076. ids[i] = i;
  3077. }
  3078. if (simple_split) {
  3079. seq.resize(1);
  3080. llama_sbatch_seq & s = seq[0];
  3081. s.n_seq_id = 0;
  3082. s.seq_id = nullptr;
  3083. s.offset = 0;
  3084. s.length = n_tokens;
  3085. s.all_seq_id = batch.all_seq_id;
  3086. return;
  3087. }
  3088. std::sort(ids.begin(), ids.end(),
  3089. [&batch](size_t a, size_t b) {
  3090. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  3091. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  3092. // sort by seq_id, then by pos
  3093. if (n_seq_a == n_seq_b) {
  3094. if (batch.seq_id) {
  3095. for (int32_t i = 0; i < n_seq_a; ++i) {
  3096. llama_seq_id seq_id_a = batch.seq_id[a][i];
  3097. llama_seq_id seq_id_b = batch.seq_id[b][i];
  3098. // smaller seq_ids go first
  3099. if (seq_id_a != seq_id_b) {
  3100. return seq_id_a < seq_id_b;
  3101. }
  3102. }
  3103. }
  3104. // when all else is equal, sort by pos
  3105. if (batch.pos) {
  3106. return batch.pos[a] < batch.pos[b];
  3107. }
  3108. // no pos, sort by id (assuming batch.all_pos_1 is positive)
  3109. return a < b;
  3110. }
  3111. // shared prompts go first
  3112. return n_seq_a > n_seq_b;
  3113. }
  3114. );
  3115. // init seq
  3116. llama_sbatch_seq * last_seq = nullptr;
  3117. if (batch.n_seq_id != nullptr && batch.seq_id != nullptr) {
  3118. for (size_t i = 0; i < n_tokens; ++i) {
  3119. const size_t bi = ids[i];
  3120. const int32_t n_seqs = batch.n_seq_id[bi];
  3121. llama_seq_id * seq_ids = batch.seq_id[bi];
  3122. if (last_seq != nullptr) {
  3123. bool same = n_seqs == last_seq->n_seq_id;
  3124. for (int32_t j = 0; same && j < n_seqs; ++j) {
  3125. if (seq_ids[j] != last_seq->seq_id[j]) {
  3126. same = false;
  3127. }
  3128. }
  3129. if (same) {
  3130. last_seq->length += 1;
  3131. continue;
  3132. }
  3133. }
  3134. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1, batch.all_seq_id};
  3135. seq.push_back(new_seq);
  3136. last_seq = &seq.back();
  3137. }
  3138. } else {
  3139. llama_sbatch_seq new_seq = {1, nullptr, 0, n_tokens, batch.all_seq_id};
  3140. seq.push_back(new_seq);
  3141. }
  3142. // keep shared prompts first at the end, then sort by length descending.
  3143. std::sort(seq.begin(), seq.end(),
  3144. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  3145. if (a.n_seq_id == b.n_seq_id) {
  3146. return a.length > b.length;
  3147. }
  3148. return a.n_seq_id < b.n_seq_id;
  3149. }
  3150. );
  3151. }
  3152. };
  3153. struct llama_context {
  3154. llama_context(const llama_model & model)
  3155. : model(model)
  3156. , t_start_us(model.t_start_us)
  3157. , t_load_us(model.t_load_us) {}
  3158. ~llama_context() {
  3159. ggml_backend_sched_free(sched);
  3160. for (ggml_backend_t backend : backends) {
  3161. ggml_backend_free(backend);
  3162. }
  3163. ggml_backend_buffer_free(buf_output);
  3164. }
  3165. const struct llama_model & model;
  3166. struct llama_cparams cparams;
  3167. struct llama_sbatch sbatch;
  3168. struct llama_kv_cache kv_self;
  3169. struct llama_control_vector cvec;
  3170. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  3171. std::vector<ggml_backend_t> backends;
  3172. #ifdef GGML_USE_METAL
  3173. ggml_backend_t backend_metal = nullptr;
  3174. #endif
  3175. #ifdef GGML_USE_BLAS
  3176. ggml_backend_t backend_blas = nullptr;
  3177. #endif
  3178. ggml_backend_t backend_cpu = nullptr;
  3179. ggml_threadpool_t threadpool = nullptr;
  3180. ggml_threadpool_t threadpool_batch = nullptr;
  3181. bool has_evaluated_once = false;
  3182. mutable int64_t t_start_us;
  3183. mutable int64_t t_load_us;
  3184. mutable int64_t t_p_eval_us = 0;
  3185. mutable int64_t t_eval_us = 0;
  3186. mutable int64_t t_compute_start_us = 0;
  3187. mutable int64_t n_queued_tokens = 0;
  3188. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3189. mutable int32_t n_eval = 0; // number of eval calls
  3190. // host buffer for the model output (logits and embeddings)
  3191. ggml_backend_buffer_t buf_output = nullptr;
  3192. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3193. size_t logits_size = 0; // capacity (of floats) for logits
  3194. float * logits = nullptr;
  3195. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3196. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3197. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3198. bool logits_all = false;
  3199. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3200. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3201. size_t embd_size = 0; // capacity (of floats) for embeddings
  3202. float * embd = nullptr;
  3203. // sequence embeddings output (map of [n_embd] vectors)
  3204. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3205. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3206. // whether we are computing encoder output or decoder output
  3207. bool is_encoding = false;
  3208. // output of the encoder part of the encoder-decoder models
  3209. std::vector<float> embd_enc;
  3210. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3211. // memory buffers used to evaluate the model
  3212. std::vector<uint8_t> buf_compute_meta;
  3213. ggml_backend_sched_t sched = nullptr;
  3214. ggml_abort_callback abort_callback = nullptr;
  3215. void * abort_callback_data = nullptr;
  3216. // input tensors
  3217. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3218. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3219. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3220. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3221. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3222. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3223. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3224. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3225. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3226. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3227. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3228. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3229. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3230. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3231. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3232. struct ggml_tensor * inp_cross_attn_state; // F32 [4, n_embd, 1061]
  3233. };
  3234. struct llama_lora_weight {
  3235. struct ggml_tensor * a = nullptr;
  3236. struct ggml_tensor * b = nullptr;
  3237. llama_lora_weight() = default;
  3238. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3239. };
  3240. struct llama_lora_adapter {
  3241. struct llama_model * base_model;
  3242. // map tensor name to lora_a_b
  3243. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3244. std::vector<struct ggml_context *> ctxs;
  3245. std::vector<ggml_backend_buffer_t> bufs;
  3246. float alpha;
  3247. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3248. base_model->lora_adapters.insert(this);
  3249. }
  3250. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3251. std::string name(w->name);
  3252. auto pos = ab_map.find(name);
  3253. if (ab_map.find(name) != ab_map.end()) {
  3254. return &pos->second;
  3255. }
  3256. return nullptr;
  3257. }
  3258. ~llama_lora_adapter() {
  3259. for (struct ggml_context * ctx : ctxs) {
  3260. ggml_free(ctx);
  3261. }
  3262. for (ggml_backend_buffer_t buf : bufs) {
  3263. ggml_backend_buffer_free(buf);
  3264. }
  3265. auto pos = base_model->lora_adapters.find(this);
  3266. if (pos != base_model->lora_adapters.end()) {
  3267. base_model->lora_adapters.erase(pos);
  3268. }
  3269. }
  3270. };
  3271. static size_t llama_get_device_count(const llama_model & model) {
  3272. size_t count = 1;
  3273. #if defined(GGML_USE_CUDA)
  3274. count = ggml_backend_cuda_get_device_count();
  3275. #elif defined(GGML_USE_SYCL)
  3276. count = ggml_backend_sycl_get_device_count();
  3277. #elif defined(GGML_USE_VULKAN)
  3278. count = ggml_backend_vk_get_device_count();
  3279. #elif defined(GGML_USE_CANN)
  3280. return ggml_backend_cann_get_device_count();
  3281. #endif
  3282. #if defined(GGML_USE_RPC)
  3283. count += model.rpc_servers.size();
  3284. #endif
  3285. return count;
  3286. GGML_UNUSED(model);
  3287. }
  3288. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  3289. ggml_backend_buffer_type_t buft = nullptr;
  3290. #ifdef GGML_USE_RPC
  3291. int rpc_count = (int)model.rpc_servers.size();
  3292. #else
  3293. int rpc_count = 0;
  3294. #endif
  3295. int local_gpu = gpu - rpc_count;
  3296. #if defined(GGML_USE_RPC)
  3297. if (gpu < rpc_count) {
  3298. const char * endpoint = model.rpc_servers[gpu].c_str();
  3299. return ggml_backend_rpc_buffer_type(endpoint);
  3300. }
  3301. #endif
  3302. #if defined(GGML_USE_METAL)
  3303. buft = ggml_backend_metal_buffer_type();
  3304. #elif defined(GGML_USE_CUDA)
  3305. buft = ggml_backend_cuda_buffer_type(local_gpu);
  3306. #elif defined(GGML_USE_VULKAN)
  3307. buft = ggml_backend_vk_buffer_type(local_gpu);
  3308. #elif defined(GGML_USE_SYCL)
  3309. buft = ggml_backend_sycl_buffer_type(local_gpu);
  3310. #elif defined(GGML_USE_KOMPUTE)
  3311. buft = ggml_backend_kompute_buffer_type(local_gpu);
  3312. if (buft == nullptr) {
  3313. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, local_gpu);
  3314. }
  3315. #elif defined(GGML_USE_CANN)
  3316. buft = ggml_backend_cann_buffer_type(local_gpu);
  3317. #endif
  3318. if (buft == nullptr) {
  3319. buft = llama_default_buffer_type_cpu(true);
  3320. }
  3321. return buft;
  3322. GGML_UNUSED(model);
  3323. GGML_UNUSED(local_gpu);
  3324. }
  3325. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  3326. ggml_backend_buffer_type_t buft = nullptr;
  3327. #ifdef GGML_USE_CUDA
  3328. if (ggml_backend_cuda_get_device_count() > 1) {
  3329. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  3330. }
  3331. #endif
  3332. #ifdef GGML_USE_SYCL
  3333. if (ggml_backend_sycl_get_device_count() > 1) {
  3334. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  3335. }
  3336. #endif
  3337. if (buft == nullptr) {
  3338. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  3339. }
  3340. return buft;
  3341. GGML_UNUSED(tensor_split);
  3342. }
  3343. static size_t llama_get_device_memory(const llama_model & model, int device) {
  3344. #ifdef GGML_USE_RPC
  3345. int rpc_count = (int)model.rpc_servers.size();
  3346. #else
  3347. int rpc_count = 0;
  3348. #endif
  3349. int local_device = device - rpc_count;
  3350. #if defined(GGML_USE_RPC)
  3351. if (device < rpc_count) {
  3352. size_t total;
  3353. size_t free;
  3354. const char * endpoint = model.rpc_servers[device].c_str();
  3355. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  3356. return free;
  3357. }
  3358. #endif
  3359. #if defined(GGML_USE_CUDA)
  3360. size_t total;
  3361. size_t free;
  3362. ggml_backend_cuda_get_device_memory(local_device, &free, &total);
  3363. return free;
  3364. #elif defined(GGML_USE_SYCL)
  3365. size_t total;
  3366. size_t free;
  3367. ggml_backend_sycl_get_device_memory(local_device, &free, &total);
  3368. return free;
  3369. #elif defined(GGML_USE_VULKAN)
  3370. size_t total;
  3371. size_t free;
  3372. ggml_backend_vk_get_device_memory(local_device, &free, &total);
  3373. return free;
  3374. #elif defined(GGML_USE_CANN)
  3375. size_t total;
  3376. size_t free;
  3377. ggml_backend_cann_get_device_memory(local_device, &free, &total);
  3378. return free;
  3379. #else
  3380. return 1;
  3381. #endif
  3382. GGML_UNUSED(model);
  3383. GGML_UNUSED(local_device);
  3384. }
  3385. //
  3386. // kv cache helpers
  3387. //
  3388. static bool llama_kv_cache_init(
  3389. struct llama_kv_cache & cache,
  3390. const llama_context * ctx,
  3391. ggml_type type_k,
  3392. ggml_type type_v,
  3393. uint32_t kv_size,
  3394. bool offload) {
  3395. const llama_model & model = ctx->model;
  3396. const llama_cparams & cparams = ctx->cparams;
  3397. const struct llama_hparams & hparams = model.hparams;
  3398. const int64_t n_layer = hparams.n_layer;
  3399. cache.has_shift = false;
  3400. cache.recurrent = llama_model_is_recurrent(&model);
  3401. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3402. cache.head = 0;
  3403. cache.size = kv_size;
  3404. cache.used = 0;
  3405. cache.type_k = type_k;
  3406. cache.type_v = type_v;
  3407. cache.cells.clear();
  3408. cache.cells.resize(kv_size);
  3409. // count used buffer types
  3410. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3411. if (offload) {
  3412. for (int64_t i = 0; i < n_layer; ++i) {
  3413. buft_layer_count[model.buft_layer[i].buft]++;
  3414. }
  3415. } else {
  3416. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  3417. }
  3418. // create a context for each buffer type
  3419. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3420. for (auto & it : buft_layer_count) {
  3421. int n_layers = it.second;
  3422. struct ggml_init_params params = {
  3423. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  3424. /*.mem_buffer =*/ NULL,
  3425. /*.no_alloc =*/ true,
  3426. };
  3427. ggml_context * ctx = ggml_init(params);
  3428. if (!ctx) {
  3429. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  3430. return false;
  3431. }
  3432. ctx_map[it.first] = ctx;
  3433. cache.ctxs.push_back(ctx);
  3434. }
  3435. cache.k_l.reserve(n_layer);
  3436. cache.v_l.reserve(n_layer);
  3437. for (int i = 0; i < (int) n_layer; i++) {
  3438. // for cross attention layers
  3439. if (model.arch == LLM_ARCH_MLLAMA && hparams.cross_attention_layers(i)) {
  3440. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3441. ggml_tensor * k = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_k, 6404, hparams.n_head_kv(i));
  3442. ggml_tensor * v = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, hparams.n_embd_head_v, 6404, hparams.n_head_kv(i));
  3443. ggml_format_name(k, "cache_k_l%d", i);
  3444. ggml_format_name(v, "cache_v_l%d", i);
  3445. cache.k_l.push_back(k);
  3446. cache.v_l.push_back(v);
  3447. continue;
  3448. }
  3449. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3450. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3451. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3452. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3453. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3454. ggml_format_name(k, "cache_k_l%d", i);
  3455. ggml_format_name(v, "cache_v_l%d", i);
  3456. cache.k_l.push_back(k);
  3457. cache.v_l.push_back(v);
  3458. }
  3459. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3460. for (auto it : ctx_map) {
  3461. ggml_backend_buffer_type_t buft = it.first;
  3462. ggml_context * ctx = it.second;
  3463. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3464. if (!buf) {
  3465. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3466. return false;
  3467. }
  3468. ggml_backend_buffer_clear(buf, 0);
  3469. 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);
  3470. cache.bufs.push_back(buf);
  3471. }
  3472. return true;
  3473. }
  3474. // find an empty slot of size "n_tokens" in the cache
  3475. // updates the cache head
  3476. // Note: On success, it's important that cache.head points
  3477. // to the first cell of the slot.
  3478. static bool llama_kv_cache_find_slot(
  3479. struct llama_kv_cache & cache,
  3480. const struct llama_ubatch & batch) {
  3481. const uint32_t n_tokens = batch.n_tokens;
  3482. const uint32_t n_seqs = batch.n_seqs;
  3483. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3484. if (cache.recurrent) {
  3485. // For recurrent state architectures (like Mamba or RWKV),
  3486. // each cache cell can store the state for a whole sequence.
  3487. // A slot should be always be contiguous.
  3488. // can only process batches with an equal number of new tokens in each sequence
  3489. GGML_ASSERT(batch.equal_seqs);
  3490. int32_t min = cache.size - 1;
  3491. int32_t max = 0;
  3492. // everything should fit if all seq_ids are smaller than the max
  3493. for (uint32_t s = 0; s < n_seqs; ++s) {
  3494. const uint32_t n_seq_id = batch.n_seq_id[s];
  3495. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3496. const llama_seq_id seq_id = batch.seq_id[s][j];
  3497. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3498. // too big seq_id
  3499. // TODO: would it be possible to resize the cache instead?
  3500. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3501. return false;
  3502. }
  3503. if (j > 0) {
  3504. llama_kv_cell & seq = cache.cells[seq_id];
  3505. if (seq.tail >= 0) {
  3506. llama_kv_cell & cell = cache.cells[seq.tail];
  3507. // clear cells from seq_ids that become shared
  3508. // (should not normally happen, but let's handle it anyway)
  3509. cell.seq_id.erase(seq_id);
  3510. seq.tail = -1;
  3511. if (cell.seq_id.empty()) {
  3512. cell.pos = -1;
  3513. cell.src = -1;
  3514. cache.used -= 1;
  3515. }
  3516. }
  3517. }
  3518. }
  3519. }
  3520. #ifndef NDEBUG
  3521. {
  3522. std::vector<int32_t> tails_verif;
  3523. tails_verif.assign(cache.size, -1);
  3524. for (uint32_t i = 0; i < cache.size; ++i) {
  3525. llama_kv_cell & cell = cache.cells[i];
  3526. for (llama_seq_id seq_id : cell.seq_id) {
  3527. if (tails_verif[seq_id] != -1) {
  3528. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3529. }
  3530. tails_verif[seq_id] = i;
  3531. }
  3532. }
  3533. for (uint32_t i = 0; i < cache.size; ++i) {
  3534. if (tails_verif[i] != cache.cells[i].tail) {
  3535. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3536. }
  3537. }
  3538. }
  3539. #endif
  3540. // find next empty cell
  3541. uint32_t next_empty_cell = cache.head;
  3542. for (uint32_t i = 0; i < cache.size; ++i) {
  3543. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3544. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3545. if (cell.is_empty()) { break; }
  3546. next_empty_cell += 1;
  3547. }
  3548. // find usable cell range
  3549. for (uint32_t s = 0; s < n_seqs; ++s) {
  3550. const llama_seq_id seq_id = batch.seq_id[s][0];
  3551. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3552. bool has_cell = false;
  3553. if (seq_meta.tail >= 0) {
  3554. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3555. GGML_ASSERT(cell.has_seq_id(seq_id));
  3556. // does this seq_id "own" the cell?
  3557. if (cell.seq_id.size() == 1) { has_cell = true; }
  3558. }
  3559. if (!has_cell) {
  3560. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3561. GGML_ASSERT(empty_cell.is_empty());
  3562. // copy old tail into the empty cell
  3563. if (seq_meta.tail >= 0) {
  3564. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3565. empty_cell.pos = orig_cell.pos;
  3566. empty_cell.src = orig_cell.src;
  3567. orig_cell.seq_id.erase(seq_id);
  3568. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3569. }
  3570. seq_meta.tail = next_empty_cell;
  3571. // find next empty cell
  3572. if (s + 1 < n_seqs) {
  3573. next_empty_cell += 1;
  3574. for (uint32_t i = 0; i < cache.size; ++i) {
  3575. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3576. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3577. if (cell.is_empty()) { break; }
  3578. next_empty_cell += 1;
  3579. }
  3580. }
  3581. }
  3582. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3583. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3584. }
  3585. // gather and re-order
  3586. for (uint32_t s = 0; s < n_seqs; ++s) {
  3587. int32_t dst_id = s + min;
  3588. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3589. if (dst_id != src_id) {
  3590. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3591. llama_kv_cell & src_cell = cache.cells[src_id];
  3592. std::swap(dst_cell.pos, src_cell.pos);
  3593. std::swap(dst_cell.src, src_cell.src);
  3594. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3595. // swap tails (assuming they NEVER overlap)
  3596. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3597. cache.cells[seq_id].tail = src_id;
  3598. }
  3599. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3600. cache.cells[seq_id].tail = dst_id;
  3601. }
  3602. }
  3603. }
  3604. // update the pos of the used seqs
  3605. for (uint32_t s = 0; s < n_seqs; ++s) {
  3606. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3607. int32_t cell_id = s + min;
  3608. llama_kv_cell & cell = cache.cells[cell_id];
  3609. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3610. // What should happen when the pos backtracks or skips a value?
  3611. // Clearing the state mid-batch would require special-casing which isn't done.
  3612. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3613. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3614. }
  3615. cell.pos = last_pos;
  3616. cell.seq_id.clear();
  3617. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3618. const llama_seq_id seq_id = batch.seq_id[s][j];
  3619. cell.seq_id.insert(seq_id);
  3620. cache.cells[seq_id].tail = cell_id;
  3621. }
  3622. }
  3623. // allow getting the range of used cells, from head to head + n
  3624. cache.head = min;
  3625. cache.n = max - min + 1;
  3626. // sanity check
  3627. return cache.n >= n_seqs;
  3628. }
  3629. // otherwise, one cell per token.
  3630. if (n_tokens > cache.size) {
  3631. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3632. return false;
  3633. }
  3634. uint32_t n_tested = 0;
  3635. while (true) {
  3636. if (cache.head + n_tokens > cache.size) {
  3637. n_tested += cache.size - cache.head;
  3638. cache.head = 0;
  3639. continue;
  3640. }
  3641. bool found = true;
  3642. for (uint32_t i = 0; i < n_tokens; i++) {
  3643. if (cache.cells[cache.head + i].pos >= 0) {
  3644. found = false;
  3645. cache.head += i + 1;
  3646. n_tested += i + 1;
  3647. break;
  3648. }
  3649. }
  3650. if (found) {
  3651. break;
  3652. }
  3653. if (n_tested >= cache.size) {
  3654. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3655. return false;
  3656. }
  3657. }
  3658. for (uint32_t s = 0; s < n_seqs; s++) {
  3659. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3660. uint32_t k = s*n_seq_tokens + i;
  3661. cache.cells[cache.head + k].pos = batch.pos[k];
  3662. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3663. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3664. }
  3665. }
  3666. }
  3667. cache.used += n_tokens;
  3668. return true;
  3669. }
  3670. // find how many cells are currently in use
  3671. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3672. for (uint32_t i = cache.size; i > 0; --i) {
  3673. const llama_kv_cell & cell = cache.cells[i - 1];
  3674. if (cell.pos >= 0 && !cell.is_empty()) {
  3675. return i;
  3676. }
  3677. }
  3678. return 0;
  3679. }
  3680. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3681. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3682. cache.cells[i].pos = -1;
  3683. cache.cells[i].seq_id.clear();
  3684. cache.cells[i].src = -1;
  3685. cache.cells[i].tail = -1;
  3686. }
  3687. cache.head = 0;
  3688. cache.used = 0;
  3689. for (auto & buf : cache.bufs) {
  3690. ggml_backend_buffer_clear(buf, 0);
  3691. }
  3692. }
  3693. static bool llama_kv_cache_seq_rm(
  3694. struct llama_kv_cache & cache,
  3695. llama_seq_id seq_id,
  3696. llama_pos p0,
  3697. llama_pos p1) {
  3698. uint32_t new_head = cache.size;
  3699. if (p0 < 0) p0 = 0;
  3700. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3701. // models like Mamba or RWKV can't have a state partially erased
  3702. if (cache.recurrent) {
  3703. if (seq_id >= (int64_t) cache.size) {
  3704. // could be fatal
  3705. return false;
  3706. }
  3707. if (0 <= seq_id) {
  3708. int32_t & tail_id = cache.cells[seq_id].tail;
  3709. if (tail_id >= 0) {
  3710. const llama_kv_cell & cell = cache.cells[tail_id];
  3711. // partial intersection is invalid
  3712. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3713. return false;
  3714. }
  3715. // invalidate tails which will be cleared
  3716. if (p0 <= cell.pos && cell.pos < p1) {
  3717. tail_id = -1;
  3718. }
  3719. }
  3720. } else {
  3721. // seq_id is negative, then the range should include everything or nothing
  3722. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3723. return false;
  3724. }
  3725. }
  3726. }
  3727. for (uint32_t i = 0; i < cache.size; ++i) {
  3728. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3729. if (seq_id < 0) {
  3730. cache.cells[i].seq_id.clear();
  3731. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3732. cache.cells[i].seq_id.erase(seq_id);
  3733. } else {
  3734. continue;
  3735. }
  3736. if (cache.cells[i].is_empty()) {
  3737. // keep count of the number of used cells
  3738. if (cache.cells[i].pos >= 0) cache.used--;
  3739. cache.cells[i].pos = -1;
  3740. cache.cells[i].src = -1;
  3741. if (new_head == cache.size) new_head = i;
  3742. }
  3743. }
  3744. }
  3745. // If we freed up a slot, set head to it so searching can start there.
  3746. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3747. return true;
  3748. }
  3749. static void llama_kv_cache_seq_cp(
  3750. struct llama_kv_cache & cache,
  3751. llama_seq_id seq_id_src,
  3752. llama_seq_id seq_id_dst,
  3753. llama_pos p0,
  3754. llama_pos p1) {
  3755. if (p0 < 0) p0 = 0;
  3756. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3757. if (cache.recurrent) {
  3758. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3759. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3760. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3761. if (tail_dst.tail >= 0) {
  3762. // clear destination seq_id if it wasn't empty
  3763. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3764. cell_dst.seq_id.erase(seq_id_dst);
  3765. tail_dst.tail = -1;
  3766. if (cell_dst.seq_id.empty()) {
  3767. cell_dst.pos = -1;
  3768. cell_dst.delta = -1;
  3769. cell_dst.src = -1;
  3770. cache.used -= 1;
  3771. }
  3772. }
  3773. if (tail_src.tail >= 0) {
  3774. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3775. cell_src.seq_id.insert(seq_id_dst);
  3776. tail_dst.tail = tail_src.tail;
  3777. }
  3778. }
  3779. return;
  3780. }
  3781. // otherwise, this is the KV cache of a Transformer-like model
  3782. cache.head = 0;
  3783. for (uint32_t i = 0; i < cache.size; ++i) {
  3784. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3785. cache.cells[i].seq_id.insert(seq_id_dst);
  3786. }
  3787. }
  3788. }
  3789. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3790. uint32_t new_head = cache.size;
  3791. for (uint32_t i = 0; i < cache.size; ++i) {
  3792. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3793. cache.cells[i].tail = -1;
  3794. }
  3795. if (!cache.cells[i].has_seq_id(seq_id)) {
  3796. if (cache.cells[i].pos >= 0) cache.used--;
  3797. cache.cells[i].pos = -1;
  3798. cache.cells[i].src = -1;
  3799. cache.cells[i].seq_id.clear();
  3800. if (new_head == cache.size) new_head = i;
  3801. } else {
  3802. cache.cells[i].seq_id.clear();
  3803. cache.cells[i].seq_id.insert(seq_id);
  3804. }
  3805. }
  3806. // If we freed up a slot, set head to it so searching can start there.
  3807. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3808. }
  3809. static void llama_kv_cache_seq_add(
  3810. struct llama_kv_cache & cache,
  3811. llama_seq_id seq_id,
  3812. llama_pos p0,
  3813. llama_pos p1,
  3814. llama_pos delta) {
  3815. uint32_t new_head = cache.size;
  3816. if (p0 < 0) p0 = 0;
  3817. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3818. // If there is no range then return early to avoid looping over the cache.
  3819. if (p0 == p1) return;
  3820. if (cache.recurrent) {
  3821. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3822. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3823. const int32_t tail_id = cache.cells[seq_id].tail;
  3824. if (tail_id >= 0) {
  3825. llama_kv_cell & cell = cache.cells[tail_id];
  3826. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3827. cell.pos += delta;
  3828. }
  3829. }
  3830. }
  3831. return;
  3832. }
  3833. for (uint32_t i = 0; i < cache.size; ++i) {
  3834. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3835. cache.has_shift = true;
  3836. cache.cells[i].pos += delta;
  3837. cache.cells[i].delta += delta;
  3838. if (cache.cells[i].pos < 0) {
  3839. if (!cache.cells[i].is_empty()) {
  3840. cache.used--;
  3841. }
  3842. cache.cells[i].pos = -1;
  3843. cache.cells[i].seq_id.clear();
  3844. if (new_head == cache.size) {
  3845. new_head = i;
  3846. }
  3847. }
  3848. }
  3849. }
  3850. // If we freed up a slot, set head to it so searching can start there.
  3851. // Otherwise we just start the next search from the beginning.
  3852. cache.head = new_head != cache.size ? new_head : 0;
  3853. }
  3854. static void llama_kv_cache_seq_div(
  3855. struct llama_kv_cache & cache,
  3856. llama_seq_id seq_id,
  3857. llama_pos p0,
  3858. llama_pos p1,
  3859. int d) {
  3860. if (p0 < 0) p0 = 0;
  3861. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3862. // If there is no range then return early to avoid looping over the cache.
  3863. if (p0 == p1) return;
  3864. if (cache.recurrent) {
  3865. // for Mamba-like or RWKV models, only the pos needs to be changed
  3866. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3867. const int32_t tail_id = cache.cells[seq_id].tail;
  3868. if (tail_id >= 0) {
  3869. llama_kv_cell & cell = cache.cells[tail_id];
  3870. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3871. cell.pos /= d;
  3872. }
  3873. }
  3874. }
  3875. return;
  3876. }
  3877. for (uint32_t i = 0; i < cache.size; ++i) {
  3878. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3879. cache.has_shift = true;
  3880. {
  3881. llama_pos p_old = cache.cells[i].pos;
  3882. cache.cells[i].pos /= d;
  3883. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3884. }
  3885. }
  3886. }
  3887. }
  3888. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3889. llama_pos result = 0;
  3890. for (uint32_t i = 0; i < cache.size; ++i) {
  3891. if (cache.cells[i].has_seq_id(seq_id)) {
  3892. result = std::max(result, cache.cells[i].pos);
  3893. }
  3894. }
  3895. return result;
  3896. }
  3897. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3898. if (!cache.recurrent) {
  3899. cache.do_defrag = true;
  3900. }
  3901. }
  3902. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3903. // the FA kernels require padding to avoid extra runtime boundary checks
  3904. return cparams.flash_attn ? 256u : 32u;
  3905. }
  3906. //
  3907. // model loading and saving
  3908. //
  3909. enum llama_fver {
  3910. GGUF_FILE_VERSION_V1 = 1,
  3911. GGUF_FILE_VERSION_V2 = 2,
  3912. GGUF_FILE_VERSION_V3 = 3,
  3913. };
  3914. static const char * llama_file_version_name(llama_fver version) {
  3915. switch (version) {
  3916. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3917. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3918. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3919. }
  3920. return "unknown";
  3921. }
  3922. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3923. char buf[256];
  3924. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3925. for (size_t i = 1; i < ne.size(); i++) {
  3926. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3927. }
  3928. return buf;
  3929. }
  3930. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3931. char buf[256];
  3932. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3933. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3934. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3935. }
  3936. return buf;
  3937. }
  3938. namespace GGUFMeta {
  3939. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3940. struct GKV_Base_Type {
  3941. static constexpr gguf_type gt = gt_;
  3942. static T getter(const gguf_context * ctx, const int kid) {
  3943. return gfun(ctx, kid);
  3944. }
  3945. };
  3946. template<typename T> struct GKV_Base;
  3947. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3948. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3949. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3950. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3951. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3952. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3953. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3954. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3955. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3956. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3957. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3958. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3959. template<> struct GKV_Base<std::string> {
  3960. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3961. static std::string getter(const gguf_context * ctx, const int kid) {
  3962. return gguf_get_val_str(ctx, kid);
  3963. }
  3964. };
  3965. struct ArrayInfo {
  3966. const gguf_type gt;
  3967. const size_t length;
  3968. const void * data;
  3969. };
  3970. template<> struct GKV_Base<ArrayInfo> {
  3971. public:
  3972. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3973. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3974. return ArrayInfo {
  3975. gguf_get_arr_type(ctx, k),
  3976. size_t(gguf_get_arr_n(ctx, k)),
  3977. gguf_get_arr_data(ctx, k),
  3978. };
  3979. }
  3980. };
  3981. template<typename T>
  3982. class GKV : public GKV_Base<T> {
  3983. GKV() = delete;
  3984. public:
  3985. static T get_kv(const gguf_context * ctx, const int k) {
  3986. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3987. if (kt != GKV::gt) {
  3988. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3989. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3990. }
  3991. return GKV::getter(ctx, k);
  3992. }
  3993. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3994. switch (ty) {
  3995. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3996. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3997. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3998. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3999. }
  4000. return "unknown";
  4001. }
  4002. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  4003. if (!ovrd) { return false; }
  4004. if (ovrd->tag == expected_type) {
  4005. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  4006. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  4007. switch (ovrd->tag) {
  4008. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  4009. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  4010. } break;
  4011. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  4012. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  4013. } break;
  4014. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  4015. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  4016. } break;
  4017. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  4018. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  4019. } break;
  4020. default:
  4021. // Shouldn't be possible to end up here, but just in case...
  4022. throw std::runtime_error(
  4023. format("Unsupported attempt to override %s type for metadata key %s\n",
  4024. override_type_to_str(ovrd->tag), ovrd->key));
  4025. }
  4026. return true;
  4027. }
  4028. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  4029. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  4030. return false;
  4031. }
  4032. template<typename OT>
  4033. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  4034. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4035. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  4036. target = ovrd->val_bool;
  4037. return true;
  4038. }
  4039. return false;
  4040. }
  4041. template<typename OT>
  4042. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  4043. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  4044. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  4045. target = ovrd->val_i64;
  4046. return true;
  4047. }
  4048. return false;
  4049. }
  4050. template<typename OT>
  4051. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  4052. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4053. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  4054. target = ovrd->val_f64;
  4055. return true;
  4056. }
  4057. return false;
  4058. }
  4059. template<typename OT>
  4060. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  4061. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  4062. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  4063. target = ovrd->val_str;
  4064. return true;
  4065. }
  4066. return false;
  4067. }
  4068. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4069. if (try_override<T>(target, ovrd)) {
  4070. return true;
  4071. }
  4072. if (k < 0) { return false; }
  4073. target = get_kv(ctx, k);
  4074. return true;
  4075. }
  4076. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4077. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  4078. }
  4079. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  4080. return set(ctx, key.c_str(), target, ovrd);
  4081. }
  4082. };
  4083. }
  4084. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  4085. static size_t llama_model_max_nodes(const llama_model & model) {
  4086. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  4087. }
  4088. struct llama_model_loader {
  4089. int n_kv = 0;
  4090. int n_tensors = 0;
  4091. int n_created = 0;
  4092. int64_t n_elements = 0;
  4093. size_t n_bytes = 0;
  4094. bool use_mmap = false;
  4095. bool check_tensors;
  4096. llama_files files;
  4097. llama_ftype ftype;
  4098. llama_fver fver;
  4099. llama_mmaps mappings;
  4100. // Holds information on a model weight
  4101. struct llama_tensor_weight {
  4102. uint16_t idx; // source file index
  4103. size_t offs; // tensor data offset in the original file
  4104. ggml_tensor * tensor;
  4105. 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) {
  4106. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  4107. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  4108. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  4109. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  4110. }
  4111. }
  4112. };
  4113. std::vector<llama_tensor_weight> weights;
  4114. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  4115. struct gguf_context * meta = NULL;
  4116. std::vector<ggml_context *> contexts;
  4117. std::string arch_name;
  4118. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  4119. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  4120. int trace = 0;
  4121. if (getenv("LLAMA_TRACE")) {
  4122. trace = atoi(getenv("LLAMA_TRACE"));
  4123. }
  4124. if (param_overrides_p != nullptr) {
  4125. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  4126. kv_overrides.insert({std::string(p->key), *p});
  4127. }
  4128. }
  4129. struct ggml_context * ctx = NULL;
  4130. struct gguf_init_params params = {
  4131. /*.no_alloc = */ true,
  4132. /*.ctx = */ &ctx,
  4133. };
  4134. meta = gguf_init_from_file(fname.c_str(), params);
  4135. if (!meta) {
  4136. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  4137. }
  4138. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  4139. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  4140. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  4141. contexts.emplace_back(ctx);
  4142. // Save tensors data offset of the main file.
  4143. // For subsidiary files, `meta` tensor data offset must not be used,
  4144. // so we build a unified tensors index for weights.
  4145. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4146. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  4147. }
  4148. uint16_t n_split = 0;
  4149. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  4150. // Load additional GGML contexts
  4151. if (n_split > 1) {
  4152. uint16_t idx = 0;
  4153. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  4154. if (idx != 0) {
  4155. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  4156. }
  4157. char split_prefix[PATH_MAX] = {0};
  4158. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  4159. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  4160. }
  4161. if (trace > 0) {
  4162. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  4163. }
  4164. char split_path[PATH_MAX] = {0};
  4165. for (idx = 1; idx < n_split; idx++) {
  4166. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  4167. struct gguf_init_params split_params = {
  4168. /*.no_alloc = */ true,
  4169. /*.ctx = */ &ctx,
  4170. };
  4171. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  4172. if (!ctx_gguf) {
  4173. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  4174. }
  4175. files.emplace_back(new llama_file(split_path, "rb"));
  4176. contexts.emplace_back(ctx);
  4177. // Save tensors data offset info of the shard.
  4178. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  4179. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  4180. }
  4181. gguf_free(ctx_gguf);
  4182. }
  4183. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  4184. // sanity check
  4185. {
  4186. const int n_tensors_loaded = (int) weights.size();
  4187. if (n_tensors != n_tensors_loaded) {
  4188. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  4189. }
  4190. }
  4191. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  4192. }
  4193. n_kv = gguf_get_n_kv(meta);
  4194. n_tensors = weights.size();
  4195. fver = (enum llama_fver) gguf_get_version(meta);
  4196. std::set<std::string> tensor_names;
  4197. for (auto & w : weights) {
  4198. n_elements += ggml_nelements(w.tensor);
  4199. n_bytes += ggml_nbytes(w.tensor);
  4200. // make sure there is no duplicated tensor names
  4201. const std::string name(w.tensor->name);
  4202. auto found = tensor_names.find(name);
  4203. if (found != tensor_names.end()) {
  4204. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  4205. }
  4206. tensor_names.insert(name);
  4207. }
  4208. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  4209. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  4210. // determine file type based on the number of tensors for each quantization and print meta data
  4211. // TODO: make optional
  4212. {
  4213. std::map<enum ggml_type, uint32_t> n_type;
  4214. uint32_t n_type_max = 0;
  4215. enum ggml_type type_max = GGML_TYPE_F32;
  4216. for (int i = 0; i < n_tensors; i++) {
  4217. const ggml_tensor * tensor = weights.at(i).tensor;
  4218. enum ggml_type type = tensor->type;
  4219. n_type[type]++;
  4220. if (n_type_max < n_type[type]) {
  4221. n_type_max = n_type[type];
  4222. type_max = type;
  4223. }
  4224. if (trace > 0) {
  4225. const uint16_t sid = weights.at(i).idx;
  4226. 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());
  4227. }
  4228. }
  4229. switch (type_max) {
  4230. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4231. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4232. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4233. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4234. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4235. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4236. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4237. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4238. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4239. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4240. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4241. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4242. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4243. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4244. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4245. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4246. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4247. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4248. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4249. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4250. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4251. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4252. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4253. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4254. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  4255. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  4256. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  4257. default:
  4258. {
  4259. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4260. ftype = LLAMA_FTYPE_ALL_F32;
  4261. } break;
  4262. }
  4263. // this is a way to mark that we have "guessed" the file type
  4264. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4265. {
  4266. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  4267. if (kid >= 0) {
  4268. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  4269. }
  4270. }
  4271. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4272. for (int i = 0; i < n_kv; i++) {
  4273. const char * name = gguf_get_key(meta, i);
  4274. const enum gguf_type type = gguf_get_kv_type(meta, i);
  4275. const std::string type_name =
  4276. type == GGUF_TYPE_ARRAY
  4277. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  4278. : gguf_type_name(type);
  4279. std::string value = gguf_kv_to_str(meta, i);
  4280. const size_t MAX_VALUE_LEN = 40;
  4281. if (value.size() > MAX_VALUE_LEN) {
  4282. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4283. }
  4284. replace_all(value, "\n", "\\n");
  4285. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4286. }
  4287. // print type counts
  4288. for (auto & kv : n_type) {
  4289. if (kv.second == 0) {
  4290. continue;
  4291. }
  4292. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4293. }
  4294. }
  4295. if (!llama_mmap::SUPPORTED) {
  4296. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4297. use_mmap = false;
  4298. }
  4299. this->use_mmap = use_mmap;
  4300. this->check_tensors = check_tensors;
  4301. }
  4302. ~llama_model_loader() {
  4303. if (meta) {
  4304. gguf_free(meta);
  4305. }
  4306. for (auto * ctx : contexts) {
  4307. ggml_free(ctx);
  4308. }
  4309. }
  4310. template<typename T>
  4311. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4312. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4313. const int kid = gguf_find_key(meta, key.c_str());
  4314. if (kid < 0) {
  4315. if (required) {
  4316. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4317. }
  4318. return false;
  4319. }
  4320. struct GGUFMeta::ArrayInfo arr_info =
  4321. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4322. result = arr_info.length;
  4323. return true;
  4324. }
  4325. template<typename T>
  4326. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4327. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4328. return get_arr_n(llm_kv(kid), result, required);
  4329. }
  4330. template<typename T>
  4331. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4332. const int kid = gguf_find_key(meta, key.c_str());
  4333. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4334. if (required) {
  4335. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4336. }
  4337. return false;
  4338. }
  4339. struct GGUFMeta::ArrayInfo arr_info =
  4340. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4341. switch (arr_info.gt) {
  4342. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4343. case GGUF_TYPE_INT32: GGML_ASSERT(
  4344. (std::is_same<T, int32_t>::value) ||
  4345. (std::is_same<T, uint32_t>::value)); break;
  4346. default:
  4347. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4348. }
  4349. result.resize(arr_info.length);
  4350. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4351. return true;
  4352. }
  4353. template<typename T, size_t N_MAX>
  4354. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4355. const int kid = gguf_find_key(meta, key.c_str());
  4356. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4357. if (required) {
  4358. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4359. }
  4360. return false;
  4361. }
  4362. struct GGUFMeta::ArrayInfo arr_info =
  4363. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4364. switch (arr_info.gt) {
  4365. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4366. case GGUF_TYPE_INT32: GGML_ASSERT(
  4367. (std::is_same<T, int32_t>::value) ||
  4368. (std::is_same<T, uint32_t>::value)); break;
  4369. default:
  4370. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4371. }
  4372. if (arr_info.length > N_MAX) {
  4373. 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));
  4374. }
  4375. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4376. return true;
  4377. }
  4378. template<typename T>
  4379. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4380. return get_arr(llm_kv(kid), result, required);
  4381. }
  4382. template<typename T>
  4383. bool get_key(const std::string & key, T & result, const bool required = true) {
  4384. auto it = kv_overrides.find(key);
  4385. const struct llama_model_kv_override * override =
  4386. it != kv_overrides.end() ? &it->second : nullptr;
  4387. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  4388. if (required && !found) {
  4389. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4390. }
  4391. return found;
  4392. }
  4393. template<typename T>
  4394. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4395. return get_key(llm_kv(kid), result, required);
  4396. }
  4397. // get array of n <= N_MAX elements, or a single element repeated n times
  4398. template<typename T, size_t N_MAX>
  4399. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4400. const int kid = gguf_find_key(meta, key.c_str());
  4401. if (kid < 0) {
  4402. if (required) {
  4403. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4404. }
  4405. return false;
  4406. }
  4407. if (n > N_MAX) {
  4408. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4409. }
  4410. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  4411. struct GGUFMeta::ArrayInfo arr_info =
  4412. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4413. if (n != arr_info.length) {
  4414. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4415. }
  4416. return get_arr(key, result, required);
  4417. } else {
  4418. T value;
  4419. bool ok = get_key(key, value, required);
  4420. if (!ok) {
  4421. return false;
  4422. }
  4423. for (uint32_t i = 0; i < n; i++) {
  4424. result[i] = value;
  4425. }
  4426. return true;
  4427. }
  4428. }
  4429. template<typename T>
  4430. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4431. return get_key_or_arr(llm_kv(kid), result, n, required);
  4432. }
  4433. std::string get_arch_name() const {
  4434. return arch_name;
  4435. }
  4436. enum llm_arch get_arch() const {
  4437. return llm_kv.arch;
  4438. }
  4439. const char * get_tensor_name(int i) const {
  4440. return weights.at(i).tensor->name;
  4441. }
  4442. const llama_tensor_weight * get_weight(const char * name) const {
  4443. for (const auto & weight : weights) {
  4444. if (strcmp(name, weight.tensor->name) == 0) {
  4445. return &weight;
  4446. }
  4447. }
  4448. return nullptr;
  4449. }
  4450. const llama_tensor_weight * get_weight(int i) const {
  4451. return get_weight(get_tensor_name(i));
  4452. }
  4453. const llama_tensor_weight & require_weight(const char * name) const {
  4454. const llama_tensor_weight * weight = get_weight(name);
  4455. if (!weight) {
  4456. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4457. }
  4458. return *weight;
  4459. }
  4460. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4461. const auto * weight = get_weight(name);
  4462. if (!weight) {
  4463. return nullptr;
  4464. }
  4465. return weight->tensor;
  4466. }
  4467. struct ggml_tensor * require_tensor_meta(const char * name) const {
  4468. struct ggml_tensor * tensor = get_tensor_meta(name);
  4469. if (!tensor) {
  4470. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4471. }
  4472. return tensor;
  4473. }
  4474. struct ggml_tensor * get_tensor_meta(int i) const {
  4475. return get_tensor_meta(get_tensor_name(i));
  4476. }
  4477. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  4478. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4479. ggml_set_name(tensor, ggml_get_name(cur));
  4480. if (duplicated) {
  4481. size_data += ggml_nbytes(cur);
  4482. } else {
  4483. n_created++;
  4484. }
  4485. return tensor;
  4486. }
  4487. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4488. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4489. if (cur == NULL) {
  4490. if (!required) {
  4491. return NULL;
  4492. }
  4493. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4494. }
  4495. {
  4496. bool is_ok = true;
  4497. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4498. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4499. is_ok = false;
  4500. break;
  4501. }
  4502. }
  4503. if (!is_ok) {
  4504. throw std::runtime_error(
  4505. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4506. __func__, name.c_str(),
  4507. llama_format_tensor_shape(ne).c_str(),
  4508. llama_format_tensor_shape(cur).c_str()));
  4509. }
  4510. }
  4511. return cur;
  4512. }
  4513. static const int TENSOR_NOT_REQUIRED = 1;
  4514. static const int TENSOR_DUPLICATED = 2;
  4515. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  4516. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4517. if (cur == NULL) {
  4518. return NULL;
  4519. }
  4520. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  4521. }
  4522. 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) {
  4523. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4524. if (cur == NULL) {
  4525. return NULL;
  4526. }
  4527. if (cur->type != base->type) {
  4528. 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)));
  4529. }
  4530. std::array<int64_t, GGML_MAX_DIMS> dims;
  4531. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4532. dims[i] = i < ne.size() ? ne[i] : 1;
  4533. }
  4534. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4535. dims[0], dims[1], dims[2], dims[3],
  4536. cur->nb[1], cur->nb[2], cur->nb[3],
  4537. offset);
  4538. ggml_set_name(tensor, name.c_str());
  4539. n_created++;
  4540. return tensor;
  4541. }
  4542. void done_getting_tensors() const {
  4543. if (n_created != n_tensors) {
  4544. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4545. }
  4546. }
  4547. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4548. if (use_mmap) {
  4549. mappings.reserve(files.size());
  4550. mmaps_used.reserve(files.size());
  4551. for (const auto & file : files) {
  4552. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  4553. mmaps_used.emplace_back(mapping->size, 0);
  4554. if (mlock_mmaps) {
  4555. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4556. mlock_mmap->init(mapping->addr);
  4557. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4558. }
  4559. mappings.emplace_back(std::move(mapping));
  4560. }
  4561. }
  4562. // compute the total size of all tensors for progress reporting
  4563. for (auto & w : weights) {
  4564. size_data += ggml_nbytes(w.tensor);
  4565. }
  4566. }
  4567. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4568. GGML_ASSERT(!mappings.empty());
  4569. const auto & mapping = mappings.at(idx);
  4570. *first = mapping->size;
  4571. *last = 0;
  4572. *addr = mapping->addr;
  4573. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4574. try {
  4575. const auto * weight = get_weight(ggml_get_name(tensor));
  4576. if (!weight) {
  4577. continue;
  4578. }
  4579. if (weight->idx != idx) {
  4580. continue;
  4581. }
  4582. *first = std::min(*first, weight->offs);
  4583. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4584. } catch(...) {
  4585. // the tensor is not in the model
  4586. }
  4587. }
  4588. }
  4589. // for backwards compatibility, does not support ggml-backend
  4590. void load_data_for(struct ggml_tensor * cur) const {
  4591. const auto & w = require_weight(ggml_get_name(cur));
  4592. if (use_mmap) {
  4593. const auto & mapping = mappings.at(w.idx);
  4594. if (cur->data == nullptr) {
  4595. cur->data = (uint8_t *)mapping->addr + w.offs;
  4596. } else {
  4597. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4598. }
  4599. } else {
  4600. GGML_ASSERT(cur->data != nullptr);
  4601. GGML_ASSERT(w.idx < files.size());
  4602. const auto & file = files.at(w.idx);
  4603. file->seek(w.offs, SEEK_SET);
  4604. file->read_raw(cur->data, ggml_nbytes(cur));
  4605. }
  4606. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4607. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4608. }
  4609. }
  4610. size_t size_done = 0;
  4611. size_t size_data = 0;
  4612. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4613. // Returns false if cancelled by progress_callback
  4614. bool load_all_data(
  4615. struct ggml_context * ctx,
  4616. llama_buf_map & bufs_mmap,
  4617. llama_mlocks * lmlocks,
  4618. llama_progress_callback progress_callback,
  4619. void * progress_callback_user_data) {
  4620. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4621. std::vector<no_init<uint8_t>> read_buf;
  4622. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4623. #if defined(GGML_USE_CUDA)
  4624. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4625. // NVMe raid configurations might require more / larger buffers.
  4626. constexpr size_t n_buffers = 4;
  4627. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4628. std::vector<ggml_backend_buffer_t> host_buffers;
  4629. std::vector<void*> host_ptrs;
  4630. std::vector<ggml_backend_event_t> events;
  4631. size_t buffer_idx = 0; // buffer to use for async loads
  4632. ggml_backend_t cuda_backend = nullptr;
  4633. if (!use_mmap && !check_tensors) {
  4634. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4635. // First determine if the CUDA backend is active, and if so, determine the device ID.
  4636. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  4637. if (buf) {
  4638. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  4639. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  4640. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  4641. if (buffer_type == cuda_buffer_type) {
  4642. cuda_backend = ggml_backend_cuda_init(i);
  4643. break;
  4644. }
  4645. }
  4646. }
  4647. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  4648. if (cuda_backend) {
  4649. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4650. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  4651. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  4652. events.emplace_back(ggml_backend_event_new(cuda_backend));
  4653. }
  4654. }
  4655. }
  4656. #endif
  4657. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4658. const auto * weight = get_weight(ggml_get_name(cur));
  4659. if (weight == nullptr) {
  4660. // this can happen with split experts models
  4661. continue;
  4662. }
  4663. if (progress_callback) {
  4664. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4665. return false;
  4666. }
  4667. }
  4668. size_t n_size = ggml_nbytes(cur);
  4669. if (use_mmap) {
  4670. const auto & mapping = mappings.at(weight->idx);
  4671. ggml_backend_buffer_t buf_mmap = nullptr;
  4672. if (bufs_mmap.count(weight->idx)) {
  4673. buf_mmap = bufs_mmap.at(weight->idx);
  4674. }
  4675. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4676. if (check_tensors) {
  4677. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4678. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4679. }));
  4680. }
  4681. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4682. if (buf_mmap && cur->data == nullptr) {
  4683. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4684. if (lmlocks) {
  4685. const auto & lmlock = lmlocks->at(weight->idx);
  4686. lmlock->grow_to(weight->offs + n_size);
  4687. }
  4688. auto & mmap_used = mmaps_used[weight->idx];
  4689. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4690. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4691. } else {
  4692. ggml_backend_tensor_set(cur, data, 0, n_size);
  4693. }
  4694. } else {
  4695. GGML_ASSERT(weight->idx < files.size());
  4696. const auto & file = files.at(weight->idx);
  4697. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4698. file->seek(weight->offs, SEEK_SET);
  4699. file->read_raw(cur->data, n_size);
  4700. if (check_tensors) {
  4701. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4702. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4703. }));
  4704. }
  4705. } else {
  4706. #if defined(GGML_USE_CUDA)
  4707. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4708. if (cuda_backend) {
  4709. file->seek(weight->offs, SEEK_SET);
  4710. size_t bytes_read = 0;
  4711. while (bytes_read < n_size) {
  4712. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4713. ggml_backend_event_synchronize(events[buffer_idx]);
  4714. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4715. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4716. ggml_backend_event_record(events[buffer_idx]);
  4717. bytes_read += read_iteration;
  4718. ++buffer_idx;
  4719. buffer_idx %= n_buffers;
  4720. }
  4721. }
  4722. else
  4723. #endif
  4724. {
  4725. read_buf.resize(n_size);
  4726. file->seek(weight->offs, SEEK_SET);
  4727. file->read_raw(read_buf.data(), n_size);
  4728. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4729. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4730. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4731. }
  4732. }
  4733. }
  4734. }
  4735. size_done += n_size;
  4736. }
  4737. #if defined(GGML_USE_CUDA)
  4738. // free temporary resources used for async cuda uploads
  4739. if (cuda_backend) {
  4740. for (size_t idx = 0; idx < n_buffers;++idx) {
  4741. ggml_backend_event_synchronize(events[idx]);
  4742. ggml_backend_event_free(events[idx]);
  4743. ggml_backend_buffer_free(host_buffers[idx]);
  4744. }
  4745. ggml_backend_free(cuda_backend);
  4746. }
  4747. #endif
  4748. // check validation results
  4749. bool validation_failed = false;
  4750. for (auto & future : validation_result) {
  4751. auto result = future.get();
  4752. if (!result.second) {
  4753. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4754. validation_failed = true;
  4755. }
  4756. }
  4757. if (validation_failed) {
  4758. throw std::runtime_error("found tensors with invalid data");
  4759. }
  4760. // check if this is the last call and do final cleanup
  4761. if (size_done >= size_data) {
  4762. // unmap offloaded tensors and metadata
  4763. if (use_mmap) {
  4764. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4765. const auto & mmap_used = mmaps_used.at(idx);
  4766. auto & mapping = mappings.at(idx);
  4767. mapping->unmap_fragment(0, mmap_used.first);
  4768. if (mmap_used.second != 0) {
  4769. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4770. }
  4771. }
  4772. }
  4773. if (progress_callback) {
  4774. // Even though the model is done loading, we still honor
  4775. // cancellation since we need to free allocations.
  4776. return progress_callback(1.0f, progress_callback_user_data);
  4777. }
  4778. }
  4779. return true;
  4780. }
  4781. };
  4782. template<>
  4783. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4784. uint32_t tmp;
  4785. const bool found = get_key(kid, tmp, required);
  4786. if (found) {
  4787. result = (enum llama_pooling_type) tmp;
  4788. } else {
  4789. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4790. }
  4791. return found;
  4792. }
  4793. //
  4794. // load LLaMA models
  4795. //
  4796. static const char * llama_model_arch_name(llm_arch arch) {
  4797. auto it = LLM_ARCH_NAMES.find(arch);
  4798. if (it == LLM_ARCH_NAMES.end()) {
  4799. return "unknown";
  4800. }
  4801. return it->second;
  4802. }
  4803. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4804. if (ftype & LLAMA_FTYPE_GUESSED) {
  4805. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4806. }
  4807. switch (ftype) {
  4808. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4809. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4810. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4811. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4812. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4813. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4814. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4815. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4816. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4817. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4818. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4819. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4820. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4821. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4822. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4823. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4824. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4825. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4826. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4827. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4828. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4829. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4830. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4831. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4832. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4833. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4834. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4835. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4836. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4837. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4838. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4839. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4840. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  4841. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  4842. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  4843. default: return "unknown, may not work";
  4844. }
  4845. }
  4846. static const char * llama_model_type_name(e_model type) {
  4847. switch (type) {
  4848. case MODEL_14M: return "14M";
  4849. case MODEL_17M: return "17M";
  4850. case MODEL_22M: return "22M";
  4851. case MODEL_33M: return "33M";
  4852. case MODEL_60M: return "60M";
  4853. case MODEL_70M: return "70M";
  4854. case MODEL_80M: return "80M";
  4855. case MODEL_109M: return "109M";
  4856. case MODEL_137M: return "137M";
  4857. case MODEL_160M: return "160M";
  4858. case MODEL_220M: return "220M";
  4859. case MODEL_250M: return "250M";
  4860. case MODEL_270M: return "270M";
  4861. case MODEL_335M: return "335M";
  4862. case MODEL_410M: return "410M";
  4863. case MODEL_450M: return "450M";
  4864. case MODEL_770M: return "770M";
  4865. case MODEL_780M: return "780M";
  4866. case MODEL_0_5B: return "0.5B";
  4867. case MODEL_1B: return "1B";
  4868. case MODEL_1_3B: return "1.3B";
  4869. case MODEL_1_4B: return "1.4B";
  4870. case MODEL_1_6B: return "1.6B";
  4871. case MODEL_2B: return "2B";
  4872. case MODEL_2_8B: return "2.8B";
  4873. case MODEL_3B: return "3B";
  4874. case MODEL_4B: return "4B";
  4875. case MODEL_6B: return "6B";
  4876. case MODEL_6_9B: return "6.9B";
  4877. case MODEL_7B: return "7B";
  4878. case MODEL_8B: return "8B";
  4879. case MODEL_9B: return "9B";
  4880. case MODEL_11B: return "11B";
  4881. case MODEL_12B: return "12B";
  4882. case MODEL_13B: return "13B";
  4883. case MODEL_14B: return "14B";
  4884. case MODEL_15B: return "15B";
  4885. case MODEL_16B: return "16B";
  4886. case MODEL_20B: return "20B";
  4887. case MODEL_30B: return "30B";
  4888. case MODEL_34B: return "34B";
  4889. case MODEL_35B: return "35B";
  4890. case MODEL_40B: return "40B";
  4891. case MODEL_65B: return "65B";
  4892. case MODEL_70B: return "70B";
  4893. case MODEL_236B: return "236B";
  4894. case MODEL_314B: return "314B";
  4895. case MODEL_SMALL: return "0.1B";
  4896. case MODEL_MEDIUM: return "0.4B";
  4897. case MODEL_LARGE: return "0.8B";
  4898. case MODEL_XL: return "1.5B";
  4899. case MODEL_A1_7B: return "A1.7B";
  4900. case MODEL_A2_7B: return "A2.7B";
  4901. case MODEL_8x7B: return "8x7B";
  4902. case MODEL_8x22B: return "8x22B";
  4903. case MODEL_16x12B: return "16x12B";
  4904. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4905. case MODEL_57B_A14B: return "57B.A14B";
  4906. case MODEL_27B: return "27B";
  4907. default: return "?B";
  4908. }
  4909. }
  4910. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4911. switch (type) {
  4912. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4913. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4914. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4915. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4916. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4917. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  4918. default: return "unknown";
  4919. }
  4920. }
  4921. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4922. model.arch = ml.get_arch();
  4923. if (model.arch == LLM_ARCH_UNKNOWN) {
  4924. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4925. }
  4926. }
  4927. static void llm_load_hparams(
  4928. llama_model_loader & ml,
  4929. llama_model & model) {
  4930. auto & hparams = model.hparams;
  4931. const gguf_context * ctx = ml.meta;
  4932. // get metadata as string
  4933. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4934. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4935. if (type == GGUF_TYPE_ARRAY) {
  4936. continue;
  4937. }
  4938. const char * name = gguf_get_key(ctx, i);
  4939. const std::string value = gguf_kv_to_str(ctx, i);
  4940. model.gguf_kv.emplace(name, value);
  4941. }
  4942. // get general kv
  4943. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4944. // get hparams kv
  4945. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4946. // everything past this point is not vocab-related
  4947. if (hparams.vocab_only) {
  4948. return;
  4949. }
  4950. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4951. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4952. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4953. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4954. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4955. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4956. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4957. if (hparams.n_expert > 0) {
  4958. GGML_ASSERT(hparams.n_expert_used > 0);
  4959. } else {
  4960. GGML_ASSERT(hparams.n_expert_used == 0);
  4961. }
  4962. // zero-out the per-layer hparams
  4963. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4964. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4965. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4966. std::fill(hparams.cross_attn_layers.begin(), hparams.cross_attn_layers.end(), -1);
  4967. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4968. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4969. ml.get_arr(LLM_KV_ATTENTION_CROSS_ATTENTION_LAYERS, hparams.cross_attn_layers, false);
  4970. // n_head_kv is optional, default to n_head
  4971. hparams.n_head_kv_arr = hparams.n_head_arr;
  4972. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4973. bool rope_finetuned = false;
  4974. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4975. hparams.rope_finetuned = rope_finetuned;
  4976. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4977. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4978. // rope_freq_base (optional)
  4979. hparams.rope_freq_base_train = 10000.0f;
  4980. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4981. std::string rope_scaling("linear");
  4982. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4983. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4984. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4985. // rope_freq_scale (inverse of the kv) is optional
  4986. float ropescale = 0.0f;
  4987. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4988. // try the old key name
  4989. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4990. }
  4991. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4992. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4993. // non-transformer models do not have attention heads
  4994. if (hparams.n_head() > 0) {
  4995. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4996. // gpt-j n_rot = rotary_dim
  4997. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4998. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4999. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  5000. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  5001. // sanity check for n_rot (optional)
  5002. hparams.n_rot = hparams.n_embd_head_k;
  5003. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  5004. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_MLLAMA || model.arch == LLM_ARCH_FALCON) {
  5005. if (hparams.n_rot != hparams.n_embd_head_k) {
  5006. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  5007. }
  5008. }
  5009. } else {
  5010. hparams.n_rot = 0;
  5011. hparams.n_embd_head_k = 0;
  5012. hparams.n_embd_head_v = 0;
  5013. }
  5014. // arch-specific KVs
  5015. switch (model.arch) {
  5016. case LLM_ARCH_LLAMA:
  5017. {
  5018. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5019. if (hparams.n_expert == 8) {
  5020. switch (hparams.n_layer) {
  5021. case 32: model.type = e_model::MODEL_8x7B; break;
  5022. case 56: model.type = e_model::MODEL_8x22B; break;
  5023. default: model.type = e_model::MODEL_UNKNOWN;
  5024. }
  5025. } else {
  5026. switch (hparams.n_layer) {
  5027. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  5028. case 22: model.type = e_model::MODEL_1B; break;
  5029. case 26: model.type = e_model::MODEL_3B; break;
  5030. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  5031. // granite uses a vocab with len 49152
  5032. 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;
  5033. case 36: model.type = e_model::MODEL_8B; break; // granite
  5034. case 40: model.type = e_model::MODEL_13B; break;
  5035. case 48: model.type = e_model::MODEL_34B; break;
  5036. case 60: model.type = e_model::MODEL_30B; break;
  5037. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  5038. default: model.type = e_model::MODEL_UNKNOWN;
  5039. }
  5040. }
  5041. } break;
  5042. case LLM_ARCH_MLLAMA:
  5043. {
  5044. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5045. switch (hparams.n_layer) {
  5046. case 40: model.type = e_model::MODEL_11B; break;
  5047. case 100: model.type = e_model::MODEL_90B; break;
  5048. default: model.type = e_model::MODEL_UNKNOWN;
  5049. }
  5050. } break;
  5051. case LLM_ARCH_MINICPM:
  5052. {
  5053. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5054. switch (hparams.n_layer) {
  5055. case 40: model.type = e_model::MODEL_2B; break;
  5056. default: model.type = e_model::MODEL_UNKNOWN;
  5057. }
  5058. } break;
  5059. case LLM_ARCH_MINICPM3:
  5060. {
  5061. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5062. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5063. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5064. switch (hparams.n_layer) {
  5065. case 62: model.type = e_model::MODEL_4B; break;
  5066. default: model.type = e_model::MODEL_UNKNOWN;
  5067. }
  5068. } break;
  5069. case LLM_ARCH_GROK:
  5070. {
  5071. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5072. switch (hparams.n_layer) {
  5073. case 64: model.type = e_model::MODEL_314B; break;
  5074. default: model.type = e_model::MODEL_UNKNOWN;
  5075. }
  5076. } break;
  5077. case LLM_ARCH_FALCON:
  5078. {
  5079. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5080. switch (hparams.n_layer) {
  5081. case 32: model.type = e_model::MODEL_7B; break;
  5082. case 60: model.type = e_model::MODEL_40B; break;
  5083. default: model.type = e_model::MODEL_UNKNOWN;
  5084. }
  5085. } break;
  5086. case LLM_ARCH_BAICHUAN:
  5087. {
  5088. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5089. switch (hparams.n_layer) {
  5090. case 32: model.type = e_model::MODEL_7B; break;
  5091. case 40: model.type = e_model::MODEL_13B; break;
  5092. default: model.type = e_model::MODEL_UNKNOWN;
  5093. }
  5094. if (model.type == e_model::MODEL_13B) {
  5095. // TODO: become GGUF KV parameter
  5096. hparams.f_max_alibi_bias = 8.0f;
  5097. }
  5098. } break;
  5099. case LLM_ARCH_STARCODER:
  5100. {
  5101. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5102. switch (hparams.n_layer) {
  5103. case 24: model.type = e_model::MODEL_1B; break;
  5104. case 36: model.type = e_model::MODEL_3B; break;
  5105. case 42: model.type = e_model::MODEL_7B; break;
  5106. case 40: model.type = e_model::MODEL_15B; break;
  5107. default: model.type = e_model::MODEL_UNKNOWN;
  5108. }
  5109. } break;
  5110. case LLM_ARCH_REFACT:
  5111. {
  5112. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5113. switch (hparams.n_layer) {
  5114. case 32: model.type = e_model::MODEL_1B; break;
  5115. default: model.type = e_model::MODEL_UNKNOWN;
  5116. }
  5117. // TODO: become GGUF KV parameter
  5118. hparams.f_max_alibi_bias = 8.0f;
  5119. } break;
  5120. case LLM_ARCH_BERT:
  5121. {
  5122. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5123. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5124. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5125. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5126. switch (hparams.n_layer) {
  5127. case 3:
  5128. model.type = e_model::MODEL_17M; break; // bge-micro
  5129. case 6:
  5130. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  5131. case 12:
  5132. switch (hparams.n_embd) {
  5133. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  5134. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  5135. } break;
  5136. case 24:
  5137. model.type = e_model::MODEL_335M; break; // bge-large
  5138. }
  5139. } break;
  5140. case LLM_ARCH_JINA_BERT_V2:
  5141. {
  5142. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5143. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5144. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5145. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  5146. hparams.f_max_alibi_bias = 8.0f;
  5147. switch (hparams.n_layer) {
  5148. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  5149. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  5150. }
  5151. } break;
  5152. case LLM_ARCH_NOMIC_BERT:
  5153. {
  5154. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5155. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  5156. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  5157. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  5158. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  5159. model.type = e_model::MODEL_137M;
  5160. }
  5161. } break;
  5162. case LLM_ARCH_BLOOM:
  5163. {
  5164. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5165. switch (hparams.n_layer) {
  5166. case 24: model.type = e_model::MODEL_1B; break;
  5167. case 30:
  5168. switch (hparams.n_embd) {
  5169. case 2560: model.type = e_model::MODEL_3B; break;
  5170. case 4096: model.type = e_model::MODEL_7B; break;
  5171. } break;
  5172. }
  5173. // TODO: become GGUF KV parameter
  5174. hparams.f_max_alibi_bias = 8.0f;
  5175. } break;
  5176. case LLM_ARCH_MPT:
  5177. {
  5178. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5179. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5180. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5181. switch (hparams.n_layer) {
  5182. case 32: model.type = e_model::MODEL_7B; break;
  5183. case 48: model.type = e_model::MODEL_30B; break;
  5184. default: model.type = e_model::MODEL_UNKNOWN;
  5185. }
  5186. } break;
  5187. case LLM_ARCH_STABLELM:
  5188. {
  5189. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5190. switch (hparams.n_layer) {
  5191. case 24: model.type = e_model::MODEL_1B; break;
  5192. case 32: model.type = e_model::MODEL_3B; break;
  5193. case 40: model.type = e_model::MODEL_12B; break;
  5194. default: model.type = e_model::MODEL_UNKNOWN;
  5195. }
  5196. } break;
  5197. case LLM_ARCH_QWEN:
  5198. {
  5199. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5200. switch (hparams.n_layer) {
  5201. case 32: model.type = e_model::MODEL_7B; break;
  5202. case 40: model.type = e_model::MODEL_13B; break;
  5203. default: model.type = e_model::MODEL_UNKNOWN;
  5204. }
  5205. } break;
  5206. case LLM_ARCH_QWEN2:
  5207. {
  5208. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5209. switch (hparams.n_layer) {
  5210. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5211. case 32: model.type = e_model::MODEL_7B; break;
  5212. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5213. case 80: model.type = e_model::MODEL_70B; break;
  5214. default: model.type = e_model::MODEL_UNKNOWN;
  5215. }
  5216. } break;
  5217. case LLM_ARCH_QWEN2MOE:
  5218. {
  5219. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5220. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5221. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5222. switch (hparams.n_layer) {
  5223. case 24: model.type = e_model::MODEL_A2_7B; break;
  5224. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5225. default: model.type = e_model::MODEL_UNKNOWN;
  5226. }
  5227. } break;
  5228. case LLM_ARCH_PHI2:
  5229. {
  5230. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5231. switch (hparams.n_layer) {
  5232. case 24: model.type = e_model::MODEL_1B; break;
  5233. case 32: model.type = e_model::MODEL_3B; break;
  5234. default: model.type = e_model::MODEL_UNKNOWN;
  5235. }
  5236. } break;
  5237. case LLM_ARCH_PHI3:
  5238. {
  5239. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5240. switch (hparams.n_layer) {
  5241. case 24: model.type = e_model::MODEL_1B; break;
  5242. case 32: model.type = e_model::MODEL_3B; break;
  5243. case 40: model.type = e_model::MODEL_14B; break;
  5244. default: model.type = e_model::MODEL_UNKNOWN;
  5245. }
  5246. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5247. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5248. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5249. hparams.n_swa = 2047;
  5250. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5251. // default value for Phi-3-mini-128k-instruct
  5252. hparams.n_swa = 262144;
  5253. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5254. // default value for Phi-3-medium-128k-instruct
  5255. hparams.n_swa = 131072;
  5256. }
  5257. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5258. if (!found_swa && hparams.n_swa == 0) {
  5259. throw std::runtime_error("invalid value for sliding_window");
  5260. }
  5261. } break;
  5262. case LLM_ARCH_PLAMO:
  5263. {
  5264. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5265. switch (hparams.n_layer) {
  5266. case 40: model.type = e_model::MODEL_13B; break;
  5267. default: model.type = e_model::MODEL_UNKNOWN;
  5268. }
  5269. } break;
  5270. case LLM_ARCH_GPT2:
  5271. {
  5272. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5273. switch (hparams.n_layer) {
  5274. case 12: model.type = e_model::MODEL_SMALL; break;
  5275. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5276. case 36: model.type = e_model::MODEL_LARGE; break;
  5277. case 48: model.type = e_model::MODEL_XL; break;
  5278. default: model.type = e_model::MODEL_UNKNOWN;
  5279. }
  5280. } break;
  5281. case LLM_ARCH_CODESHELL:
  5282. {
  5283. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5284. switch (hparams.n_layer) {
  5285. case 42: model.type = e_model::MODEL_7B; break;
  5286. default: model.type = e_model::MODEL_UNKNOWN;
  5287. }
  5288. } break;
  5289. case LLM_ARCH_ORION:
  5290. {
  5291. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5292. switch (hparams.n_layer) {
  5293. case 40: model.type = e_model::MODEL_14B; break;
  5294. default: model.type = e_model::MODEL_UNKNOWN;
  5295. }
  5296. } break;
  5297. case LLM_ARCH_INTERNLM2:
  5298. {
  5299. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5300. switch (hparams.n_layer) {
  5301. case 32: model.type = e_model::MODEL_7B; break;
  5302. case 48: model.type = e_model::MODEL_20B; break;
  5303. default: model.type = e_model::MODEL_UNKNOWN;
  5304. }
  5305. } break;
  5306. case LLM_ARCH_GEMMA:
  5307. {
  5308. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5309. switch (hparams.n_layer) {
  5310. case 18: model.type = e_model::MODEL_2B; break;
  5311. case 28: model.type = e_model::MODEL_7B; break;
  5312. default: model.type = e_model::MODEL_UNKNOWN;
  5313. }
  5314. } break;
  5315. case LLM_ARCH_GEMMA2:
  5316. {
  5317. hparams.n_swa = 4096; // default value of gemma 2
  5318. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5319. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5320. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5321. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5322. hparams.attn_soft_cap = true;
  5323. switch (hparams.n_layer) {
  5324. case 26: model.type = e_model::MODEL_2B; break;
  5325. case 42: model.type = e_model::MODEL_9B; break;
  5326. case 46: model.type = e_model::MODEL_27B; break;
  5327. default: model.type = e_model::MODEL_UNKNOWN;
  5328. }
  5329. } break;
  5330. case LLM_ARCH_STARCODER2:
  5331. {
  5332. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5333. switch (hparams.n_layer) {
  5334. case 30: model.type = e_model::MODEL_3B; break;
  5335. case 32: model.type = e_model::MODEL_7B; break;
  5336. case 40: model.type = e_model::MODEL_15B; break;
  5337. case 52: model.type = e_model::MODEL_20B; break; // granite
  5338. case 88: model.type = e_model::MODEL_34B; break; // granite
  5339. default: model.type = e_model::MODEL_UNKNOWN;
  5340. }
  5341. } break;
  5342. case LLM_ARCH_MAMBA:
  5343. {
  5344. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5345. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5346. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5347. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5348. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5349. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5350. switch (hparams.n_layer) {
  5351. case 24:
  5352. switch (hparams.n_embd) {
  5353. case 768: model.type = e_model::MODEL_SMALL; break;
  5354. default: model.type = e_model::MODEL_UNKNOWN;
  5355. } break;
  5356. case 48:
  5357. switch (hparams.n_embd) {
  5358. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5359. case 1536: model.type = e_model::MODEL_LARGE; break;
  5360. case 2048: model.type = e_model::MODEL_XL; break;
  5361. default: model.type = e_model::MODEL_UNKNOWN;
  5362. } break;
  5363. case 64:
  5364. switch (hparams.n_embd) {
  5365. case 2560: model.type = e_model::MODEL_3B; break;
  5366. default: model.type = e_model::MODEL_UNKNOWN;
  5367. } break;
  5368. default: model.type = e_model::MODEL_UNKNOWN;
  5369. }
  5370. } break;
  5371. case LLM_ARCH_XVERSE:
  5372. {
  5373. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5374. switch (hparams.n_layer) {
  5375. case 32: model.type = e_model::MODEL_7B; break;
  5376. case 40: model.type = e_model::MODEL_13B; break;
  5377. case 80: model.type = e_model::MODEL_65B; break;
  5378. default: model.type = e_model::MODEL_UNKNOWN;
  5379. }
  5380. } break;
  5381. case LLM_ARCH_COMMAND_R:
  5382. {
  5383. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5384. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5385. switch (hparams.n_layer) {
  5386. case 40: model.type = e_model::MODEL_35B; break;
  5387. default: model.type = e_model::MODEL_UNKNOWN;
  5388. }
  5389. } break;
  5390. case LLM_ARCH_DBRX:
  5391. {
  5392. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5393. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5394. switch (hparams.n_layer) {
  5395. case 40: model.type = e_model::MODEL_16x12B; break;
  5396. default: model.type = e_model::MODEL_UNKNOWN;
  5397. }
  5398. } break;
  5399. case LLM_ARCH_OLMO:
  5400. {
  5401. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5402. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5403. switch (hparams.n_layer) {
  5404. case 22: model.type = e_model::MODEL_1B; break;
  5405. case 32: model.type = e_model::MODEL_7B; break;
  5406. case 80: model.type = e_model::MODEL_70B; break;
  5407. default: model.type = e_model::MODEL_UNKNOWN;
  5408. }
  5409. } break;
  5410. case LLM_ARCH_OLMOE:
  5411. {
  5412. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5413. switch (hparams.n_layer) {
  5414. case 16: model.type = e_model::MODEL_A1_7B; break;
  5415. default: model.type = e_model::MODEL_UNKNOWN;
  5416. }
  5417. } break;
  5418. case LLM_ARCH_OPENELM:
  5419. {
  5420. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5421. switch (hparams.n_layer) {
  5422. case 16: model.type = e_model::MODEL_270M; break;
  5423. case 20: model.type = e_model::MODEL_450M; break;
  5424. case 28: model.type = e_model::MODEL_1B; break;
  5425. case 36: model.type = e_model::MODEL_3B; break;
  5426. default: model.type = e_model::MODEL_UNKNOWN;
  5427. }
  5428. } break;
  5429. case LLM_ARCH_GPTNEOX:
  5430. {
  5431. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5432. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5433. switch (hparams.n_layer) {
  5434. case 6:
  5435. switch (hparams.n_ff()) {
  5436. case 512: model.type = e_model::MODEL_14M; break;
  5437. case 2048: model.type = e_model::MODEL_70M; break;
  5438. default: model.type = e_model::MODEL_UNKNOWN;
  5439. } break;
  5440. case 12:
  5441. switch (hparams.n_ff()) {
  5442. case 3072: model.type = e_model::MODEL_160M; break;
  5443. default: model.type = e_model::MODEL_UNKNOWN;
  5444. } break;
  5445. case 16:
  5446. switch (hparams.n_ff()) {
  5447. case 8192: model.type = e_model::MODEL_1B; break;
  5448. default: model.type = e_model::MODEL_UNKNOWN;
  5449. } break;
  5450. case 24:
  5451. switch (hparams.n_ff()) {
  5452. case 4096: model.type = e_model::MODEL_410M; break;
  5453. case 8192: model.type = e_model::MODEL_1_4B; break;
  5454. default: model.type = e_model::MODEL_UNKNOWN;
  5455. } break;
  5456. case 32:
  5457. switch (hparams.n_ff()) {
  5458. case 10240: model.type = e_model::MODEL_2_8B; break;
  5459. case 16384: model.type = e_model::MODEL_6_9B; break;
  5460. default: model.type = e_model::MODEL_UNKNOWN;
  5461. } break;
  5462. case 36:
  5463. switch (hparams.n_ff()) {
  5464. case 20480: model.type = e_model::MODEL_12B; break;
  5465. default: model.type = e_model::MODEL_UNKNOWN;
  5466. } break;
  5467. case 44:
  5468. switch (hparams.n_ff()) {
  5469. case 24576: model.type = e_model::MODEL_20B; break;
  5470. default: model.type = e_model::MODEL_UNKNOWN;
  5471. } break;
  5472. default: model.type = e_model::MODEL_UNKNOWN;
  5473. }
  5474. } break;
  5475. case LLM_ARCH_ARCTIC:
  5476. {
  5477. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5478. if (hparams.n_expert == 128) {
  5479. switch (hparams.n_layer) {
  5480. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5481. default: model.type = e_model::MODEL_UNKNOWN;
  5482. }
  5483. } else {
  5484. model.type = e_model::MODEL_UNKNOWN;
  5485. }
  5486. } break;
  5487. case LLM_ARCH_DEEPSEEK2:
  5488. {
  5489. bool is_lite = (hparams.n_layer == 27);
  5490. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5491. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5492. if (!is_lite) {
  5493. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5494. }
  5495. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5496. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5497. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5498. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5499. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5500. switch (hparams.n_layer) {
  5501. case 27: model.type = e_model::MODEL_16B; break;
  5502. case 60: model.type = e_model::MODEL_236B; break;
  5503. default: model.type = e_model::MODEL_UNKNOWN;
  5504. }
  5505. } break;
  5506. case LLM_ARCH_CHATGLM:
  5507. {
  5508. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5509. switch (hparams.n_layer) {
  5510. case 28: model.type = e_model::MODEL_6B; break;
  5511. case 40: model.type = e_model::MODEL_9B; break;
  5512. default: model.type = e_model::MODEL_UNKNOWN;
  5513. }
  5514. } break;
  5515. case LLM_ARCH_BITNET:
  5516. {
  5517. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5518. switch (hparams.n_layer) {
  5519. case 26: model.type = e_model::MODEL_3B; break;
  5520. default: model.type = e_model::MODEL_UNKNOWN;
  5521. }
  5522. } break;
  5523. case LLM_ARCH_T5:
  5524. {
  5525. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5526. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5527. uint32_t dec_start_token_id;
  5528. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5529. hparams.dec_start_token_id = dec_start_token_id;
  5530. }
  5531. switch (hparams.n_layer) {
  5532. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5533. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5534. case 12:
  5535. switch (hparams.n_ff()) {
  5536. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5537. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5538. default: model.type = e_model::MODEL_UNKNOWN;
  5539. } break;
  5540. case 24:
  5541. switch (hparams.n_ff()) {
  5542. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5543. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5544. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5545. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5546. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5547. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5548. default: model.type = e_model::MODEL_UNKNOWN;
  5549. } break;
  5550. default: model.type = e_model::MODEL_UNKNOWN;
  5551. }
  5552. } break;
  5553. case LLM_ARCH_T5ENCODER:
  5554. {
  5555. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5556. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5557. model.type = e_model::MODEL_UNKNOWN;
  5558. } break;
  5559. case LLM_ARCH_JAIS:
  5560. {
  5561. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5562. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5563. switch (hparams.n_layer) {
  5564. case 24: model.type = e_model::MODEL_1_3B; break;
  5565. case 40: model.type = e_model::MODEL_13B; break;
  5566. /* TODO: add variants */
  5567. default: model.type = e_model::MODEL_UNKNOWN;
  5568. }
  5569. } break;
  5570. case LLM_ARCH_NEMOTRON:
  5571. {
  5572. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5573. switch (hparams.n_layer) {
  5574. case 32: model.type = e_model::MODEL_4B; break;
  5575. default: model.type = e_model::MODEL_UNKNOWN;
  5576. }
  5577. } break;
  5578. case LLM_ARCH_EXAONE:
  5579. {
  5580. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5581. switch (hparams.n_layer) {
  5582. case 32: model.type = e_model::MODEL_8B; break;
  5583. default: model.type = e_model::MODEL_UNKNOWN;
  5584. }
  5585. } break;
  5586. case LLM_ARCH_RWKV6:
  5587. {
  5588. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5589. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5590. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5591. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5592. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5593. switch (hparams.n_layer) {
  5594. case 24: model.type = e_model::MODEL_1_6B; break;
  5595. case 32:
  5596. switch (hparams.n_embd) {
  5597. case 2560: model.type = e_model::MODEL_3B; break;
  5598. case 4096: model.type = e_model::MODEL_7B; break;
  5599. default: model.type = e_model::MODEL_UNKNOWN;
  5600. } break;
  5601. case 61: model.type = e_model::MODEL_14B; break;
  5602. default: model.type = e_model::MODEL_UNKNOWN;
  5603. }
  5604. } break;
  5605. case LLM_ARCH_GRANITE:
  5606. case LLM_ARCH_GRANITE_MOE:
  5607. {
  5608. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5609. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5610. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5611. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5612. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5613. switch (hparams.n_layer) {
  5614. case 32: model.type = e_model::MODEL_3B; break;
  5615. case 40: model.type = e_model::MODEL_3B; break;
  5616. // Add additional layer/vocab/etc checks here for other model sizes
  5617. default: model.type = e_model::MODEL_UNKNOWN;
  5618. }
  5619. } break;
  5620. case LLM_ARCH_CHAMELEON:
  5621. {
  5622. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5623. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5624. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5625. switch (hparams.n_layer) {
  5626. case 32: model.type = e_model::MODEL_7B; break;
  5627. case 48: model.type = e_model::MODEL_34B; break;
  5628. default: model.type = e_model::MODEL_UNKNOWN;
  5629. }
  5630. } break;
  5631. case LLM_ARCH_SOLAR:
  5632. {
  5633. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5634. for (int i = 0; i < hparams.n_bskcn_arr.max_size(); ++i) {
  5635. auto & bskcn = hparams.n_bskcn_arr.at(i);
  5636. bskcn.fill(0);
  5637. 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);
  5638. }
  5639. switch (hparams.n_layer) {
  5640. case 64: model.type = e_model::MODEL_22B; break;
  5641. default: model.type = e_model::MODEL_UNKNOWN;
  5642. }
  5643. }
  5644. default: (void)0;
  5645. }
  5646. model.ftype = ml.ftype;
  5647. if (hparams.f_max_alibi_bias > 0.0f) {
  5648. hparams.use_alibi = true;
  5649. }
  5650. hparams.rope_type = llama_rope_type(&model);
  5651. }
  5652. static void llm_load_vocab(
  5653. llama_model_loader & ml,
  5654. llama_model & model) {
  5655. auto & vocab = model.vocab;
  5656. struct gguf_context * ctx = ml.meta;
  5657. const auto kv = LLM_KV(model.arch);
  5658. // determine vocab type
  5659. {
  5660. std::string tokenizer_model;
  5661. std::string tokenizer_pre;
  5662. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5663. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5664. if (tokenizer_model == "no_vocab") {
  5665. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5666. // default special tokens
  5667. vocab.special_bos_id = -1;
  5668. vocab.special_eos_id = -1;
  5669. vocab.special_unk_id = -1;
  5670. vocab.special_sep_id = -1;
  5671. vocab.special_pad_id = -1;
  5672. vocab.special_cls_id = -1;
  5673. vocab.special_mask_id = -1;
  5674. vocab.linefeed_id = -1;
  5675. // read vocab size from metadata
  5676. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5677. vocab.n_vocab = 0;
  5678. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5679. }
  5680. return;
  5681. }
  5682. if (tokenizer_model == "llama") {
  5683. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5684. // default special tokens
  5685. vocab.special_bos_id = 1;
  5686. vocab.special_eos_id = 2;
  5687. vocab.special_unk_id = 0;
  5688. vocab.special_sep_id = -1;
  5689. vocab.special_pad_id = -1;
  5690. vocab.special_cls_id = -1;
  5691. vocab.special_mask_id = -1;
  5692. } else if (tokenizer_model == "bert") {
  5693. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5694. // default special tokens
  5695. vocab.special_bos_id = -1;
  5696. vocab.special_eos_id = -1;
  5697. vocab.special_unk_id = 100;
  5698. vocab.special_sep_id = 102;
  5699. vocab.special_pad_id = 0;
  5700. vocab.special_cls_id = 101;
  5701. vocab.special_mask_id = 103;
  5702. } else if (tokenizer_model == "gpt2") {
  5703. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5704. // read bpe merges and populate bpe ranks
  5705. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5706. if (merges_keyidx == -1) {
  5707. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5708. }
  5709. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5710. for (int i = 0; i < n_merges; i++) {
  5711. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5712. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5713. std::string first;
  5714. std::string second;
  5715. const size_t pos = word.find(' ', 1);
  5716. if (pos != std::string::npos) {
  5717. first = word.substr(0, pos);
  5718. second = word.substr(pos + 1);
  5719. }
  5720. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5721. }
  5722. // default special tokens
  5723. vocab.special_bos_id = 11;
  5724. vocab.special_eos_id = 11;
  5725. vocab.special_unk_id = -1;
  5726. vocab.special_sep_id = -1;
  5727. vocab.special_pad_id = -1;
  5728. vocab.special_cls_id = -1;
  5729. vocab.special_mask_id = -1;
  5730. } else if (tokenizer_model == "t5") {
  5731. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5732. // default special tokens
  5733. vocab.special_bos_id = -1;
  5734. vocab.special_eos_id = 1;
  5735. vocab.special_unk_id = 2;
  5736. vocab.special_sep_id = -1;
  5737. vocab.special_pad_id = 0;
  5738. vocab.special_cls_id = -1;
  5739. vocab.special_mask_id = -1;
  5740. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5741. if (precompiled_charsmap_keyidx != -1) {
  5742. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5743. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5744. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5745. #ifdef IS_BIG_ENDIAN
  5746. // correct endiannes of data in precompiled_charsmap binary blob
  5747. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5748. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5749. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5750. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5751. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5752. for (size_t i = 0; i < xcda_array_size; ++i) {
  5753. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5754. }
  5755. #endif
  5756. }
  5757. } else if (tokenizer_model == "rwkv") {
  5758. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5759. // default special tokens
  5760. vocab.special_bos_id = -1;
  5761. vocab.special_eos_id = -1;
  5762. vocab.special_unk_id = -1;
  5763. vocab.special_sep_id = -1;
  5764. vocab.special_pad_id = -1;
  5765. } else {
  5766. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5767. }
  5768. // for now, only BPE models have pre-tokenizers
  5769. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5770. vocab.tokenizer_add_space_prefix = false;
  5771. vocab.tokenizer_clean_spaces = true;
  5772. if (tokenizer_pre == "default") {
  5773. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5774. } else if (
  5775. tokenizer_pre == "llama3" ||
  5776. tokenizer_pre == "llama-v3" ||
  5777. tokenizer_pre == "llama-bpe") {
  5778. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5779. vocab.tokenizer_ignore_merges = true;
  5780. vocab.tokenizer_add_bos = true;
  5781. } else if (
  5782. tokenizer_pre == "deepseek-llm") {
  5783. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5784. vocab.tokenizer_clean_spaces = false;
  5785. } else if (
  5786. tokenizer_pre == "deepseek-coder") {
  5787. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5788. vocab.tokenizer_clean_spaces = false;
  5789. } else if (
  5790. tokenizer_pre == "falcon") {
  5791. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5792. } else if (
  5793. tokenizer_pre == "mpt") {
  5794. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5795. } else if (
  5796. tokenizer_pre == "starcoder") {
  5797. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5798. } else if (
  5799. tokenizer_pre == "gpt-2" ||
  5800. tokenizer_pre == "phi-2" ||
  5801. tokenizer_pre == "jina-es" ||
  5802. tokenizer_pre == "jina-de" ||
  5803. tokenizer_pre == "jina-v1-en" ||
  5804. tokenizer_pre == "jina-v2-es" ||
  5805. tokenizer_pre == "jina-v2-de" ||
  5806. tokenizer_pre == "jina-v2-code") {
  5807. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5808. } else if (
  5809. tokenizer_pre == "refact") {
  5810. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5811. } else if (
  5812. tokenizer_pre == "command-r") {
  5813. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5814. vocab.tokenizer_clean_spaces = false;
  5815. } else if (
  5816. tokenizer_pre == "qwen2") {
  5817. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5818. vocab.tokenizer_clean_spaces = false;
  5819. } else if (
  5820. tokenizer_pre == "stablelm2") {
  5821. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5822. } else if (
  5823. tokenizer_pre == "olmo") {
  5824. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5825. } else if (
  5826. tokenizer_pre == "dbrx") {
  5827. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5828. } else if (
  5829. tokenizer_pre == "smaug-bpe") {
  5830. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5831. } else if (
  5832. tokenizer_pre == "poro-chat") {
  5833. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5834. vocab.tokenizer_clean_spaces = false;
  5835. } else if (
  5836. tokenizer_pre == "chatglm-bpe") {
  5837. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5838. vocab.special_bos_id = -1;
  5839. } else if (
  5840. tokenizer_pre == "viking") {
  5841. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5842. vocab.tokenizer_clean_spaces = false;
  5843. } else if (
  5844. tokenizer_pre == "jais") {
  5845. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5846. } else if (
  5847. tokenizer_pre == "tekken") {
  5848. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5849. vocab.tokenizer_clean_spaces = false;
  5850. vocab.tokenizer_ignore_merges = true;
  5851. vocab.tokenizer_add_bos = true;
  5852. } else if (
  5853. tokenizer_pre == "smollm") {
  5854. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5855. vocab.tokenizer_clean_spaces = false;
  5856. } else if (
  5857. tokenizer_pre == "codeshell") {
  5858. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5859. } else if (
  5860. tokenizer_pre == "bloom") {
  5861. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5862. } else if (
  5863. tokenizer_pre == "gpt3-finnish") {
  5864. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5865. } else if (
  5866. tokenizer_pre == "exaone") {
  5867. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5868. } else if (
  5869. tokenizer_pre == "chameleon") {
  5870. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5871. vocab.tokenizer_add_bos = true;
  5872. vocab.tokenizer_clean_spaces = false;
  5873. } else {
  5874. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  5875. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5876. }
  5877. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5878. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5879. vocab.tokenizer_add_space_prefix = true;
  5880. vocab.tokenizer_clean_spaces = false;
  5881. vocab.tokenizer_add_bos = true;
  5882. vocab.tokenizer_add_eos = false;
  5883. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5884. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5885. vocab.tokenizer_add_space_prefix = false;
  5886. vocab.tokenizer_clean_spaces = true;
  5887. vocab.tokenizer_add_bos = true;
  5888. vocab.tokenizer_add_eos = false;
  5889. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  5890. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5891. vocab.tokenizer_add_bos = false;
  5892. vocab.tokenizer_add_eos = true;
  5893. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5894. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5895. vocab.tokenizer_add_space_prefix = false;
  5896. vocab.tokenizer_clean_spaces = false;
  5897. vocab.tokenizer_add_bos = false;
  5898. vocab.tokenizer_add_eos = false;
  5899. } else {
  5900. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5901. }
  5902. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  5903. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  5904. }
  5905. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  5906. if (token_idx == -1) {
  5907. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  5908. }
  5909. const float * scores = nullptr;
  5910. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  5911. if (score_idx != -1) {
  5912. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  5913. }
  5914. const int * toktypes = nullptr;
  5915. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  5916. if (toktype_idx != -1) {
  5917. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  5918. }
  5919. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  5920. vocab.n_vocab = n_vocab;
  5921. vocab.id_to_token.resize(n_vocab);
  5922. for (uint32_t i = 0; i < n_vocab; i++) {
  5923. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  5924. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5925. if (word.empty()) {
  5926. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  5927. word = "[EMPTY_" + std::to_string(i) + "]";
  5928. }
  5929. vocab.token_to_id[word] = i;
  5930. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  5931. auto & token_data = vocab.id_to_token[i];
  5932. token_data.text = std::move(word);
  5933. token_data.score = scores ? scores[i] : 0.0f;
  5934. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  5935. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  5936. switch(toktypes[i]) {
  5937. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  5938. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  5939. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  5940. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  5941. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  5942. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  5943. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5944. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5945. }
  5946. }
  5947. }
  5948. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  5949. vocab.init_tokenizer();
  5950. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  5951. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5952. // For Fill-In-the-Middle (FIM)/infill models which where converted
  5953. // prior to support of FIM special tokens in GGUF, the following
  5954. // will allow those models to continue to work. The general names
  5955. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  5956. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  5957. // new versions of these models have been published.
  5958. std::string gen_name;
  5959. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  5960. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  5961. [](unsigned char c){ return std::tolower(c); });
  5962. if (gen_name.find("code") != std::string::npos) {
  5963. if (model.arch == LLM_ARCH_LLAMA
  5964. && 32010 < vocab.id_to_token.size()
  5965. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  5966. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  5967. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  5968. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  5969. vocab.special_prefix_id = 32007;
  5970. vocab.special_suffix_id = 32008;
  5971. vocab.special_middle_id = 32009;
  5972. vocab.special_eot_id = 32010;
  5973. } else if (model.arch == LLM_ARCH_GEMMA
  5974. && 107 < vocab.id_to_token.size()
  5975. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  5976. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  5977. && vocab.id_to_token[68].text == "<|fim_middle|>"
  5978. && vocab.id_to_token[107].text == "<end_of_turn>") {
  5979. vocab.special_prefix_id = 67;
  5980. vocab.special_suffix_id = 69;
  5981. vocab.special_middle_id = 68;
  5982. // TODO: this is not EOT, it is "file separator" token, needs fix
  5983. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  5984. //vocab.special_eot_id = 70;
  5985. vocab.special_eot_id = 107;
  5986. }
  5987. }
  5988. try {
  5989. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  5990. } catch (const std::exception & e) {
  5991. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  5992. vocab.linefeed_id = vocab.special_pad_id;
  5993. }
  5994. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5995. vocab.linefeed_id = vocab.special_pad_id;
  5996. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5997. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  5998. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  5999. vocab.linefeed_id = ids[0];
  6000. } else {
  6001. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  6002. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  6003. if (ids.empty()) {
  6004. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  6005. vocab.linefeed_id = vocab.special_pad_id;
  6006. } else {
  6007. vocab.linefeed_id = ids[0];
  6008. }
  6009. }
  6010. // special tokens
  6011. {
  6012. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  6013. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  6014. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  6015. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  6016. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  6017. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  6018. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  6019. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  6020. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  6021. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  6022. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  6023. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  6024. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  6025. };
  6026. for (const auto & it : special_token_types) {
  6027. const std::string & key = kv(std::get<0>(it));
  6028. int32_t & id = std::get<1>(it);
  6029. uint32_t new_id;
  6030. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  6031. continue;
  6032. }
  6033. if (new_id >= vocab.id_to_token.size()) {
  6034. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  6035. __func__, key.c_str(), new_id, id);
  6036. } else {
  6037. id = new_id;
  6038. }
  6039. }
  6040. // Handle add_bos_token and add_eos_token
  6041. {
  6042. bool temp = true;
  6043. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  6044. vocab.tokenizer_add_bos = temp;
  6045. }
  6046. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  6047. vocab.tokenizer_add_eos = temp;
  6048. }
  6049. }
  6050. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  6051. //
  6052. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  6053. // for now, we apply this workaround to find the EOT token based on its text
  6054. if (vocab.special_eot_id == -1) {
  6055. for (const auto & t : vocab.token_to_id) {
  6056. if (false
  6057. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  6058. // need to fix convert script
  6059. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  6060. || t.first == "<|eot_id|>"
  6061. || t.first == "<|im_end|>"
  6062. || t.first == "<|end|>"
  6063. || t.first == "<end_of_turn>"
  6064. || t.first == "<|endoftext|>"
  6065. || t.first == "<EOT>"
  6066. ) {
  6067. vocab.special_eot_id = t.second;
  6068. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6069. 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",
  6070. __func__, t.first.c_str());
  6071. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6072. }
  6073. break;
  6074. }
  6075. }
  6076. }
  6077. // find EOM token: "<|eom_id|>"
  6078. //
  6079. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOM_ID
  6080. // for now, we apply this workaround to find the EOM token based on its text
  6081. if (vocab.special_eom_id == -1) {
  6082. const auto & t = vocab.token_to_id.find("<|eom_id|>");
  6083. if (t != vocab.token_to_id.end()) {
  6084. vocab.special_eom_id = t->second;
  6085. if ((vocab.id_to_token[t->second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6086. 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",
  6087. __func__, t->first.c_str());
  6088. vocab.id_to_token[t->second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6089. }
  6090. }
  6091. }
  6092. // maintain a list of tokens that cause end-of-generation
  6093. // this is currently determined based on the token text, which is obviously not ideal
  6094. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  6095. vocab.special_eog_ids.clear();
  6096. for (const auto & t : vocab.token_to_id) {
  6097. if (false
  6098. || t.first == "<|eot_id|>"
  6099. || t.first == "<|im_end|>"
  6100. || t.first == "<|end|>"
  6101. || t.first == "<end_of_turn>"
  6102. || t.first == "<|endoftext|>"
  6103. || t.first == "<|eom_id|>"
  6104. || t.first == "<EOT>"
  6105. ) {
  6106. vocab.special_eog_ids.insert(t.second);
  6107. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  6108. 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",
  6109. __func__, t.first.c_str());
  6110. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  6111. }
  6112. }
  6113. }
  6114. if (vocab.special_eos_id != -1 && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  6115. vocab.special_eog_ids.insert(vocab.special_eos_id);
  6116. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6117. }
  6118. if (vocab.special_eot_id != -1 && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  6119. vocab.special_eog_ids.insert(vocab.special_eot_id);
  6120. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6121. }
  6122. if (vocab.special_eom_id != -1 && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  6123. vocab.special_eog_ids.insert(vocab.special_eom_id);
  6124. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  6125. }
  6126. }
  6127. // build special tokens cache
  6128. {
  6129. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6130. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6131. vocab.cache_special_tokens.push_back(id);
  6132. }
  6133. }
  6134. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6135. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6136. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6137. }
  6138. );
  6139. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6140. }
  6141. // build token to piece cache
  6142. {
  6143. size_t size_cache = 0;
  6144. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6145. for (uint32_t id = 0; id < n_vocab; ++id) {
  6146. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6147. size_cache += cache_token_to_piece[id].size();
  6148. }
  6149. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6150. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6151. }
  6152. // Handle per token attributes
  6153. //NOTE: Each model customizes per token attributes.
  6154. //NOTE: Per token attributes are missing from the GGUF file.
  6155. //TODO: Extract attributes from GGUF file.
  6156. {
  6157. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6158. for (auto substr : substrs) {
  6159. if (str.find(substr) < std::string::npos) {
  6160. return true;
  6161. }
  6162. }
  6163. return false;
  6164. };
  6165. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6166. uint32_t current = vocab.id_to_token.at(id).attr;
  6167. current = value ? (current | attr) : (current & ~attr);
  6168. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6169. };
  6170. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6171. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6172. };
  6173. std::string model_name;
  6174. std::string tokenizer_pre;
  6175. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6176. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6177. // model name to lowercase
  6178. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6179. [] (const std::string::value_type x) {
  6180. return std::tolower(x);
  6181. }
  6182. );
  6183. // set attributes by model/tokenizer name
  6184. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6185. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6186. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6187. for (auto id : vocab.cache_special_tokens) {
  6188. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6189. }
  6190. for (auto token : {"</s>"}) {
  6191. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6192. }
  6193. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6194. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6195. }
  6196. }
  6197. }
  6198. }
  6199. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6200. const auto & hparams = model.hparams;
  6201. const auto & vocab = model.vocab;
  6202. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6203. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6204. bool is_var = false;
  6205. std::vector<uint32_t> v;
  6206. for (uint32_t i = 0; i < n; ++i) {
  6207. v.push_back(f(i));
  6208. if (v[i] != v[0]) {
  6209. is_var = true;
  6210. }
  6211. }
  6212. std::stringstream ss;
  6213. if (is_var) {
  6214. ss << "[";
  6215. for (uint32_t i = 0; i < n; ++i) {
  6216. ss << v[i];
  6217. if (i < n - 1) {
  6218. ss << ", ";
  6219. }
  6220. }
  6221. ss << "]";
  6222. } else {
  6223. ss << v[0];
  6224. }
  6225. return ss.str();
  6226. };
  6227. // hparams
  6228. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6229. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6230. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6231. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6232. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6233. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6234. if (!hparams.vocab_only) {
  6235. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6236. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6237. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6238. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6239. 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());
  6240. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6241. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6242. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6243. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6244. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6245. 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());
  6246. 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());
  6247. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6248. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6249. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6250. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6251. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6252. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6253. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6254. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6255. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6256. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6257. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6258. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6259. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6260. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6261. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6262. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6263. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6264. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6265. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6266. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6267. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6268. }
  6269. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6270. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6271. if (ml.n_elements >= 1e12) {
  6272. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6273. } else if (ml.n_elements >= 1e9) {
  6274. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6275. } else if (ml.n_elements >= 1e6) {
  6276. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6277. } else {
  6278. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6279. }
  6280. if (ml.n_bytes < GiB) {
  6281. 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);
  6282. } else {
  6283. 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);
  6284. }
  6285. // general kv
  6286. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6287. // special tokens
  6288. 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() ); }
  6289. 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() ); }
  6290. 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() ); }
  6291. 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() ); }
  6292. 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() ); }
  6293. 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() ); }
  6294. 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() ); }
  6295. 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() ); }
  6296. 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() ); }
  6297. 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() ); }
  6298. 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() ); }
  6299. 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() ); }
  6300. 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() ); }
  6301. for (const auto & id : vocab.special_eog_ids) {
  6302. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6303. }
  6304. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6305. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6306. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6307. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6308. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6309. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6310. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6311. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6312. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6313. }
  6314. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6315. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6316. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6317. }
  6318. if (model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6319. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6320. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6321. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6322. }
  6323. }
  6324. // Returns false if cancelled by progress_callback
  6325. static bool llm_load_tensors(
  6326. llama_model_loader & ml,
  6327. llama_model & model,
  6328. int n_gpu_layers,
  6329. enum llama_split_mode split_mode,
  6330. int main_gpu,
  6331. const float * tensor_split,
  6332. bool use_mlock,
  6333. llama_progress_callback progress_callback,
  6334. void * progress_callback_user_data) {
  6335. auto & hparams = model.hparams;
  6336. model.split_mode = split_mode;
  6337. model.main_gpu = main_gpu;
  6338. model.n_gpu_layers = n_gpu_layers;
  6339. const int n_layer = hparams.n_layer;
  6340. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6341. bool use_mmap_buffer = true;
  6342. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6343. model.buft_input = llama_default_buffer_type_cpu(true);
  6344. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  6345. model.buft_layer.resize(n_layer);
  6346. // assign cpu layers
  6347. for (int i = 0; i < i_gpu_start; ++i) {
  6348. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  6349. }
  6350. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  6351. // calculate the split points
  6352. int device_count = llama_get_device_count(model);
  6353. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6354. std::vector<float> splits(device_count);
  6355. if (all_zero) {
  6356. // default split, by free memory
  6357. for (int i = 0; i < device_count; ++i) {
  6358. splits[i] = llama_get_device_memory(model, i);
  6359. }
  6360. } else {
  6361. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6362. }
  6363. // sum and normalize the splits to get the split points
  6364. float split_sum = 0.0f;
  6365. for (int i = 0; i < device_count; ++i) {
  6366. split_sum += splits[i];
  6367. splits[i] = split_sum;
  6368. }
  6369. for (int i = 0; i < device_count; ++i) {
  6370. splits[i] /= split_sum;
  6371. }
  6372. // assign the repeating layers to the devices according to the splits
  6373. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  6374. for (int i = i_gpu_start; i < n_layer; ++i) {
  6375. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  6376. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  6377. }
  6378. // assign the output layer
  6379. if (n_gpu_layers > n_layer) {
  6380. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  6381. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  6382. } else {
  6383. model.buft_output = llama_default_buffer_type_cpu(true);
  6384. }
  6385. } else {
  6386. ggml_backend_buffer_type_t split_buft;
  6387. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6388. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  6389. } else {
  6390. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  6391. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  6392. }
  6393. // assign the repeating layers
  6394. for (int i = i_gpu_start; i < n_layer; ++i) {
  6395. model.buft_layer[i] = {
  6396. split_buft,
  6397. llama_default_buffer_type_offload(model, main_gpu)
  6398. };
  6399. }
  6400. // assign the output layer
  6401. if (n_gpu_layers > n_layer) {
  6402. model.buft_output = {
  6403. split_buft,
  6404. llama_default_buffer_type_offload(model, main_gpu)
  6405. };
  6406. } else {
  6407. model.buft_output = llama_default_buffer_type_cpu(true);
  6408. }
  6409. }
  6410. // count used buffer types
  6411. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  6412. buft_layer_count[model.buft_input.buft]++;
  6413. buft_layer_count[model.buft_input.buft_matrix]++;
  6414. buft_layer_count[model.buft_output.buft]++;
  6415. buft_layer_count[model.buft_output.buft_matrix]++;
  6416. for (int i = 0; i < n_layer; ++i) {
  6417. buft_layer_count[model.buft_layer[i].buft]++;
  6418. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  6419. }
  6420. // create one context per buffer type
  6421. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  6422. // for moe merged tensors
  6423. ctx_size += ggml_tensor_overhead()*n_layer*3;
  6424. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6425. for (auto & it : buft_layer_count) {
  6426. struct ggml_init_params params = {
  6427. /*.mem_size =*/ ctx_size,
  6428. /*.mem_buffer =*/ NULL,
  6429. /*.no_alloc =*/ true,
  6430. };
  6431. ggml_context * ctx = ggml_init(params);
  6432. if (!ctx) {
  6433. throw std::runtime_error(format("failed to create context"));
  6434. }
  6435. ctx_map[it.first] = ctx;
  6436. model.ctxs.push_back(ctx);
  6437. }
  6438. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  6439. // create tensors for the weights
  6440. {
  6441. // note: cast to int64_t since we will use these for the tensor dimensions
  6442. const int64_t n_head = hparams.n_head();
  6443. const int64_t n_head_kv = hparams.n_head_kv();
  6444. const int64_t n_embd = hparams.n_embd;
  6445. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6446. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6447. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6448. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6449. const int64_t n_ff = hparams.n_ff();
  6450. const int64_t n_embd_gqa = n_embd_v_gqa;
  6451. const int64_t n_vocab = hparams.n_vocab;
  6452. const int64_t n_vocab_type = hparams.n_vocab_type;
  6453. const int64_t n_rot = hparams.n_rot;
  6454. const int64_t n_expert = hparams.n_expert;
  6455. const int64_t n_expert_used = hparams.n_expert_used;
  6456. const int64_t n_ctx_train = hparams.n_ctx_train;
  6457. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6458. throw std::runtime_error("model has expert layers but no expert layers are used");
  6459. }
  6460. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  6461. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  6462. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  6463. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  6464. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  6465. model.layers.resize(n_layer);
  6466. const auto tn = LLM_TN(model.arch);
  6467. switch (model.arch) {
  6468. case LLM_ARCH_LLAMA:
  6469. case LLM_ARCH_REFACT:
  6470. case LLM_ARCH_MINICPM:
  6471. case LLM_ARCH_GRANITE:
  6472. case LLM_ARCH_GRANITE_MOE:
  6473. {
  6474. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6475. // output
  6476. {
  6477. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6478. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6479. // if output is NULL, init from the input tok embed
  6480. if (model.output == NULL) {
  6481. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6482. }
  6483. }
  6484. for (int i = 0; i < n_layer; ++i) {
  6485. ggml_context * ctx_layer = ctx_for_layer(i);
  6486. ggml_context * ctx_split = ctx_for_layer_split(i);
  6487. auto & layer = model.layers[i];
  6488. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6489. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6490. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6491. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6492. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6493. // optional bias tensors
  6494. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6495. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6496. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6497. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6498. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6499. 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));
  6500. if (n_expert == 0) {
  6501. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6502. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6503. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6504. // optional MLP bias
  6505. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6506. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6507. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6508. } else {
  6509. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6510. 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);
  6511. if (layer.ffn_gate_exps) {
  6512. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6513. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6514. } else {
  6515. // merge split expert into a single tensor for compatibility with older models
  6516. // requires disabling mmap
  6517. use_mmap_buffer = false;
  6518. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6519. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6520. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6521. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6522. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6523. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6524. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6525. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6526. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6527. for (uint32_t x = 0; x < n_expert; ++x) {
  6528. // the individual experts are loaded into a view of the merged tensor
  6529. 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);
  6530. 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);
  6531. 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);
  6532. }
  6533. }
  6534. }
  6535. }
  6536. } break;
  6537. case LLM_ARCH_MINICPM3:
  6538. {
  6539. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6540. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6541. const int64_t q_lora_rank = hparams.n_lora_q;
  6542. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6543. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6544. // output
  6545. {
  6546. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6547. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6548. // if output is NULL, init from the input tok embed
  6549. if (model.output == NULL) {
  6550. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6551. }
  6552. }
  6553. for (int i = 0; i < n_layer; ++i) {
  6554. ggml_context * ctx_layer = ctx_for_layer(i);
  6555. ggml_context * ctx_split = ctx_for_layer_split(i);
  6556. auto & layer = model.layers[i];
  6557. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6558. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6559. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6560. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6561. 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});
  6562. 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)});
  6563. 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)});
  6564. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6565. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6566. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6567. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6568. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6569. 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));
  6570. 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));
  6571. }
  6572. } break;
  6573. case LLM_ARCH_MLLAMA:
  6574. {
  6575. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab+8});
  6576. // output
  6577. {
  6578. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6579. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6580. // if output is NULL, init from the input tok embed
  6581. if (model.output == NULL) {
  6582. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6583. }
  6584. }
  6585. for (int i = 0; i < n_layer; ++i) {
  6586. ggml_context * ctx_layer = ctx_for_layer(i);
  6587. ggml_context * ctx_split = ctx_for_layer_split(i);
  6588. auto & layer = model.layers[i];
  6589. if (hparams.cross_attention_layers(i)) {
  6590. layer.cross_attn_k_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_K_NORM, "weight", i), {128});
  6591. layer.cross_attn_k_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_K_PROJ, "weight", i), {n_embd, 1024});
  6592. layer.cross_attn_o_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_O_PROJ, "weight", i), {n_embd, n_embd});
  6593. layer.cross_attn_q_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_Q_NORM, "weight", i), {128});
  6594. layer.cross_attn_q_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_Q_PROJ, "weight", i), {n_embd, n_embd});
  6595. layer.cross_attn_v_proj = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_V_PROJ, "weight", i), {n_embd, 1024});
  6596. layer.cross_attn_attn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_ATTN_GATE, i), {1});
  6597. layer.cross_attn_mlp_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_CROSS_ATTN_MLP_GATE, i), {1});
  6598. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6599. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6600. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6601. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6602. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6603. } else {
  6604. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6605. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6606. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6607. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6608. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6609. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6610. 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));
  6611. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6612. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6613. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6614. }
  6615. }
  6616. } break;
  6617. case LLM_ARCH_GROK:
  6618. {
  6619. if (n_expert == 0) {
  6620. throw std::runtime_error("Grok model cannot have zero experts");
  6621. }
  6622. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6623. // output
  6624. {
  6625. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6626. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6627. // if output is NULL, init from the input tok embed
  6628. if (model.output == NULL) {
  6629. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6630. }
  6631. }
  6632. for (int i = 0; i < n_layer; ++i) {
  6633. ggml_context * ctx_layer = ctx_for_layer(i);
  6634. ggml_context * ctx_split = ctx_for_layer_split(i);
  6635. auto & layer = model.layers[i];
  6636. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6637. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6638. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6639. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6640. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6641. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6642. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6643. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6644. 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);
  6645. if (layer.ffn_gate_exps) {
  6646. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6647. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6648. } else {
  6649. // merge split expert into a single tensor for compatibility with older models
  6650. // requires disabling mmap
  6651. use_mmap_buffer = false;
  6652. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6653. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6654. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6655. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6656. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6657. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6658. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6659. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6660. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6661. for (uint32_t x = 0; x < n_expert; ++x) {
  6662. // the individual experts are loaded into a view of the merged tensor
  6663. 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);
  6664. 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);
  6665. 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);
  6666. }
  6667. }
  6668. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6669. }
  6670. } break;
  6671. case LLM_ARCH_DBRX:
  6672. {
  6673. if (n_expert == 0) {
  6674. throw std::runtime_error("DBRX model cannot have zero experts");
  6675. }
  6676. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6677. // output
  6678. {
  6679. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6680. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6681. }
  6682. for (int i = 0; i < n_layer; ++i) {
  6683. ggml_context * ctx_layer = ctx_for_layer(i);
  6684. ggml_context * ctx_split = ctx_for_layer_split(i);
  6685. auto & layer = model.layers[i];
  6686. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6687. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6688. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6689. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6690. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6691. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6692. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  6693. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6694. }
  6695. } break;
  6696. case LLM_ARCH_BAICHUAN:
  6697. {
  6698. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6699. {
  6700. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6701. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6702. }
  6703. for (int i = 0; i < n_layer; ++i) {
  6704. ggml_context * ctx_layer = ctx_for_layer(i);
  6705. ggml_context * ctx_split = ctx_for_layer_split(i);
  6706. auto & layer = model.layers[i];
  6707. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6708. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6709. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6710. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6711. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6712. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6713. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6714. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6715. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6716. }
  6717. } break;
  6718. case LLM_ARCH_FALCON:
  6719. {
  6720. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6721. // output
  6722. {
  6723. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6724. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6725. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6726. if (!model.output) {
  6727. 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
  6728. }
  6729. }
  6730. for (int i = 0; i < n_layer; ++i) {
  6731. ggml_context * ctx_layer = ctx_for_layer(i);
  6732. ggml_context * ctx_split = ctx_for_layer_split(i);
  6733. auto & layer = model.layers[i];
  6734. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6735. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6736. 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);
  6737. 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);
  6738. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6739. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6740. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6741. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6742. }
  6743. } break;
  6744. case LLM_ARCH_STARCODER:
  6745. {
  6746. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6747. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6748. // output
  6749. {
  6750. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6751. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6752. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6753. if (!model.output) {
  6754. // needs to be on GPU
  6755. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6756. }
  6757. }
  6758. for (int i = 0; i < n_layer; ++i) {
  6759. ggml_context * ctx_layer = ctx_for_layer(i);
  6760. ggml_context * ctx_split = ctx_for_layer_split(i);
  6761. auto & layer = model.layers[i];
  6762. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6763. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6764. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6765. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6766. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6767. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6768. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6769. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6770. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6771. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6772. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6773. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6774. }
  6775. } break;
  6776. case LLM_ARCH_BERT:
  6777. case LLM_ARCH_NOMIC_BERT:
  6778. {
  6779. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6780. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  6781. if (model.arch == LLM_ARCH_BERT) {
  6782. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6783. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6784. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6785. model.cls_out = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6786. model.cls_out_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6787. }
  6788. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6789. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6790. for (int i = 0; i < n_layer; ++i) {
  6791. ggml_context * ctx_layer = ctx_for_layer(i);
  6792. ggml_context * ctx_split = ctx_for_layer_split(i);
  6793. auto & layer = model.layers[i];
  6794. if (model.arch == LLM_ARCH_BERT) {
  6795. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6796. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6797. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6798. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6799. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6800. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6801. } else {
  6802. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6803. }
  6804. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6805. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6806. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6807. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6808. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6809. if (model.arch == LLM_ARCH_BERT) {
  6810. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6811. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6812. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6813. } else {
  6814. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6815. }
  6816. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6817. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6818. }
  6819. } break;
  6820. case LLM_ARCH_JINA_BERT_V2:
  6821. {
  6822. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  6823. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  6824. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  6825. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  6826. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6827. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6828. for (int i = 0; i < n_layer; ++i) {
  6829. ggml_context * ctx_layer = ctx_for_layer(i);
  6830. ggml_context * ctx_split = ctx_for_layer_split(i);
  6831. auto & layer = model.layers[i]; // JinaBertLayer
  6832. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6833. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6834. 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);
  6835. 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);
  6836. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6837. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6838. 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);
  6839. 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);
  6840. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6841. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6842. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  6843. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  6844. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  6845. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6846. 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);
  6847. 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);
  6848. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6849. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6850. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6851. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6852. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6853. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6854. }
  6855. } break;
  6856. case LLM_ARCH_BLOOM:
  6857. {
  6858. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6859. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6860. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6861. // output
  6862. {
  6863. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6864. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6865. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6866. }
  6867. for (int i = 0; i < n_layer; ++i) {
  6868. ggml_context * ctx_layer = ctx_for_layer(i);
  6869. ggml_context * ctx_split = ctx_for_layer_split(i);
  6870. auto & layer = model.layers[i];
  6871. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6872. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6873. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6874. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6875. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6876. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6877. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6878. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6879. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6880. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6881. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6882. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6883. }
  6884. } break;
  6885. case LLM_ARCH_MPT:
  6886. {
  6887. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6888. 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);
  6889. // output
  6890. {
  6891. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6892. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6893. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6894. if (!model.output) {
  6895. 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
  6896. }
  6897. }
  6898. for (int i = 0; i < n_layer; ++i) {
  6899. ggml_context * ctx_layer = ctx_for_layer(i);
  6900. ggml_context * ctx_split = ctx_for_layer_split(i);
  6901. auto & layer = model.layers[i];
  6902. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6903. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6904. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6905. 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);
  6906. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6907. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6908. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6909. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6910. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6911. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6912. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6913. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6914. 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);
  6915. 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);
  6916. 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);
  6917. 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);
  6918. // AWQ ScaleActivation layer
  6919. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6920. }
  6921. } break;
  6922. case LLM_ARCH_STABLELM:
  6923. {
  6924. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6925. // output
  6926. {
  6927. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6928. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6929. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6930. }
  6931. for (int i = 0; i < n_layer; ++i) {
  6932. ggml_context * ctx_layer = ctx_for_layer(i);
  6933. ggml_context * ctx_split = ctx_for_layer_split(i);
  6934. auto & layer = model.layers[i];
  6935. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6936. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6937. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6938. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6939. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6940. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6941. // optional bias tensors, present in Stable LM 2 1.6B
  6942. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6943. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6944. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6945. // optional q and k layernorms, present in StableLM 2 12B
  6946. 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);
  6947. 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);
  6948. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  6949. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6950. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6951. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6952. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6953. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6954. }
  6955. } break;
  6956. case LLM_ARCH_QWEN:
  6957. {
  6958. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6959. // output
  6960. {
  6961. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6962. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6963. }
  6964. for (int i = 0; i < n_layer; ++i) {
  6965. ggml_context * ctx_layer = ctx_for_layer(i);
  6966. ggml_context * ctx_split = ctx_for_layer_split(i);
  6967. auto & layer = model.layers[i];
  6968. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6969. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  6970. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  6971. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6972. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6973. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  6974. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  6975. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  6976. }
  6977. } break;
  6978. case LLM_ARCH_QWEN2:
  6979. {
  6980. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6981. // output
  6982. {
  6983. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6984. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6985. // if output is NULL, init from the input tok embed
  6986. if (model.output == NULL) {
  6987. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6988. }
  6989. }
  6990. for (int i = 0; i < n_layer; ++i) {
  6991. ggml_context * ctx_layer = ctx_for_layer(i);
  6992. ggml_context * ctx_split = ctx_for_layer_split(i);
  6993. auto & layer = model.layers[i];
  6994. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6995. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6996. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6997. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6998. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6999. // optional bias tensors
  7000. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7001. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7002. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7003. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7004. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7005. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7006. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7007. }
  7008. } break;
  7009. case LLM_ARCH_QWEN2MOE:
  7010. {
  7011. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7012. // output
  7013. {
  7014. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7015. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7016. }
  7017. for (int i = 0; i < n_layer; ++i) {
  7018. ggml_context * ctx_layer = ctx_for_layer(i);
  7019. ggml_context * ctx_split = ctx_for_layer_split(i);
  7020. auto & layer = model.layers[i];
  7021. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7022. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7023. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7024. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7025. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7026. // optional bias tensors
  7027. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7028. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7029. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7030. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7031. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7032. GGML_ASSERT(n_expert > 0);
  7033. GGML_ASSERT(n_expert_used > 0);
  7034. // MoE branch
  7035. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  7036. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7037. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  7038. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7039. // Shared expert branch
  7040. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  7041. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  7042. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  7043. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  7044. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  7045. }
  7046. } break;
  7047. case LLM_ARCH_PHI2:
  7048. {
  7049. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7050. // output
  7051. {
  7052. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7053. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7054. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7055. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  7056. }
  7057. for (int i = 0; i < n_layer; ++i) {
  7058. ggml_context * ctx_layer = ctx_for_layer(i);
  7059. ggml_context * ctx_split = ctx_for_layer_split(i);
  7060. auto & layer = model.layers[i];
  7061. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7062. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7063. 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);
  7064. 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);
  7065. if (layer.wqkv == nullptr) {
  7066. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7067. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7068. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7069. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7070. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7071. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7072. }
  7073. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7074. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7075. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7076. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7077. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7078. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7079. }
  7080. } break;
  7081. case LLM_ARCH_PHI3:
  7082. {
  7083. const int64_t n_embd_head = n_embd / n_head;
  7084. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  7085. // output
  7086. {
  7087. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  7088. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  7089. }
  7090. for (int i = 0; i < n_layer; ++i) {
  7091. ggml_context * ctx_layer = ctx_for_layer(i);
  7092. ggml_context * ctx_split = ctx_for_layer_split(i);
  7093. auto & layer = model.layers[i];
  7094. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  7095. 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);
  7096. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  7097. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  7098. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  7099. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  7100. 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));
  7101. 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));
  7102. }
  7103. } break;
  7104. case LLM_ARCH_PLAMO:
  7105. {
  7106. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7107. // output
  7108. {
  7109. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7110. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7111. }
  7112. for (int i = 0; i < n_layer; ++i) {
  7113. ggml_context * ctx_layer = ctx_for_layer(i);
  7114. ggml_context * ctx_split = ctx_for_layer_split(i);
  7115. auto & layer = model.layers[i];
  7116. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7117. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7118. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7119. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7120. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7121. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7122. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7123. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7124. }
  7125. } break;
  7126. case LLM_ARCH_GPT2:
  7127. {
  7128. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7129. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  7130. // output
  7131. {
  7132. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7133. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7134. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7135. }
  7136. for (int i = 0; i < n_layer; ++i) {
  7137. ggml_context * ctx_layer = ctx_for_layer(i);
  7138. ggml_context * ctx_split = ctx_for_layer_split(i);
  7139. auto & layer = model.layers[i];
  7140. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7141. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7142. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7143. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7144. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7145. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7146. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7147. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7148. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7149. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7150. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7151. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7152. }
  7153. } break;
  7154. case LLM_ARCH_CODESHELL:
  7155. {
  7156. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7157. // output
  7158. {
  7159. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7160. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7161. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7162. }
  7163. for (int i = 0; i < n_layer; ++i) {
  7164. ggml_context * ctx_layer = ctx_for_layer(i);
  7165. ggml_context * ctx_split = ctx_for_layer_split(i);
  7166. auto & layer = model.layers[i];
  7167. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7168. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7169. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7170. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7171. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7172. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7173. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7174. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7175. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7176. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7177. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7178. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7179. }
  7180. } break;
  7181. case LLM_ARCH_ORION:
  7182. {
  7183. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7184. {
  7185. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7186. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7187. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7188. }
  7189. for (int i = 0; i < n_layer; ++i) {
  7190. ggml_context * ctx_layer = ctx_for_layer(i);
  7191. ggml_context * ctx_split = ctx_for_layer_split(i);
  7192. auto & layer = model.layers[i];
  7193. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7194. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7195. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7196. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7197. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7198. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7199. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7200. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7201. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7202. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7203. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7204. }
  7205. } break;
  7206. case LLM_ARCH_INTERNLM2:
  7207. {
  7208. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7209. // output
  7210. {
  7211. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7212. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7213. }
  7214. for (int i = 0; i < n_layer; ++i) {
  7215. ggml_context * ctx_layer = ctx_for_layer(i);
  7216. ggml_context * ctx_split = ctx_for_layer_split(i);
  7217. auto & layer = model.layers[i];
  7218. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7219. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7220. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7221. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7222. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7223. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7224. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7225. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7226. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7227. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7228. }
  7229. } break;
  7230. case LLM_ARCH_GEMMA:
  7231. {
  7232. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7233. // output
  7234. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7235. 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
  7236. for (int i = 0; i < n_layer; ++i) {
  7237. ggml_context * ctx_layer = ctx_for_layer(i);
  7238. ggml_context * ctx_split = ctx_for_layer_split(i);
  7239. auto & layer = model.layers[i];
  7240. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7241. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7242. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7243. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7244. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7245. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7246. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7247. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7248. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7249. }
  7250. } break;
  7251. case LLM_ARCH_GEMMA2:
  7252. {
  7253. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7254. // output
  7255. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7256. 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
  7257. for (int i = 0; i < n_layer; ++i) {
  7258. ggml_context * ctx_layer = ctx_for_layer(i);
  7259. ggml_context * ctx_split = ctx_for_layer_split(i);
  7260. auto & layer = model.layers[i];
  7261. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7262. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7263. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7264. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7265. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7266. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  7267. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7268. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7269. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7270. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7271. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  7272. }
  7273. } break;
  7274. case LLM_ARCH_STARCODER2:
  7275. {
  7276. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7277. // output
  7278. {
  7279. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7280. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7281. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7282. // if output is NULL, init from the input tok embed
  7283. if (model.output == NULL) {
  7284. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7285. }
  7286. }
  7287. for (int i = 0; i < n_layer; ++i) {
  7288. ggml_context * ctx_layer = ctx_for_layer(i);
  7289. ggml_context * ctx_split = ctx_for_layer_split(i);
  7290. auto & layer = model.layers[i];
  7291. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7292. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7293. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7294. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7295. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7296. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7297. // optional bias tensors
  7298. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7299. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7300. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7301. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7302. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7303. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7304. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7305. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7306. // optional bias tensors
  7307. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7308. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  7309. }
  7310. } break;
  7311. case LLM_ARCH_MAMBA:
  7312. {
  7313. const int64_t d_conv = hparams.ssm_d_conv;
  7314. const int64_t d_inner = hparams.ssm_d_inner;
  7315. const int64_t d_state = hparams.ssm_d_state;
  7316. const int64_t dt_rank = hparams.ssm_dt_rank;
  7317. // only an expansion factor of 2 is supported for now
  7318. GGML_ASSERT(2 * n_embd == d_inner);
  7319. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7320. // output
  7321. {
  7322. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7323. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7324. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7325. if (model.output == NULL) {
  7326. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7327. }
  7328. }
  7329. for (int i = 0; i < n_layer; ++i) {
  7330. ggml_context * ctx_layer = ctx_for_layer(i);
  7331. ggml_context * ctx_split = ctx_for_layer_split(i);
  7332. auto & layer = model.layers[i];
  7333. // norm
  7334. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7335. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  7336. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  7337. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  7338. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  7339. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  7340. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  7341. // no "weight" suffix for these
  7342. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  7343. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  7344. // out_proj
  7345. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  7346. }
  7347. } break;
  7348. case LLM_ARCH_XVERSE:
  7349. {
  7350. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7351. {
  7352. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7353. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7354. }
  7355. for (int i = 0; i < n_layer; ++i) {
  7356. ggml_context * ctx_layer = ctx_for_layer(i);
  7357. ggml_context * ctx_split = ctx_for_layer_split(i);
  7358. auto & layer = model.layers[i];
  7359. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7360. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7361. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7362. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7363. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7364. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7365. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7366. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7367. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7368. }
  7369. } break;
  7370. case LLM_ARCH_COMMAND_R:
  7371. {
  7372. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7373. // output
  7374. {
  7375. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7376. // init output from the input tok embed
  7377. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7378. }
  7379. for (int i = 0; i < n_layer; ++i) {
  7380. ggml_context * ctx_layer = ctx_for_layer(i);
  7381. ggml_context * ctx_split = ctx_for_layer_split(i);
  7382. auto & layer = model.layers[i];
  7383. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7384. if (n_layer >= 64){
  7385. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7386. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7387. }
  7388. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7389. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7390. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7391. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7392. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7393. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7394. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7395. }
  7396. } break;
  7397. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7398. {
  7399. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7400. // output
  7401. {
  7402. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7403. // if output is NULL, init from the input tok embed
  7404. if (model.output == NULL) {
  7405. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7406. }
  7407. }
  7408. for (int i = 0; i < n_layer; ++i) {
  7409. ggml_context * ctx_split = ctx_for_layer_split(i);
  7410. auto & layer = model.layers[i];
  7411. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7412. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7413. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7414. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7415. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7416. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7417. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7418. }
  7419. } break;
  7420. case LLM_ARCH_OLMOE:
  7421. {
  7422. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7423. // output
  7424. {
  7425. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7426. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7427. }
  7428. for (int i = 0; i < n_layer; ++i) {
  7429. ggml_context * ctx_layer = ctx_for_layer(i);
  7430. ggml_context * ctx_split = ctx_for_layer_split(i);
  7431. auto & layer = model.layers[i];
  7432. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7433. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7434. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7435. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7436. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7437. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd});
  7438. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd});
  7439. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7440. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7441. GGML_ASSERT(n_expert > 0);
  7442. GGML_ASSERT(n_expert_used > 0);
  7443. // MoE branch
  7444. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7445. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  7446. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7447. }
  7448. } break;
  7449. case LLM_ARCH_OPENELM:
  7450. {
  7451. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7452. // output
  7453. {
  7454. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7455. // init output from the input tok embed
  7456. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7457. }
  7458. for (int i = 0; i < n_layer; ++i) {
  7459. const int64_t n_head = hparams.n_head(i);
  7460. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7461. const int64_t n_ff = hparams.n_ff(i);
  7462. ggml_context * ctx_layer = ctx_for_layer(i);
  7463. ggml_context * ctx_split = ctx_for_layer_split(i);
  7464. auto & layer = model.layers[i];
  7465. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7466. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  7467. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  7468. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  7469. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  7470. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7471. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7472. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7473. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7474. }
  7475. } break;
  7476. case LLM_ARCH_GPTNEOX:
  7477. {
  7478. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7479. // output
  7480. {
  7481. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7482. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7483. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7484. }
  7485. for (int i = 0; i < n_layer; ++i) {
  7486. ggml_context * ctx_layer = ctx_for_layer(i);
  7487. ggml_context * ctx_split = ctx_for_layer_split(i);
  7488. auto & layer = model.layers[i];
  7489. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7490. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7491. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7492. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7493. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7494. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7495. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7496. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7497. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7498. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7499. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7500. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7501. }
  7502. } break;
  7503. case LLM_ARCH_ARCTIC:
  7504. {
  7505. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7506. // output
  7507. {
  7508. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7509. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7510. // if output is NULL, init from the input tok embed
  7511. if (model.output == NULL) {
  7512. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7513. }
  7514. }
  7515. for (int i = 0; i < n_layer; ++i) {
  7516. ggml_context * ctx_layer = ctx_for_layer(i);
  7517. ggml_context * ctx_split = ctx_for_layer_split(i);
  7518. auto & layer = model.layers[i];
  7519. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7520. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7521. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7522. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7523. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7524. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7525. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  7526. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  7527. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  7528. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7529. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  7530. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  7531. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  7532. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7533. }
  7534. } break;
  7535. case LLM_ARCH_DEEPSEEK2:
  7536. {
  7537. const bool is_lite = (hparams.n_layer == 27);
  7538. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7539. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7540. const int64_t q_lora_rank = hparams.n_lora_q;
  7541. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7542. const int64_t n_ff_exp = hparams.n_ff_exp;
  7543. const int64_t n_expert_shared = hparams.n_expert_shared;
  7544. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7545. // output
  7546. {
  7547. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7548. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7549. }
  7550. for (int i = 0; i < n_layer; ++i) {
  7551. ggml_context * ctx_layer = ctx_for_layer(i);
  7552. ggml_context * ctx_split = ctx_for_layer_split(i);
  7553. auto & layer = model.layers[i];
  7554. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7555. if (!is_lite) {
  7556. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  7557. }
  7558. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  7559. if (!is_lite) {
  7560. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  7561. 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});
  7562. } else {
  7563. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7564. }
  7565. 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)});
  7566. 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)});
  7567. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  7568. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7569. if (i < (int) hparams.n_layer_dense_lead) {
  7570. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7571. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7572. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7573. } else {
  7574. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7575. GGML_ASSERT(n_expert > 0);
  7576. GGML_ASSERT(n_expert_used > 0);
  7577. // MoE branch
  7578. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7579. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  7580. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7581. // Shared expert branch
  7582. 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});
  7583. 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});
  7584. 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});
  7585. }
  7586. }
  7587. } break;
  7588. case LLM_ARCH_BITNET:
  7589. {
  7590. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7591. // output
  7592. {
  7593. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7594. }
  7595. for (int i = 0; i < n_layer; ++i) {
  7596. ggml_context * ctx_layer = ctx_for_layer(i);
  7597. ggml_context * ctx_split = ctx_for_layer_split(i);
  7598. auto & layer = model.layers[i];
  7599. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7600. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  7601. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7602. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7603. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7604. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7605. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7606. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7607. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7608. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7609. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7610. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  7611. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7612. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7613. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7614. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7615. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7616. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7617. }
  7618. } break;
  7619. case LLM_ARCH_T5:
  7620. {
  7621. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7622. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7623. // output
  7624. {
  7625. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7626. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  7627. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7628. // if output is NULL, init from the input tok embed
  7629. if (model.output == NULL) {
  7630. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7631. }
  7632. }
  7633. for (int i = 0; i < n_layer; ++i) {
  7634. ggml_context * ctx_layer = ctx_for_layer(i);
  7635. ggml_context * ctx_split = ctx_for_layer_split(i);
  7636. auto & layer = model.layers[i];
  7637. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7638. 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);
  7639. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7640. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7641. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7642. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7643. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7644. 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);
  7645. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7646. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7647. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  7648. 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);
  7649. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7650. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7651. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7652. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7653. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  7654. // this tensor seems to be unused in HF transformers implementation
  7655. 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);
  7656. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7657. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7658. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7659. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7660. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  7661. 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);
  7662. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7663. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  7664. }
  7665. } break;
  7666. case LLM_ARCH_T5ENCODER:
  7667. {
  7668. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7669. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7670. // output
  7671. {
  7672. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7673. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7674. // if output is NULL, init from the input tok embed
  7675. if (model.output == NULL) {
  7676. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7677. }
  7678. }
  7679. for (int i = 0; i < n_layer; ++i) {
  7680. ggml_context * ctx_layer = ctx_for_layer(i);
  7681. ggml_context * ctx_split = ctx_for_layer_split(i);
  7682. auto & layer = model.layers[i];
  7683. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7684. 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);
  7685. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7686. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7687. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7688. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7689. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7690. 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);
  7691. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7692. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7693. }
  7694. } break;
  7695. case LLM_ARCH_JAIS:
  7696. {
  7697. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7698. // Output
  7699. {
  7700. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7701. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7702. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7703. }
  7704. for (int i = 0; i < n_layer; ++i) {
  7705. ggml_context * ctx_layer = ctx_for_layer(i);
  7706. ggml_context * ctx_split = ctx_for_layer_split(i);
  7707. auto & layer = model.layers[i];
  7708. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7709. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7710. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7711. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7712. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7713. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7714. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7715. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7716. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7717. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7718. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7719. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  7720. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7721. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7722. }
  7723. } break;
  7724. case LLM_ARCH_CHATGLM:
  7725. {
  7726. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7727. // output
  7728. {
  7729. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7730. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7731. }
  7732. for (int i = 0; i < n_layer; ++i) {
  7733. ggml_context * ctx_layer = ctx_for_layer(i);
  7734. ggml_context * ctx_split = ctx_for_layer_split(i);
  7735. auto & layer = model.layers[i];
  7736. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7737. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7738. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7739. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7740. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7741. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  7742. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7743. }
  7744. } break;
  7745. case LLM_ARCH_NEMOTRON:
  7746. {
  7747. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7748. // output
  7749. {
  7750. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7751. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7752. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7753. }
  7754. for (int i = 0; i < n_layer; ++i) {
  7755. ggml_context * ctx_layer = ctx_for_layer(i);
  7756. ggml_context * ctx_split = ctx_for_layer_split(i);
  7757. auto & layer = model.layers[i];
  7758. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7759. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7760. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7761. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7762. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7763. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7764. // optional bias tensors
  7765. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7766. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7767. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7768. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7769. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7770. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7771. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7772. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7773. // optional MLP bias
  7774. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7775. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7776. }
  7777. } break;
  7778. case LLM_ARCH_EXAONE:
  7779. {
  7780. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7781. // output
  7782. {
  7783. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7784. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7785. }
  7786. for (int i = 0; i < n_layer; ++i) {
  7787. ggml_context * ctx_layer = ctx_for_layer(i);
  7788. ggml_context * ctx_split = ctx_for_layer_split(i);
  7789. auto & layer = model.layers[i];
  7790. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7791. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7792. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7793. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7794. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7795. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7796. 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));
  7797. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7798. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7799. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7800. }
  7801. } break;
  7802. case LLM_ARCH_RWKV6:
  7803. {
  7804. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7805. // Block 0, LN0
  7806. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  7807. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  7808. // output
  7809. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7810. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7811. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7812. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  7813. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  7814. const int head_size = hparams.wkv_head_size;
  7815. const int attn_hidden_size = n_embd;
  7816. const int ffn_size = hparams.n_ff_arr[0];
  7817. for (int i = 0; i < n_layer; ++i) {
  7818. ggml_context * ctx_layer = ctx_for_layer(i);
  7819. auto & layer = model.layers[i];
  7820. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7821. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7822. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  7823. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  7824. layer.time_mix_w1 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5});
  7825. layer.time_mix_w2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5});
  7826. layer.time_mix_lerp_x = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1});
  7827. layer.time_mix_lerp_w = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1});
  7828. layer.time_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7829. layer.time_mix_lerp_v = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1});
  7830. layer.time_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7831. layer.time_mix_lerp_g = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1});
  7832. layer.time_mix_first = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size});
  7833. layer.time_mix_decay = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd});
  7834. 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});
  7835. 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});
  7836. layer.time_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd});
  7837. layer.time_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd});
  7838. layer.time_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd});
  7839. layer.time_mix_gate = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd});
  7840. layer.time_mix_ln = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd});
  7841. layer.time_mix_ln_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd});
  7842. layer.time_mix_output = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size});
  7843. layer.channel_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7844. layer.channel_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7845. layer.channel_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size});
  7846. layer.channel_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd});
  7847. layer.channel_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd});
  7848. }
  7849. } break;
  7850. case LLM_ARCH_CHAMELEON:
  7851. {
  7852. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7853. // output
  7854. {
  7855. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7856. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7857. // if output is NULL, init from the input tok embed
  7858. if (model.output == NULL) {
  7859. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7860. }
  7861. }
  7862. for (int i = 0; i < n_layer; ++i) {
  7863. ggml_context * ctx_layer = ctx_for_layer(i);
  7864. ggml_context * ctx_split = ctx_for_layer_split(i);
  7865. auto & layer = model.layers[i];
  7866. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7867. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7868. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7869. 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);
  7870. 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);
  7871. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7872. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7873. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7874. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7875. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7876. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7877. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7878. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7879. }
  7880. } break;
  7881. case LLM_ARCH_SOLAR:
  7882. {
  7883. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7884. // output
  7885. {
  7886. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7887. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7888. }
  7889. for (int i = 0; i < n_layer; ++i) {
  7890. ggml_context * ctx_layer = ctx_for_layer(i);
  7891. ggml_context * ctx_split = ctx_for_layer_split(i);
  7892. auto & layer = model.layers[i];
  7893. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7894. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7895. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7896. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7897. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7898. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7899. 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));
  7900. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7901. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7902. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7903. }
  7904. } break;
  7905. default:
  7906. throw std::runtime_error("unknown architecture");
  7907. }
  7908. }
  7909. ml.done_getting_tensors();
  7910. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  7911. model.mappings.reserve(ml.mappings.size());
  7912. // create the backend buffers
  7913. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  7914. ctx_bufs.reserve(ctx_map.size());
  7915. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  7916. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  7917. model.bufs.reserve(n_max_backend_buffer);
  7918. for (auto & it : ctx_map) {
  7919. ggml_backend_buffer_type_t buft = it.first;
  7920. ggml_context * ctx = it.second;
  7921. llama_buf_map bufs;
  7922. bufs.reserve(n_max_backend_buffer);
  7923. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  7924. // 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
  7925. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  7926. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  7927. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7928. void * addr = nullptr;
  7929. size_t first, last;
  7930. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7931. if (first >= last) {
  7932. continue;
  7933. }
  7934. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  7935. if (buf == nullptr) {
  7936. throw std::runtime_error("unable to allocate backend CPU buffer");
  7937. }
  7938. model.bufs.push_back(buf);
  7939. bufs.emplace(idx, buf);
  7940. #ifdef GGML_USE_CUDA
  7941. if (n_layer >= n_gpu_layers) {
  7942. ggml_backend_cuda_register_host_buffer(
  7943. ggml_backend_buffer_get_base(buf),
  7944. ggml_backend_buffer_get_size(buf));
  7945. }
  7946. #endif
  7947. }
  7948. }
  7949. #ifdef GGML_USE_METAL
  7950. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  7951. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7952. const size_t max_size = ggml_get_max_tensor_size(ctx);
  7953. void * addr = nullptr;
  7954. size_t first, last;
  7955. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7956. if (first >= last) {
  7957. continue;
  7958. }
  7959. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  7960. if (buf == nullptr) {
  7961. throw std::runtime_error("unable to allocate backend metal buffer");
  7962. }
  7963. model.bufs.push_back(buf);
  7964. bufs.emplace(idx, buf);
  7965. }
  7966. }
  7967. #endif
  7968. else {
  7969. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  7970. if (buf == nullptr) {
  7971. throw std::runtime_error("unable to allocate backend buffer");
  7972. }
  7973. model.bufs.push_back(buf);
  7974. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  7975. model.mlock_bufs.emplace_back(new llama_mlock);
  7976. auto & mlock_buf = model.mlock_bufs.back();
  7977. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  7978. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  7979. }
  7980. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7981. bufs.emplace(idx, buf);
  7982. }
  7983. }
  7984. if (bufs.empty()) {
  7985. throw std::runtime_error("failed to allocate buffer");
  7986. }
  7987. for (auto & buf : bufs) {
  7988. // indicate that this buffer contains weights
  7989. // 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
  7990. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  7991. }
  7992. ctx_bufs.emplace_back(ctx, bufs);
  7993. }
  7994. if (llama_supports_gpu_offload()) {
  7995. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  7996. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  7997. if (n_gpu_layers > (int) hparams.n_layer) {
  7998. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  7999. }
  8000. const int max_backend_supported_layers = hparams.n_layer + 1;
  8001. const int max_offloadable_layers = hparams.n_layer + 1;
  8002. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  8003. }
  8004. // print memory requirements
  8005. for (ggml_backend_buffer_t buf : model.bufs) {
  8006. 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);
  8007. }
  8008. // populate tensors_by_name
  8009. for (ggml_context * ctx : model.ctxs) {
  8010. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  8011. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  8012. }
  8013. }
  8014. // load tensor data
  8015. for (auto & it : ctx_bufs) {
  8016. ggml_context * ctx = it.first;
  8017. auto & bufs = it.second;
  8018. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  8019. return false;
  8020. }
  8021. }
  8022. if (use_mmap_buffer) {
  8023. for (auto & mapping : ml.mappings) {
  8024. model.mappings.emplace_back(std::move(mapping));
  8025. }
  8026. }
  8027. return true;
  8028. }
  8029. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  8030. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  8031. model.t_start_us = ggml_time_us();
  8032. try {
  8033. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  8034. model.hparams.vocab_only = params.vocab_only;
  8035. try {
  8036. llm_load_arch(ml, model);
  8037. } catch(const std::exception & e) {
  8038. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  8039. }
  8040. try {
  8041. llm_load_hparams(ml, model);
  8042. } catch(const std::exception & e) {
  8043. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  8044. }
  8045. try {
  8046. llm_load_vocab(ml, model);
  8047. } catch(const std::exception & e) {
  8048. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  8049. }
  8050. llm_load_print_meta(ml, model);
  8051. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  8052. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  8053. LLAMA_LOG_WARN("%s: vocab mismatch %u !- %zu ...\n", __func__, model.hparams.n_vocab, model.vocab.id_to_token.size());
  8054. }
  8055. if (params.vocab_only) {
  8056. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  8057. return 0;
  8058. }
  8059. #ifdef GGML_USE_KOMPUTE
  8060. if (params.n_gpu_layers > 0 && (
  8061. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  8062. || !(
  8063. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  8064. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  8065. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  8066. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  8067. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  8068. )
  8069. )) {
  8070. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  8071. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  8072. params.n_gpu_layers = 0;
  8073. }
  8074. #endif
  8075. if (!llm_load_tensors(
  8076. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  8077. params.progress_callback, params.progress_callback_user_data
  8078. )) {
  8079. return -2;
  8080. }
  8081. } catch (const std::exception & err) {
  8082. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  8083. return -1;
  8084. }
  8085. // loading time will be recalculate after the first eval, so
  8086. // we take page faults deferred by mmap() into consideration
  8087. model.t_load_us = ggml_time_us() - model.t_start_us;
  8088. return 0;
  8089. }
  8090. //
  8091. // llm_build
  8092. //
  8093. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  8094. enum llm_ffn_op_type {
  8095. LLM_FFN_SILU,
  8096. LLM_FFN_GELU,
  8097. LLM_FFN_RELU,
  8098. LLM_FFN_RELU_SQR,
  8099. LLM_FFN_SWIGLU,
  8100. };
  8101. enum llm_ffn_gate_type {
  8102. LLM_FFN_SEQ,
  8103. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  8104. };
  8105. enum llm_norm_type {
  8106. LLM_NORM,
  8107. LLM_NORM_RMS,
  8108. };
  8109. static struct ggml_tensor * llm_build_inp_embd(
  8110. struct ggml_context * ctx,
  8111. struct llama_context & lctx,
  8112. const llama_hparams & hparams,
  8113. const llama_ubatch & batch,
  8114. struct ggml_tensor * tok_embd,
  8115. const llm_build_cb & cb) {
  8116. const int64_t n_embd = hparams.n_embd;
  8117. struct ggml_tensor * inpL;
  8118. if (batch.token) {
  8119. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  8120. cb(lctx.inp_tokens, "inp_tokens", -1);
  8121. ggml_set_input(lctx.inp_tokens);
  8122. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  8123. } else {
  8124. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  8125. inpL = lctx.inp_embd;
  8126. ggml_set_input(lctx.inp_embd);
  8127. }
  8128. // For Granite architecture
  8129. if (hparams.f_embedding_scale != 0.0f) {
  8130. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  8131. }
  8132. cb(inpL, "inp_embd", -1);
  8133. return inpL;
  8134. }
  8135. static struct ggml_tensor * llm_build_inp_cross_attn_state(
  8136. struct ggml_context * ctx,
  8137. struct llama_context & lctx,
  8138. const llama_hparams & hparams,
  8139. const llm_build_cb & cb) {
  8140. const int64_t n_embd = hparams.n_embd;
  8141. struct ggml_tensor * inpCAS = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_embd, 1601, 4);
  8142. cb(inpCAS, "inp_cross_attn_state", -1);
  8143. ggml_set_input(inpCAS);
  8144. lctx.inp_cross_attn_state = inpCAS;
  8145. return inpCAS;
  8146. }
  8147. static void llm_build_kv_store(
  8148. struct ggml_context * ctx,
  8149. const llama_hparams & hparams,
  8150. const llama_cparams & cparams,
  8151. const llama_kv_cache & kv,
  8152. struct ggml_cgraph * graph,
  8153. struct ggml_tensor * k_cur,
  8154. struct ggml_tensor * v_cur,
  8155. int32_t n_tokens,
  8156. int32_t kv_head,
  8157. const llm_build_cb & cb,
  8158. int64_t il) {
  8159. const int64_t n_ctx = cparams.n_ctx;
  8160. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8161. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8162. GGML_ASSERT(kv.size == n_ctx);
  8163. 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);
  8164. cb(k_cache_view, "k_cache_view", il);
  8165. // note: storing RoPE-ed version of K in the KV cache
  8166. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  8167. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  8168. struct ggml_tensor * v_cache_view = nullptr;
  8169. if (cparams.flash_attn) {
  8170. 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);
  8171. } else {
  8172. // note: the V cache is transposed when not using flash attention
  8173. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  8174. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  8175. (kv_head)*ggml_element_size(kv.v_l[il]));
  8176. v_cur = ggml_transpose(ctx, v_cur);
  8177. }
  8178. cb(v_cache_view, "v_cache_view", il);
  8179. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  8180. }
  8181. // do mat_mul, while optionally apply lora
  8182. static struct ggml_tensor * llm_build_lora_mm(
  8183. struct llama_context & lctx,
  8184. struct ggml_context * ctx0,
  8185. struct ggml_tensor * w,
  8186. struct ggml_tensor * cur) {
  8187. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  8188. for (auto & it : lctx.lora_adapters) {
  8189. struct llama_lora_weight * lora = it.first->get_weight(w);
  8190. if (lora == nullptr) {
  8191. continue;
  8192. }
  8193. const float alpha = it.first->alpha;
  8194. const float rank = (float) lora->b->ne[0];
  8195. const float scale = alpha ? it.second * alpha / rank : it.second;
  8196. struct ggml_tensor * ab_cur = ggml_mul_mat(
  8197. ctx0, lora->b,
  8198. ggml_mul_mat(ctx0, lora->a, cur)
  8199. );
  8200. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8201. res = ggml_add(ctx0, res, ab_cur);
  8202. }
  8203. return res;
  8204. }
  8205. // do mat_mul_id, while optionally apply lora
  8206. static struct ggml_tensor * llm_build_lora_mm_id(
  8207. struct llama_context & lctx,
  8208. struct ggml_context * ctx0,
  8209. struct ggml_tensor * w, // struct ggml_tensor * as
  8210. struct ggml_tensor * cur, // struct ggml_tensor * b
  8211. struct ggml_tensor * ids) {
  8212. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8213. for (auto & it : lctx.lora_adapters) {
  8214. struct llama_lora_weight * lora = it.first->get_weight(w);
  8215. if (lora == nullptr) {
  8216. continue;
  8217. }
  8218. const float alpha = it.first->alpha;
  8219. const float rank = (float) lora->b->ne[0];
  8220. const float scale = alpha ? it.second * alpha / rank : it.second;
  8221. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8222. ctx0, lora->b,
  8223. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8224. ids
  8225. );
  8226. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8227. res = ggml_add(ctx0, res, ab_cur);
  8228. }
  8229. return res;
  8230. }
  8231. static struct ggml_tensor * llm_build_norm(
  8232. struct ggml_context * ctx,
  8233. struct ggml_tensor * cur,
  8234. const llama_hparams & hparams,
  8235. struct ggml_tensor * mw,
  8236. struct ggml_tensor * mb,
  8237. llm_norm_type type,
  8238. const llm_build_cb & cb,
  8239. int il) {
  8240. switch (type) {
  8241. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8242. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8243. }
  8244. if (mw || mb) {
  8245. cb(cur, "norm", il);
  8246. }
  8247. if (mw) {
  8248. cur = ggml_mul(ctx, cur, mw);
  8249. if (mb) {
  8250. cb(cur, "norm_w", il);
  8251. }
  8252. }
  8253. if (mb) {
  8254. cur = ggml_add(ctx, cur, mb);
  8255. }
  8256. return cur;
  8257. }
  8258. static struct ggml_tensor * llm_build_ffn(
  8259. struct ggml_context * ctx,
  8260. struct llama_context & lctx,
  8261. struct ggml_tensor * cur,
  8262. struct ggml_tensor * up,
  8263. struct ggml_tensor * up_b,
  8264. struct ggml_tensor * up_s,
  8265. struct ggml_tensor * gate,
  8266. struct ggml_tensor * gate_b,
  8267. struct ggml_tensor * gate_s,
  8268. struct ggml_tensor * down,
  8269. struct ggml_tensor * down_b,
  8270. struct ggml_tensor * down_s,
  8271. struct ggml_tensor * act_scales,
  8272. llm_ffn_op_type type_op,
  8273. llm_ffn_gate_type type_gate,
  8274. const llm_build_cb & cb,
  8275. int il) {
  8276. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8277. cb(tmp, "ffn_up", il);
  8278. if (up_b) {
  8279. tmp = ggml_add(ctx, tmp, up_b);
  8280. cb(tmp, "ffn_up_b", il);
  8281. }
  8282. if (up_s) {
  8283. tmp = ggml_mul(ctx, tmp, up_s);
  8284. cb(tmp, "ffn_up_s", il);
  8285. }
  8286. if (gate) {
  8287. switch (type_gate) {
  8288. case LLM_FFN_SEQ:
  8289. {
  8290. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8291. cb(cur, "ffn_gate", il);
  8292. } break;
  8293. case LLM_FFN_PAR:
  8294. {
  8295. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8296. cb(cur, "ffn_gate", il);
  8297. } break;
  8298. }
  8299. if (gate_b) {
  8300. cur = ggml_add(ctx, cur, gate_b);
  8301. cb(cur, "ffn_gate_b", il);
  8302. }
  8303. if (gate_s) {
  8304. cur = ggml_mul(ctx, cur, gate_s);
  8305. cb(cur, "ffn_gate_s", il);
  8306. }
  8307. } else {
  8308. cur = tmp;
  8309. }
  8310. switch (type_op) {
  8311. case LLM_FFN_SILU:
  8312. {
  8313. cur = ggml_silu(ctx, cur);
  8314. cb(cur, "ffn_silu", il);
  8315. } break;
  8316. case LLM_FFN_GELU:
  8317. {
  8318. cur = ggml_gelu(ctx, cur);
  8319. cb(cur, "ffn_gelu", il);
  8320. if (act_scales != NULL) {
  8321. cur = ggml_div(ctx, cur, act_scales);
  8322. cb(cur, "ffn_act", il);
  8323. }
  8324. } break;
  8325. case LLM_FFN_RELU:
  8326. {
  8327. cur = ggml_relu(ctx, cur);
  8328. cb(cur, "ffn_relu", il);
  8329. } break;
  8330. case LLM_FFN_RELU_SQR:
  8331. {
  8332. cur = ggml_relu(ctx, cur);
  8333. cb(cur, "ffn_relu", il);
  8334. cur = ggml_sqr(ctx, cur);
  8335. cb(cur, "ffn_sqr(relu)", il);
  8336. } break;
  8337. case LLM_FFN_SWIGLU:
  8338. {
  8339. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8340. int64_t split_point = cur->ne[0] / 2;
  8341. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8342. 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)));
  8343. x0 = ggml_silu(ctx, x0);
  8344. cb(cur, "ffn_silu", il);
  8345. cur = ggml_mul(ctx, x0, x1);
  8346. cb(cur, "ffn_mul", il);
  8347. } break;
  8348. }
  8349. if (type_gate == LLM_FFN_PAR) {
  8350. cur = ggml_mul(ctx, cur, tmp);
  8351. cb(cur, "ffn_gate_par", il);
  8352. }
  8353. if (down) {
  8354. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8355. }
  8356. if (down_b) {
  8357. cb(cur, "ffn_down", il);
  8358. }
  8359. if (down_b) {
  8360. cur = ggml_add(ctx, cur, down_b);
  8361. }
  8362. if (down_s) {
  8363. cur = ggml_mul(ctx, cur, down_s);
  8364. cb(cur, "ffn_down_s", il);
  8365. }
  8366. return cur;
  8367. }
  8368. static struct ggml_tensor * llm_build_moe_ffn(
  8369. struct ggml_context * ctx,
  8370. struct llama_context & lctx,
  8371. struct ggml_tensor * cur,
  8372. struct ggml_tensor * gate_inp,
  8373. struct ggml_tensor * up_exps,
  8374. struct ggml_tensor * gate_exps,
  8375. struct ggml_tensor * down_exps,
  8376. int64_t n_expert,
  8377. int64_t n_expert_used,
  8378. llm_ffn_op_type type_op,
  8379. bool norm_w,
  8380. bool scale_w,
  8381. float w_scale,
  8382. const llm_build_cb & cb,
  8383. int il) {
  8384. int64_t n_embd = cur->ne[0];
  8385. int64_t n_tokens = cur->ne[1];
  8386. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8387. cb(logits, "ffn_moe_logits", il);
  8388. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8389. cb(probs, "ffn_moe_probs", il);
  8390. // select experts
  8391. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8392. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8393. cb(selected_experts, "ffn_moe_topk", il);
  8394. ggml_tensor * weights = ggml_get_rows(ctx,
  8395. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8396. cb(weights, "ffn_moe_weights", il);
  8397. if (norm_w) {
  8398. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8399. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8400. cb(weights_sum, "ffn_moe_weights_sum", il);
  8401. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8402. cb(weights, "ffn_moe_weights_norm", il);
  8403. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8404. }
  8405. if (scale_w) {
  8406. weights = ggml_scale(ctx, weights, w_scale);
  8407. cb(weights, "ffn_moe_weights_scaled", il);
  8408. }
  8409. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8410. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8411. cb(up, "ffn_moe_up", il);
  8412. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8413. cb(gate, "ffn_moe_gate", il);
  8414. switch (type_op) {
  8415. case LLM_FFN_SILU:
  8416. {
  8417. gate = ggml_silu(ctx, gate);
  8418. cb(gate, "ffn_moe_silu", il);
  8419. } break;
  8420. case LLM_FFN_GELU:
  8421. {
  8422. gate = ggml_gelu(ctx, gate);
  8423. cb(gate, "ffn_moe_gelu", il);
  8424. } break;
  8425. default:
  8426. GGML_ABORT("fatal error");
  8427. }
  8428. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8429. cb(par, "ffn_moe_gate_par", il);
  8430. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8431. cb(experts, "ffn_moe_down", il);
  8432. experts = ggml_mul(ctx, experts, weights);
  8433. // aggregate experts
  8434. ggml_tensor * moe_out = nullptr;
  8435. for (int i = 0; i < n_expert_used; ++i) {
  8436. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8437. experts->nb[2], i*experts->nb[1]);
  8438. if (i == 0) {
  8439. moe_out = cur_expert;
  8440. } else {
  8441. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8442. }
  8443. }
  8444. if (n_expert_used == 1) {
  8445. // avoid returning a non-contiguous tensor
  8446. moe_out = ggml_cont(ctx, moe_out);
  8447. }
  8448. return moe_out;
  8449. }
  8450. static struct ggml_tensor * llm_build_kqv(
  8451. struct ggml_context * ctx,
  8452. struct llama_context & lctx,
  8453. const llama_kv_cache & kv,
  8454. struct ggml_cgraph * graph,
  8455. struct ggml_tensor * wo,
  8456. struct ggml_tensor * wo_b,
  8457. struct ggml_tensor * q_cur,
  8458. struct ggml_tensor * kq_mask,
  8459. int32_t n_tokens,
  8460. int32_t n_kv,
  8461. float kq_scale,
  8462. const llm_build_cb & cb,
  8463. int il) {
  8464. const llama_model & model = lctx.model;
  8465. const llama_hparams & hparams = lctx.model.hparams;
  8466. const llama_cparams & cparams = lctx.cparams;
  8467. const int64_t n_ctx = cparams.n_ctx;
  8468. const int64_t n_head = hparams.n_head(il);
  8469. const int64_t n_head_kv = hparams.n_head_kv(il);
  8470. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8471. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8472. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8473. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8474. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8475. cb(q, "q", il);
  8476. struct ggml_tensor * k =
  8477. ggml_view_3d(ctx, kv.k_l[il],
  8478. n_embd_head_k, n_kv, n_head_kv,
  8479. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8480. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8481. 0);
  8482. cb(k, "k", il);
  8483. struct ggml_tensor * cur;
  8484. if (cparams.flash_attn) {
  8485. GGML_UNUSED(model);
  8486. GGML_UNUSED(n_ctx);
  8487. // split cached v into n_head heads (not transposed)
  8488. struct ggml_tensor * v =
  8489. ggml_view_3d(ctx, kv.v_l[il],
  8490. n_embd_head_v, n_kv, n_head_kv,
  8491. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8492. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8493. 0);
  8494. cb(v, "v", il);
  8495. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8496. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8497. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_GEMMA2) {
  8498. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8499. }
  8500. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8501. } else {
  8502. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8503. cb(kq, "kq", il);
  8504. 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) {
  8505. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  8506. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  8507. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8508. }
  8509. if (model.arch == LLM_ARCH_GROK) {
  8510. // need to do the following:
  8511. // multiply by attn_output_multiplyer of 0.08838834764831845
  8512. // and then :
  8513. // kq = 30 * tanh(kq / 30)
  8514. // before the softmax below
  8515. //try from phi2
  8516. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8517. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8518. kq = ggml_scale(ctx, kq, 30);
  8519. }
  8520. if (hparams.attn_soft_cap) {
  8521. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8522. kq = ggml_tanh(ctx, kq);
  8523. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8524. }
  8525. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8526. cb(kq, "kq_soft_max_ext", il);
  8527. GGML_ASSERT(kv.size == n_ctx);
  8528. // split cached v into n_head heads
  8529. struct ggml_tensor * v =
  8530. ggml_view_3d(ctx, kv.v_l[il],
  8531. n_kv, n_embd_head_v, n_head_kv,
  8532. ggml_element_size(kv.v_l[il])*n_ctx,
  8533. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8534. 0);
  8535. cb(v, "v", il);
  8536. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8537. cb(kqv, "kqv", il);
  8538. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8539. cb(kqv_merged, "kqv_merged", il);
  8540. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8541. cb(cur, "kqv_merged_cont", il);
  8542. }
  8543. ggml_build_forward_expand(graph, cur);
  8544. if (wo) {
  8545. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8546. }
  8547. if (wo_b) {
  8548. cb(cur, "kqv_wo", il);
  8549. }
  8550. if (wo_b) {
  8551. cur = ggml_add(ctx, cur, wo_b);
  8552. }
  8553. return cur;
  8554. }
  8555. static struct ggml_tensor * llm_build_kv(
  8556. struct ggml_context * ctx,
  8557. struct llama_context & lctx,
  8558. const llama_kv_cache & kv,
  8559. struct ggml_cgraph * graph,
  8560. struct ggml_tensor * wo,
  8561. struct ggml_tensor * wo_b,
  8562. struct ggml_tensor * k_cur,
  8563. struct ggml_tensor * v_cur,
  8564. struct ggml_tensor * q_cur,
  8565. struct ggml_tensor * kq_mask,
  8566. int32_t n_tokens,
  8567. int32_t kv_head,
  8568. int32_t n_kv,
  8569. float kq_scale,
  8570. const llm_build_cb & cb,
  8571. int il) {
  8572. const llama_hparams & hparams = lctx.model.hparams;
  8573. const llama_cparams & cparams = lctx.cparams;
  8574. // these nodes are added to the graph together so that they are not reordered
  8575. // by doing so, the number of splits in the graph is reduced
  8576. ggml_build_forward_expand(graph, q_cur);
  8577. ggml_build_forward_expand(graph, k_cur);
  8578. ggml_build_forward_expand(graph, v_cur);
  8579. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8580. struct ggml_tensor * cur;
  8581. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8582. cb(cur, "kqv_out", il);
  8583. return cur;
  8584. }
  8585. static struct ggml_tensor * llm_build_copy_mask_state(
  8586. struct ggml_context * ctx,
  8587. struct ggml_cgraph * graph,
  8588. struct ggml_tensor * s,
  8589. struct ggml_tensor * state_copy,
  8590. struct ggml_tensor * state_mask,
  8591. int32_t n_state,
  8592. int32_t kv_size,
  8593. int32_t kv_head,
  8594. int32_t n_kv,
  8595. int32_t n_seqs) {
  8596. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  8597. // copy states
  8598. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  8599. // this shrinks the tensors's ne[1] to n_kv
  8600. states = ggml_get_rows(ctx, states, state_copy);
  8601. // clear states of sequences which are starting at the beginning of this batch
  8602. // FIXME: zero-out NANs?
  8603. states = ggml_mul(ctx, states, state_mask);
  8604. // copy states which won't be changed further (between n_seqs and n_kv)
  8605. ggml_build_forward_expand(graph,
  8606. ggml_cpy(ctx,
  8607. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  8608. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  8609. // the part of the states that will be used and modified
  8610. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  8611. }
  8612. // TODO: split
  8613. static struct ggml_tensor * llm_build_mamba(
  8614. struct ggml_context * ctx,
  8615. struct llama_context & lctx,
  8616. const llama_ubatch & batch,
  8617. struct ggml_cgraph * graph,
  8618. struct ggml_tensor * cur,
  8619. struct ggml_tensor * state_copy,
  8620. struct ggml_tensor * state_mask,
  8621. int32_t kv_head,
  8622. int32_t n_kv,
  8623. const llm_build_cb & cb,
  8624. int il) {
  8625. const llama_model & model = lctx.model;
  8626. const llama_hparams & hparams = model.hparams;
  8627. const llama_kv_cache & kv = lctx.kv_self;
  8628. const int64_t d_conv = hparams.ssm_d_conv;
  8629. const int64_t d_inner = hparams.ssm_d_inner;
  8630. const int64_t d_state = hparams.ssm_d_state;
  8631. const int64_t dt_rank = hparams.ssm_dt_rank;
  8632. const int64_t n_seqs = batch.n_seqs;
  8633. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  8634. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  8635. // Use the same RMS norm as the final layer norm
  8636. const float norm_rms_eps = hparams.f_norm_rms_eps;
  8637. const int64_t n_seq_tokens = batch.n_seq_tokens;
  8638. GGML_ASSERT(n_seqs != 0);
  8639. GGML_ASSERT(batch.equal_seqs);
  8640. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  8641. struct ggml_tensor * conv_states_all = kv.k_l[il];
  8642. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  8643. // (ab)using the KV cache to store the states
  8644. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  8645. graph, conv_states_all, state_copy, state_mask,
  8646. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  8647. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  8648. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  8649. graph, ssm_states_all, state_copy, state_mask,
  8650. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  8651. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  8652. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  8653. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  8654. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  8655. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  8656. // split the above in two
  8657. // => {d_inner, n_seq_tokens, n_seqs}
  8658. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  8659. 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));
  8660. // conv
  8661. {
  8662. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  8663. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  8664. // copy last (d_conv - 1) columns back into the state cache
  8665. 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]));
  8666. ggml_build_forward_expand(graph,
  8667. ggml_cpy(ctx, last_conv,
  8668. ggml_view_1d(ctx, conv_states_all,
  8669. (d_conv - 1)*(d_inner)*(n_seqs),
  8670. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  8671. // 1D convolution
  8672. // The equivalent is to make a self-overlapping view of conv_x
  8673. // over d_conv columns at each stride in the 3rd dimension,
  8674. // then element-wise multiply that with the conv1d weight,
  8675. // then sum the elements of each row,
  8676. // (the last two steps are a dot product over rows (also doable with mul_mat))
  8677. // then permute away the ne[0] dimension,
  8678. // and then you're left with the resulting x tensor.
  8679. // For simultaneous sequences, all sequences need to have the same length.
  8680. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  8681. // bias
  8682. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  8683. x = ggml_silu(ctx, x);
  8684. }
  8685. // ssm
  8686. {
  8687. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  8688. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  8689. // split
  8690. 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);
  8691. 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);
  8692. 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));
  8693. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  8694. if (ssm_dt_b_c_rms) {
  8695. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  8696. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  8697. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  8698. }
  8699. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  8700. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  8701. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  8702. // Custom operator to optimize the parallel associative scan
  8703. // as described in the Annex D of the Mamba paper.
  8704. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  8705. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  8706. // store last states
  8707. ggml_build_forward_expand(graph,
  8708. ggml_cpy(ctx,
  8709. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  8710. 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))));
  8711. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  8712. // TODO: skip computing output earlier for unused tokens
  8713. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  8714. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  8715. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  8716. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  8717. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  8718. }
  8719. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  8720. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  8721. cb(cur, "mamba_out", il);
  8722. return cur;
  8723. }
  8724. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  8725. struct llama_context & lctx,
  8726. struct ggml_context * ctx,
  8727. const struct llama_layer * layer,
  8728. struct ggml_tensor * cur,
  8729. struct ggml_tensor * x_prev,
  8730. struct ggml_tensor ** wkv_state) {
  8731. size_t n_embd = cur->ne[0];
  8732. size_t n_seq_tokens = cur->ne[1];
  8733. size_t n_seqs = cur->ne[2];
  8734. size_t head_size = layer->time_mix_first->ne[0];
  8735. size_t head_count = layer->time_mix_first->ne[1];
  8736. size_t n_tokens = n_seqs * n_seq_tokens;
  8737. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8738. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  8739. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8740. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  8741. xxx = ggml_reshape_4d(
  8742. ctx,
  8743. ggml_tanh(
  8744. ctx,
  8745. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  8746. ),
  8747. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  8748. );
  8749. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  8750. xxx = ggml_mul_mat(
  8751. ctx,
  8752. ggml_reshape_4d(
  8753. ctx,
  8754. layer->time_mix_w2,
  8755. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  8756. ),
  8757. xxx
  8758. );
  8759. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  8760. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  8761. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  8762. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  8763. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  8764. struct ggml_tensor * xw = ggml_add(
  8765. ctx,
  8766. ggml_mul(
  8767. ctx,
  8768. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  8769. sx
  8770. ),
  8771. cur
  8772. );
  8773. struct ggml_tensor * xk = ggml_add(
  8774. ctx,
  8775. ggml_mul(
  8776. ctx,
  8777. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  8778. sx
  8779. ),
  8780. cur
  8781. );
  8782. struct ggml_tensor * xv = ggml_add(
  8783. ctx,
  8784. ggml_mul(
  8785. ctx,
  8786. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  8787. sx
  8788. ),
  8789. cur
  8790. );
  8791. struct ggml_tensor * xr = ggml_add(
  8792. ctx,
  8793. ggml_mul(
  8794. ctx,
  8795. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  8796. sx
  8797. ),
  8798. cur
  8799. );
  8800. struct ggml_tensor * xg = ggml_add(
  8801. ctx,
  8802. ggml_mul(
  8803. ctx,
  8804. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  8805. sx
  8806. ),
  8807. cur
  8808. );
  8809. 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);
  8810. 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);
  8811. 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);
  8812. struct ggml_tensor * g = ggml_silu(
  8813. ctx,
  8814. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  8815. );
  8816. struct ggml_tensor * w = ggml_mul_mat(
  8817. ctx,
  8818. layer->time_mix_decay_w2,
  8819. ggml_tanh(
  8820. ctx,
  8821. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  8822. )
  8823. );
  8824. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  8825. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  8826. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  8827. k = ggml_transpose(ctx, k);
  8828. v = ggml_transpose(ctx, v);
  8829. r = ggml_transpose(ctx, r);
  8830. struct ggml_tensor * wkv_output = ggml_rwkv_wkv(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  8831. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  8832. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  8833. // group norm with head_count groups
  8834. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  8835. cur = ggml_norm(ctx, cur, 64e-5f);
  8836. // Convert back to regular vectors.
  8837. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8838. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  8839. cur = ggml_mul(ctx, cur, g);
  8840. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  8841. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  8842. }
  8843. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  8844. struct llama_context & lctx,
  8845. struct ggml_context * ctx,
  8846. const struct llama_layer * layer,
  8847. struct ggml_tensor * cur,
  8848. struct ggml_tensor * x_prev) {
  8849. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8850. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  8851. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  8852. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  8853. struct ggml_tensor * k = ggml_sqr(
  8854. ctx,
  8855. ggml_relu(
  8856. ctx,
  8857. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  8858. )
  8859. );
  8860. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  8861. }
  8862. struct llm_build_context {
  8863. const llama_model & model;
  8864. llama_context & lctx;
  8865. const llama_hparams & hparams;
  8866. const llama_cparams & cparams;
  8867. const llama_ubatch & batch;
  8868. const llama_kv_cache & kv_self;
  8869. const int64_t n_embd;
  8870. const int64_t n_layer;
  8871. const int64_t n_rot;
  8872. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  8873. const int64_t n_head;
  8874. const int64_t n_head_kv;
  8875. const int64_t n_embd_head_k;
  8876. const int64_t n_embd_k_gqa;
  8877. const int64_t n_embd_head_v;
  8878. const int64_t n_embd_v_gqa;
  8879. const int64_t n_expert;
  8880. const int64_t n_expert_used;
  8881. const float freq_base;
  8882. const float freq_scale;
  8883. const float ext_factor;
  8884. const float attn_factor;
  8885. const float beta_fast;
  8886. const float beta_slow;
  8887. const float norm_eps;
  8888. const float norm_rms_eps;
  8889. const int32_t n_tokens;
  8890. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  8891. const int32_t n_outputs;
  8892. const int32_t n_outputs_enc;
  8893. const int32_t kv_head; // index of where we store new KV data in the cache
  8894. const int32_t n_ctx_orig;
  8895. const bool flash_attn;
  8896. const enum llama_pooling_type pooling_type;
  8897. const enum llama_rope_type rope_type;
  8898. const llm_build_cb & cb;
  8899. std::vector<uint8_t> & buf_compute_meta;
  8900. struct ggml_context * ctx0 = nullptr;
  8901. // TODO: consider making the entire interface noexcept
  8902. llm_build_context(
  8903. llama_context & lctx,
  8904. const llama_ubatch & batch,
  8905. const llm_build_cb & cb,
  8906. bool worst_case) :
  8907. model (lctx.model),
  8908. lctx (lctx),
  8909. hparams (model.hparams),
  8910. cparams (lctx.cparams),
  8911. batch (batch),
  8912. kv_self (lctx.kv_self),
  8913. n_embd (hparams.n_embd),
  8914. n_layer (hparams.n_layer),
  8915. n_rot (hparams.n_rot),
  8916. n_ctx (cparams.n_ctx),
  8917. n_head (hparams.n_head()),
  8918. n_head_kv (hparams.n_head_kv()),
  8919. n_embd_head_k (hparams.n_embd_head_k),
  8920. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  8921. n_embd_head_v (hparams.n_embd_head_v),
  8922. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  8923. n_expert (hparams.n_expert),
  8924. n_expert_used (hparams.n_expert_used),
  8925. freq_base (cparams.rope_freq_base),
  8926. freq_scale (cparams.rope_freq_scale),
  8927. ext_factor (cparams.yarn_ext_factor),
  8928. attn_factor (cparams.yarn_attn_factor),
  8929. beta_fast (cparams.yarn_beta_fast),
  8930. beta_slow (cparams.yarn_beta_slow),
  8931. norm_eps (hparams.f_norm_eps),
  8932. norm_rms_eps (hparams.f_norm_rms_eps),
  8933. n_tokens (batch.n_tokens),
  8934. n_kv (worst_case ? kv_self.size : kv_self.n),
  8935. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  8936. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  8937. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  8938. n_ctx_orig (cparams.n_ctx_orig_yarn),
  8939. flash_attn (cparams.flash_attn),
  8940. pooling_type (cparams.pooling_type),
  8941. rope_type (hparams.rope_type),
  8942. cb (cb),
  8943. buf_compute_meta (lctx.buf_compute_meta) {
  8944. // all initializations should be done in init()
  8945. }
  8946. void init() {
  8947. struct ggml_init_params params = {
  8948. /*.mem_size =*/ buf_compute_meta.size(),
  8949. /*.mem_buffer =*/ buf_compute_meta.data(),
  8950. /*.no_alloc =*/ true,
  8951. };
  8952. ctx0 = ggml_init(params);
  8953. lctx.inp_tokens = nullptr;
  8954. lctx.inp_embd = nullptr;
  8955. lctx.inp_pos = nullptr;
  8956. lctx.inp_out_ids = nullptr;
  8957. lctx.inp_KQ_mask = nullptr;
  8958. lctx.inp_KQ_mask_swa = nullptr;
  8959. lctx.inp_K_shift = nullptr;
  8960. lctx.inp_mean = nullptr;
  8961. lctx.inp_cls = nullptr;
  8962. lctx.inp_s_copy = nullptr;
  8963. lctx.inp_s_mask = nullptr;
  8964. lctx.inp_s_seq = nullptr;
  8965. lctx.inp_pos_bucket = nullptr;
  8966. lctx.inp_embd_enc = nullptr;
  8967. lctx.inp_KQ_mask_cross = nullptr;
  8968. lctx.inp_cross_attn_state = nullptr;
  8969. }
  8970. void free() {
  8971. if (ctx0) {
  8972. ggml_free(ctx0);
  8973. ctx0 = nullptr;
  8974. }
  8975. }
  8976. struct ggml_cgraph * build_k_shift() {
  8977. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8978. GGML_ASSERT(kv_self.size == n_ctx);
  8979. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  8980. cb(lctx.inp_K_shift, "K_shift", -1);
  8981. ggml_set_input(lctx.inp_K_shift);
  8982. for (int il = 0; il < n_layer; ++il) {
  8983. const int64_t n_head_kv = hparams.n_head_kv(il);
  8984. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8985. struct ggml_tensor * rope_factors = build_rope_factors(il);
  8986. struct ggml_tensor * k =
  8987. ggml_view_3d(ctx0, kv_self.k_l[il],
  8988. n_embd_head_k, n_head_kv, n_ctx,
  8989. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  8990. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8991. 0);
  8992. struct ggml_tensor * tmp;
  8993. if (ggml_is_quantized(k->type)) {
  8994. // dequantize to f32 -> RoPE -> quantize back
  8995. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  8996. cb(tmp, "K_f32", il);
  8997. for (auto * backend : lctx.backends) {
  8998. // Figure out which backend KV cache belongs to
  8999. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft)) {
  9000. ggml_backend_sched_set_tensor_backend(lctx.sched, tmp, backend);
  9001. break;
  9002. }
  9003. }
  9004. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  9005. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9006. ext_factor, attn_factor, beta_fast, beta_slow);
  9007. cb(tmp, "K_shifted_f32", il);
  9008. tmp = ggml_cpy(ctx0, tmp, k);
  9009. } else {
  9010. // we rotate only the first n_rot dimensions
  9011. tmp = ggml_rope_ext_inplace(ctx0, k,
  9012. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9013. ext_factor, attn_factor, beta_fast, beta_slow);
  9014. }
  9015. cb(tmp, "K_shifted", il);
  9016. ggml_build_forward_expand(gf, tmp);
  9017. }
  9018. return gf;
  9019. }
  9020. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  9021. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9022. for (uint32_t i = 0; i < ids.size(); ++i) {
  9023. const uint32_t id = ids[i];
  9024. if (i == id || id == ids.size()) {
  9025. continue;
  9026. }
  9027. uint32_t nm = 1;
  9028. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  9029. nm++;
  9030. }
  9031. for (int il = 0; il < n_layer; ++il) {
  9032. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  9033. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  9034. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  9035. n_embd_k_gqa, nm,
  9036. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9037. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  9038. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  9039. n_embd_k_gqa, nm,
  9040. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  9041. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  9042. ggml_tensor * view_v_src;
  9043. ggml_tensor * view_v_dst;
  9044. if (flash_attn) {
  9045. // NOTE: the V cache is not transposed when using flash attention
  9046. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9047. n_embd_v_gqa, nm,
  9048. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9049. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  9050. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9051. n_embd_v_gqa, nm,
  9052. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  9053. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  9054. } else {
  9055. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  9056. nm, n_embd_v_gqa,
  9057. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9058. ggml_row_size(kv_self.v_l[il]->type, i));
  9059. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  9060. nm, n_embd_v_gqa,
  9061. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  9062. ggml_row_size(kv_self.v_l[il]->type, id));
  9063. }
  9064. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  9065. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  9066. }
  9067. i += nm - 1;
  9068. }
  9069. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  9070. return gf;
  9071. }
  9072. struct ggml_tensor * build_inp_pos() {
  9073. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9074. cb(lctx.inp_pos, "inp_pos", -1);
  9075. ggml_set_input(lctx.inp_pos);
  9076. return lctx.inp_pos;
  9077. }
  9078. struct ggml_tensor * build_rope_factors(int il) {
  9079. // choose long/short freq factors based on the context size
  9080. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  9081. if (model.layers[il].rope_freqs != nullptr) {
  9082. return model.layers[il].rope_freqs;
  9083. }
  9084. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  9085. return model.layers[il].rope_long;
  9086. }
  9087. return model.layers[il].rope_short;
  9088. }
  9089. struct ggml_tensor * build_inp_out_ids() {
  9090. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  9091. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  9092. ggml_set_input(lctx.inp_out_ids);
  9093. return lctx.inp_out_ids;
  9094. }
  9095. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  9096. lctx.inp_KQ_mask = causal
  9097. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9098. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9099. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  9100. ggml_set_input(lctx.inp_KQ_mask);
  9101. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  9102. }
  9103. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  9104. GGML_ASSERT(hparams.n_swa > 0);
  9105. lctx.inp_KQ_mask_swa = causal
  9106. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  9107. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9108. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  9109. ggml_set_input(lctx.inp_KQ_mask_swa);
  9110. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  9111. }
  9112. struct ggml_tensor * build_inp_mean() {
  9113. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  9114. cb(lctx.inp_mean, "inp_mean", -1);
  9115. ggml_set_input(lctx.inp_mean);
  9116. return lctx.inp_mean;
  9117. }
  9118. struct ggml_tensor * build_inp_cls() {
  9119. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  9120. cb(lctx.inp_cls, "inp_cls", -1);
  9121. ggml_set_input(lctx.inp_cls);
  9122. return lctx.inp_cls;
  9123. }
  9124. struct ggml_tensor * build_inp_s_copy() {
  9125. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  9126. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  9127. ggml_set_input(lctx.inp_s_copy);
  9128. return lctx.inp_s_copy;
  9129. }
  9130. struct ggml_tensor * build_inp_s_mask() {
  9131. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  9132. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  9133. ggml_set_input(lctx.inp_s_mask);
  9134. return lctx.inp_s_mask;
  9135. }
  9136. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  9137. // find result_norm tensor for input
  9138. struct ggml_tensor * inp = nullptr;
  9139. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  9140. inp = ggml_graph_node(gf, i);
  9141. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  9142. break;
  9143. } else {
  9144. inp = nullptr;
  9145. }
  9146. }
  9147. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  9148. struct ggml_tensor * cur;
  9149. switch (pooling_type) {
  9150. case LLAMA_POOLING_TYPE_NONE:
  9151. {
  9152. cur = inp;
  9153. } break;
  9154. case LLAMA_POOLING_TYPE_MEAN:
  9155. {
  9156. struct ggml_tensor * inp_mean = build_inp_mean();
  9157. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  9158. } break;
  9159. case LLAMA_POOLING_TYPE_CLS:
  9160. case LLAMA_POOLING_TYPE_LAST:
  9161. {
  9162. struct ggml_tensor * inp_cls = build_inp_cls();
  9163. cur = ggml_get_rows(ctx0, inp, inp_cls);
  9164. } break;
  9165. case LLAMA_POOLING_TYPE_RANK:
  9166. {
  9167. struct ggml_tensor * inp_cls = build_inp_cls();
  9168. inp = ggml_get_rows(ctx0, inp, inp_cls);
  9169. // classification head
  9170. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  9171. GGML_ASSERT(model.cls != nullptr);
  9172. GGML_ASSERT(model.cls_b != nullptr);
  9173. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  9174. cur = ggml_tanh(ctx0, cur);
  9175. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  9176. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  9177. if (model.cls_out) {
  9178. GGML_ASSERT(model.cls_out_b != nullptr);
  9179. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  9180. }
  9181. } break;
  9182. default:
  9183. {
  9184. GGML_ABORT("unknown pooling type");
  9185. }
  9186. }
  9187. cb(cur, "result_embd_pooled", -1);
  9188. ggml_build_forward_expand(gf, cur);
  9189. return gf;
  9190. }
  9191. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  9192. if (causal) {
  9193. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  9194. } else {
  9195. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  9196. }
  9197. ggml_set_input(lctx.inp_pos_bucket);
  9198. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  9199. return lctx.inp_pos_bucket;
  9200. }
  9201. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  9202. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  9203. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  9204. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  9205. cb(pos_bias, "pos_bias", -1);
  9206. 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);
  9207. cb(pos_bias, "pos_bias", -1);
  9208. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  9209. cb(pos_bias, "pos_bias", -1);
  9210. pos_bias = ggml_cont(ctx0, pos_bias);
  9211. cb(pos_bias, "pos_bias", -1);
  9212. return pos_bias;
  9213. }
  9214. struct ggml_tensor * llm_build_inp_embd_enc() {
  9215. const int64_t n_embd = hparams.n_embd;
  9216. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9217. ggml_set_input(lctx.inp_embd_enc);
  9218. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9219. return lctx.inp_embd_enc;
  9220. }
  9221. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9222. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9223. ggml_set_input(lctx.inp_KQ_mask_cross);
  9224. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9225. return lctx.inp_KQ_mask_cross;
  9226. }
  9227. struct ggml_cgraph * build_llama() {
  9228. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9229. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9230. int32_t n_tokens = this->n_tokens;
  9231. const int64_t n_embd_head = hparams.n_embd_head_v;
  9232. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9233. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9234. struct ggml_tensor * cur;
  9235. struct ggml_tensor * inpL;
  9236. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9237. // inp_pos - contains the positions
  9238. struct ggml_tensor * inp_pos = build_inp_pos();
  9239. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9240. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9241. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9242. for (int il = 0; il < n_layer; ++il) {
  9243. struct ggml_tensor * inpSA = inpL;
  9244. // norm
  9245. cur = llm_build_norm(ctx0, inpL, hparams,
  9246. model.layers[il].attn_norm, NULL,
  9247. LLM_NORM_RMS, cb, il);
  9248. cb(cur, "attn_norm", il);
  9249. // self-attention
  9250. {
  9251. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9252. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9253. // compute Q and K and RoPE them
  9254. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9255. cb(Qcur, "Qcur", il);
  9256. if (model.layers[il].bq) {
  9257. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9258. cb(Qcur, "Qcur", il);
  9259. }
  9260. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9261. cb(Kcur, "Kcur", il);
  9262. if (model.layers[il].bk) {
  9263. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9264. cb(Kcur, "Kcur", il);
  9265. }
  9266. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9267. cb(Vcur, "Vcur", il);
  9268. if (model.layers[il].bv) {
  9269. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9270. cb(Vcur, "Vcur", il);
  9271. }
  9272. Qcur = ggml_rope_ext(
  9273. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9274. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9275. ext_factor, attn_factor, beta_fast, beta_slow
  9276. );
  9277. cb(Qcur, "Qcur", il);
  9278. Kcur = ggml_rope_ext(
  9279. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9280. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9281. ext_factor, attn_factor, beta_fast, beta_slow
  9282. );
  9283. cb(Kcur, "Kcur", il);
  9284. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9285. model.layers[il].wo, model.layers[il].bo,
  9286. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9287. }
  9288. if (il == n_layer - 1) {
  9289. // skip computing output for unused tokens
  9290. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9291. n_tokens = n_outputs;
  9292. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9293. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9294. }
  9295. // For Granite architecture
  9296. if (hparams.f_residual_scale) {
  9297. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9298. }
  9299. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9300. cb(ffn_inp, "ffn_inp", il);
  9301. // feed-forward network
  9302. if (model.layers[il].ffn_gate_inp == nullptr) {
  9303. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9304. model.layers[il].ffn_norm, NULL,
  9305. LLM_NORM_RMS, cb, il);
  9306. cb(cur, "ffn_norm", il);
  9307. cur = llm_build_ffn(ctx0, lctx, cur,
  9308. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9309. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9310. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9311. NULL,
  9312. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9313. cb(cur, "ffn_out", il);
  9314. } else {
  9315. // MoE branch
  9316. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9317. model.layers[il].ffn_norm, NULL,
  9318. LLM_NORM_RMS, cb, il);
  9319. cb(cur, "ffn_norm", il);
  9320. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9321. model.layers[il].ffn_gate_inp,
  9322. model.layers[il].ffn_up_exps,
  9323. model.layers[il].ffn_gate_exps,
  9324. model.layers[il].ffn_down_exps,
  9325. n_expert, n_expert_used,
  9326. LLM_FFN_SILU, true,
  9327. false, 0.0,
  9328. cb, il);
  9329. cb(cur, "ffn_moe_out", il);
  9330. }
  9331. // For Granite architecture
  9332. if (hparams.f_residual_scale) {
  9333. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9334. }
  9335. cur = ggml_add(ctx0, cur, ffn_inp);
  9336. cb(cur, "ffn_out", il);
  9337. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9338. cb(cur, "l_out", il);
  9339. // input for next layer
  9340. inpL = cur;
  9341. }
  9342. cur = inpL;
  9343. cur = llm_build_norm(ctx0, cur, hparams,
  9344. model.output_norm, NULL,
  9345. LLM_NORM_RMS, cb, -1);
  9346. cb(cur, "result_norm", -1);
  9347. // lm_head
  9348. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9349. // For Granite architecture
  9350. if (hparams.f_logit_scale) {
  9351. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9352. }
  9353. cb(cur, "result_output", -1);
  9354. ggml_build_forward_expand(gf, cur);
  9355. return gf;
  9356. }
  9357. struct ggml_cgraph * build_baichuan() {
  9358. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9359. const int64_t n_embd_head = hparams.n_embd_head_v;
  9360. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9361. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9362. struct ggml_tensor * cur;
  9363. struct ggml_tensor * inpL;
  9364. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9365. // inp_pos - contains the positions
  9366. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9367. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9368. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9369. for (int il = 0; il < n_layer; ++il) {
  9370. struct ggml_tensor * inpSA = inpL;
  9371. cur = llm_build_norm(ctx0, inpL, hparams,
  9372. model.layers[il].attn_norm, NULL,
  9373. LLM_NORM_RMS, cb, il);
  9374. cb(cur, "attn_norm", il);
  9375. // self-attention
  9376. {
  9377. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9378. cb(Qcur, "Qcur", il);
  9379. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9380. cb(Kcur, "Kcur", il);
  9381. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9382. cb(Vcur, "Vcur", il);
  9383. switch (model.type) {
  9384. case MODEL_7B:
  9385. Qcur = ggml_rope_ext(
  9386. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9387. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9388. ext_factor, attn_factor, beta_fast, beta_slow
  9389. );
  9390. Kcur = ggml_rope_ext(
  9391. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9392. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9393. ext_factor, attn_factor, beta_fast, beta_slow
  9394. );
  9395. break;
  9396. case MODEL_13B:
  9397. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9398. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9399. break;
  9400. default:
  9401. GGML_ABORT("fatal error");
  9402. }
  9403. cb(Qcur, "Qcur", il);
  9404. cb(Kcur, "Kcur", il);
  9405. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9406. model.layers[il].wo, NULL,
  9407. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9408. }
  9409. if (il == n_layer - 1) {
  9410. // skip computing output for unused tokens
  9411. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9412. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9413. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9414. }
  9415. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9416. cb(ffn_inp, "ffn_inp", il);
  9417. // feed-forward network
  9418. {
  9419. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9420. model.layers[il].ffn_norm, NULL,
  9421. LLM_NORM_RMS, cb, il);
  9422. cb(cur, "ffn_norm", il);
  9423. cur = llm_build_ffn(ctx0, lctx, cur,
  9424. model.layers[il].ffn_up, NULL, NULL,
  9425. model.layers[il].ffn_gate, NULL, NULL,
  9426. model.layers[il].ffn_down, NULL, NULL,
  9427. NULL,
  9428. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9429. cb(cur, "ffn_out", il);
  9430. }
  9431. cur = ggml_add(ctx0, cur, ffn_inp);
  9432. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9433. cb(cur, "l_out", il);
  9434. // input for next layer
  9435. inpL = cur;
  9436. }
  9437. cur = inpL;
  9438. cur = llm_build_norm(ctx0, cur, hparams,
  9439. model.output_norm, NULL,
  9440. LLM_NORM_RMS, cb, -1);
  9441. cb(cur, "result_norm", -1);
  9442. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9443. cb(cur, "result_output", -1);
  9444. ggml_build_forward_expand(gf, cur);
  9445. return gf;
  9446. }
  9447. struct ggml_cgraph * build_mllama() {
  9448. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9449. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9450. int32_t n_tokens = this->n_tokens;
  9451. const int64_t n_embd_head = hparams.n_embd_head_v;
  9452. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9453. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9454. struct ggml_tensor * cur;
  9455. struct ggml_tensor * inpL;
  9456. struct ggml_tensor * inpCAS;
  9457. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9458. inpCAS = llm_build_inp_cross_attn_state(ctx0, lctx, hparams, cb);
  9459. // inp_pos - contains the positions
  9460. struct ggml_tensor * inp_pos = build_inp_pos();
  9461. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9462. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9463. for (int il = 0; il < n_layer; ++il) {
  9464. struct ggml_tensor * inpSA = inpL;
  9465. // norm
  9466. cur = llm_build_norm(ctx0, inpL, hparams,
  9467. model.layers[il].attn_norm, NULL,
  9468. LLM_NORM_RMS, cb, il);
  9469. cb(cur, "attn_norm", il);
  9470. if (hparams.cross_attention_layers(il)) {
  9471. if (!batch.embd && !cparams.cross_attn) {
  9472. continue;
  9473. }
  9474. // cross attention layer
  9475. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_q_proj, cur);
  9476. cb(Qcur, "Qcur", il);
  9477. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9478. cb(Qcur, "Qcur", il);
  9479. Qcur = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 0, 2, 1, 3));
  9480. cb(Qcur, "Qcur", il);
  9481. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].cross_attn_q_norm, NULL, LLM_NORM_RMS, cb, il);
  9482. cb(Qcur, "Qcur", il);
  9483. struct ggml_tensor * Kcur, * Vcur;
  9484. if (batch.embd) {
  9485. Kcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_k_proj, inpCAS);
  9486. cb(Kcur, "Kcur", il);
  9487. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 6404);
  9488. cb(Kcur, "Kcur", il);
  9489. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9490. cb(Kcur, "Kcur", il);
  9491. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].cross_attn_k_norm, NULL, LLM_NORM_RMS, cb, il);
  9492. cb(Kcur, "Kcur", il);
  9493. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, kv_self.k_l[il]));
  9494. Vcur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_v_proj, inpCAS);
  9495. cb(Vcur, "Vcur", il);
  9496. Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, 6404);
  9497. cb(Vcur, "Vcur", il);
  9498. Vcur = ggml_permute(ctx0, Vcur, 0, 2, 1, 3);
  9499. cb(Vcur, "Vcur", il);
  9500. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, kv_self.v_l[il]));
  9501. } else {
  9502. Kcur = ggml_view_tensor(ctx0, kv_self.k_l[il]);
  9503. cb(Kcur, "Kcur (view)", il);
  9504. Vcur = ggml_view_tensor(ctx0, kv_self.v_l[il]);
  9505. cb(Vcur, "Vcur (view)", il);
  9506. }
  9507. struct ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur);
  9508. cb(kq, "kq", il);
  9509. // TODO: apply causal masks
  9510. struct ggml_tensor * kq_soft_max = ggml_soft_max_ext(ctx0, kq, nullptr, 1.f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  9511. cb(kq_soft_max, "kq_soft_max", il);
  9512. Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, Vcur));
  9513. cb(Vcur, "Vcur", il);
  9514. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, Vcur, kq_soft_max);
  9515. cb(kqv, "kqv", il);
  9516. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9517. cb(kqv_merged, "kqv_merged", il);
  9518. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_head_v*n_head, n_tokens);
  9519. cb(cur, "kqv_merged_cont", il);
  9520. cur = ggml_mul_mat(ctx0, model.layers[il].cross_attn_o_proj, cur);
  9521. cb(cur, "cur", il);
  9522. // TODO: do this in place once?
  9523. cur = ggml_mul(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_attn_gate));
  9524. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9525. cb(ffn_inp, "ffn_inp", il);
  9526. // feed-forward network
  9527. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9528. model.layers[il].ffn_norm, NULL,
  9529. LLM_NORM_RMS, cb, il);
  9530. cb(cur, "ffn_norm", il);
  9531. cur = llm_build_ffn(ctx0, lctx, cur,
  9532. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9533. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9534. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9535. NULL,
  9536. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9537. cb(cur, "ffn_out", il);
  9538. // TODO: do this inplace once?
  9539. cur = ggml_add_inplace(ctx0, ggml_mul_inplace(ctx0, cur, ggml_tanh(ctx0, model.layers[il].cross_attn_mlp_gate)), ffn_inp);
  9540. cb(cur, "ffn_out", il);
  9541. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9542. cb(cur, "l_out", il);
  9543. // input for next layer
  9544. inpL = cur;
  9545. } else {
  9546. // self attention layer
  9547. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9548. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9549. // compute Q and K and RoPE them
  9550. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9551. cb(Qcur, "Qcur", il);
  9552. if (model.layers[il].bq) {
  9553. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9554. cb(Qcur, "Qcur", il);
  9555. }
  9556. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9557. cb(Kcur, "Kcur", il);
  9558. if (model.layers[il].bk) {
  9559. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9560. cb(Kcur, "Kcur", il);
  9561. }
  9562. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9563. cb(Vcur, "Vcur", il);
  9564. if (model.layers[il].bv) {
  9565. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9566. cb(Vcur, "Vcur", il);
  9567. }
  9568. Qcur = ggml_rope_ext(
  9569. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9570. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9571. ext_factor, attn_factor, beta_fast, beta_slow
  9572. );
  9573. cb(Qcur, "Qcur", il);
  9574. Kcur = ggml_rope_ext(
  9575. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9576. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9577. ext_factor, attn_factor, beta_fast, beta_slow
  9578. );
  9579. cb(Kcur, "Kcur", il);
  9580. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9581. model.layers[il].wo, model.layers[il].bo,
  9582. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9583. if (il == n_layer - 1) {
  9584. // skip computing output for unused tokens
  9585. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9586. n_tokens = n_outputs;
  9587. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9588. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9589. }
  9590. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9591. cb(ffn_inp, "ffn_inp", il);
  9592. // feed-forward network
  9593. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9594. model.layers[il].ffn_norm, NULL,
  9595. LLM_NORM_RMS, cb, il);
  9596. cb(cur, "ffn_norm", il);
  9597. cur = llm_build_ffn(ctx0, lctx, cur,
  9598. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9599. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9600. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9601. NULL,
  9602. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9603. cb(cur, "ffn_out", il);
  9604. cur = ggml_add(ctx0, cur, ffn_inp);
  9605. cb(cur, "ffn_out", il);
  9606. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9607. cb(cur, "l_out", il);
  9608. // input for next layer
  9609. inpL = cur;
  9610. }
  9611. }
  9612. cur = inpL;
  9613. cur = llm_build_norm(ctx0, cur, hparams,
  9614. model.output_norm, NULL,
  9615. LLM_NORM_RMS, cb, -1);
  9616. cb(cur, "result_norm", -1);
  9617. // lm_head
  9618. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9619. cb(cur, "result_output", -1);
  9620. ggml_build_forward_expand(gf, cur);
  9621. return gf;
  9622. }
  9623. struct ggml_cgraph * build_xverse() {
  9624. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9625. const int64_t n_embd_head = hparams.n_embd_head_v;
  9626. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9627. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9628. struct ggml_tensor * cur;
  9629. struct ggml_tensor * inpL;
  9630. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9631. // inp_pos - contains the positions
  9632. struct ggml_tensor * inp_pos = build_inp_pos();
  9633. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9634. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9635. for (int il = 0; il < n_layer; ++il) {
  9636. struct ggml_tensor * inpSA = inpL;
  9637. cur = llm_build_norm(ctx0, inpL, hparams,
  9638. model.layers[il].attn_norm, NULL,
  9639. LLM_NORM_RMS, cb, il);
  9640. cb(cur, "attn_norm", il);
  9641. // self-attention
  9642. {
  9643. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9644. cb(Qcur, "Qcur", il);
  9645. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9646. cb(Kcur, "Kcur", il);
  9647. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9648. cb(Vcur, "Vcur", il);
  9649. Qcur = ggml_rope_ext(
  9650. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9651. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9652. ext_factor, attn_factor, beta_fast, beta_slow
  9653. );
  9654. cb(Qcur, "Qcur", il);
  9655. Kcur = ggml_rope_ext(
  9656. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9657. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9658. ext_factor, attn_factor, beta_fast, beta_slow
  9659. );
  9660. cb(Kcur, "Kcur", il);
  9661. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9662. model.layers[il].wo, NULL,
  9663. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9664. }
  9665. if (il == n_layer - 1) {
  9666. // skip computing output for unused tokens
  9667. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9668. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9669. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9670. }
  9671. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9672. cb(ffn_inp, "ffn_inp", il);
  9673. // feed-forward network
  9674. {
  9675. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9676. model.layers[il].ffn_norm, NULL,
  9677. LLM_NORM_RMS, cb, il);
  9678. cb(cur, "ffn_norm", il);
  9679. cur = llm_build_ffn(ctx0, lctx, cur,
  9680. model.layers[il].ffn_up, NULL, NULL,
  9681. model.layers[il].ffn_gate, NULL, NULL,
  9682. model.layers[il].ffn_down, NULL, NULL,
  9683. NULL,
  9684. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9685. cb(cur, "ffn_out", il);
  9686. }
  9687. cur = ggml_add(ctx0, cur, ffn_inp);
  9688. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9689. cb(cur, "l_out", il);
  9690. // input for next layer
  9691. inpL = cur;
  9692. }
  9693. cur = inpL;
  9694. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  9695. cb(cur, "result_norm", -1);
  9696. // lm_head
  9697. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9698. cb(cur, "result_output", -1);
  9699. ggml_build_forward_expand(gf, cur);
  9700. return gf;
  9701. }
  9702. struct ggml_cgraph * build_falcon() {
  9703. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9704. const int64_t n_embd_head = hparams.n_embd_head_v;
  9705. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9706. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9707. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9708. struct ggml_tensor * cur;
  9709. struct ggml_tensor * inpL;
  9710. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9711. // inp_pos - contains the positions
  9712. struct ggml_tensor * inp_pos = build_inp_pos();
  9713. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9714. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9715. for (int il = 0; il < n_layer; ++il) {
  9716. struct ggml_tensor * attn_norm;
  9717. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  9718. model.layers[il].attn_norm,
  9719. model.layers[il].attn_norm_b,
  9720. LLM_NORM, cb, il);
  9721. cb(attn_norm, "attn_norm", il);
  9722. // self-attention
  9723. {
  9724. if (model.layers[il].attn_norm_2) {
  9725. // Falcon-40B
  9726. cur = llm_build_norm(ctx0, inpL, hparams,
  9727. model.layers[il].attn_norm_2,
  9728. model.layers[il].attn_norm_2_b,
  9729. LLM_NORM, cb, il);
  9730. cb(cur, "attn_norm_2", il);
  9731. } else {
  9732. cur = attn_norm;
  9733. }
  9734. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9735. cb(cur, "wqkv", il);
  9736. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9737. 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)));
  9738. 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)));
  9739. cb(Qcur, "Qcur", il);
  9740. cb(Kcur, "Kcur", il);
  9741. cb(Vcur, "Vcur", il);
  9742. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9743. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9744. // using mode = 2 for neox mode
  9745. Qcur = ggml_rope_ext(
  9746. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9747. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9748. );
  9749. cb(Qcur, "Qcur", il);
  9750. Kcur = ggml_rope_ext(
  9751. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9752. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9753. );
  9754. cb(Kcur, "Kcur", il);
  9755. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9756. model.layers[il].wo, NULL,
  9757. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9758. }
  9759. if (il == n_layer - 1) {
  9760. // skip computing output for unused tokens
  9761. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9762. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9763. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9764. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  9765. }
  9766. struct ggml_tensor * ffn_inp = cur;
  9767. // feed forward
  9768. {
  9769. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  9770. model.layers[il].ffn_up, NULL, NULL,
  9771. NULL, NULL, NULL,
  9772. model.layers[il].ffn_down, NULL, NULL,
  9773. NULL,
  9774. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9775. cb(cur, "ffn_out", il);
  9776. }
  9777. cur = ggml_add(ctx0, cur, ffn_inp);
  9778. cur = ggml_add(ctx0, cur, inpL);
  9779. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9780. cb(cur, "l_out", il);
  9781. // input for next layer
  9782. inpL = cur;
  9783. }
  9784. cur = inpL;
  9785. // norm
  9786. cur = llm_build_norm(ctx0, cur, hparams,
  9787. model.output_norm,
  9788. model.output_norm_b,
  9789. LLM_NORM, cb, -1);
  9790. cb(cur, "result_norm", -1);
  9791. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9792. cb(cur, "result_output", -1);
  9793. ggml_build_forward_expand(gf, cur);
  9794. return gf;
  9795. }
  9796. struct ggml_cgraph * build_grok() {
  9797. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9798. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9799. int32_t n_tokens = this->n_tokens;
  9800. const int64_t n_embd_head = hparams.n_embd_head_v;
  9801. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9802. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9803. struct ggml_tensor * cur;
  9804. struct ggml_tensor * inpL;
  9805. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9806. // multiply by embedding_multiplier_scale of 78.38367176906169
  9807. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  9808. // inp_pos - contains the positions
  9809. struct ggml_tensor * inp_pos = build_inp_pos();
  9810. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9811. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9812. for (int il = 0; il < n_layer; ++il) {
  9813. struct ggml_tensor * inpSA = inpL;
  9814. // norm
  9815. cur = llm_build_norm(ctx0, inpL, hparams,
  9816. model.layers[il].attn_norm, NULL,
  9817. LLM_NORM_RMS, cb, il);
  9818. cb(cur, "attn_norm", il);
  9819. // self-attention
  9820. {
  9821. // compute Q and K and RoPE them
  9822. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9823. cb(Qcur, "Qcur", il);
  9824. if (model.layers[il].bq) {
  9825. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9826. cb(Qcur, "Qcur", il);
  9827. }
  9828. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9829. cb(Kcur, "Kcur", il);
  9830. if (model.layers[il].bk) {
  9831. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9832. cb(Kcur, "Kcur", il);
  9833. }
  9834. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9835. cb(Vcur, "Vcur", il);
  9836. if (model.layers[il].bv) {
  9837. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9838. cb(Vcur, "Vcur", il);
  9839. }
  9840. Qcur = ggml_rope_ext(
  9841. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9842. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9843. ext_factor, attn_factor, beta_fast, beta_slow
  9844. );
  9845. cb(Qcur, "Qcur", il);
  9846. Kcur = ggml_rope_ext(
  9847. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9848. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9849. ext_factor, attn_factor, beta_fast, beta_slow
  9850. );
  9851. cb(Kcur, "Kcur", il);
  9852. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9853. model.layers[il].wo, model.layers[il].bo,
  9854. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9855. }
  9856. if (il == n_layer - 1) {
  9857. // skip computing output for unused tokens
  9858. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9859. n_tokens = n_outputs;
  9860. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9861. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9862. }
  9863. // Grok
  9864. // if attn_out_norm is present then apply it before adding the input
  9865. if (model.layers[il].attn_out_norm) {
  9866. cur = llm_build_norm(ctx0, cur, hparams,
  9867. model.layers[il].attn_out_norm, NULL,
  9868. LLM_NORM_RMS, cb, il);
  9869. cb(cur, "attn_out_norm", il);
  9870. }
  9871. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9872. cb(ffn_inp, "ffn_inp", il);
  9873. // feed-forward network
  9874. // MoE branch
  9875. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9876. model.layers[il].ffn_norm, NULL,
  9877. LLM_NORM_RMS, cb, il);
  9878. cb(cur, "ffn_norm", il);
  9879. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9880. model.layers[il].ffn_gate_inp,
  9881. model.layers[il].ffn_up_exps,
  9882. model.layers[il].ffn_gate_exps,
  9883. model.layers[il].ffn_down_exps,
  9884. n_expert, n_expert_used,
  9885. LLM_FFN_GELU, true,
  9886. false, 0.0,
  9887. cb, il);
  9888. cb(cur, "ffn_moe_out", il);
  9889. // Grok
  9890. // if layer_out_norm is present then apply it before adding the input
  9891. // Idea: maybe ffn_out_norm is a better name
  9892. if (model.layers[il].layer_out_norm) {
  9893. cur = llm_build_norm(ctx0, cur, hparams,
  9894. model.layers[il].layer_out_norm, NULL,
  9895. LLM_NORM_RMS, cb, il);
  9896. cb(cur, "layer_out_norm", il);
  9897. }
  9898. cur = ggml_add(ctx0, cur, ffn_inp);
  9899. cb(cur, "ffn_out", il);
  9900. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9901. cb(cur, "l_out", il);
  9902. // input for next layer
  9903. inpL = cur;
  9904. }
  9905. cur = inpL;
  9906. cur = llm_build_norm(ctx0, cur, hparams,
  9907. model.output_norm, NULL,
  9908. LLM_NORM_RMS, cb, -1);
  9909. cb(cur, "result_norm", -1);
  9910. // lm_head
  9911. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9912. // Grok
  9913. // multiply logits by output_multiplier_scale of 0.5773502691896257
  9914. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  9915. cb(cur, "result_output", -1);
  9916. ggml_build_forward_expand(gf, cur);
  9917. return gf;
  9918. }
  9919. struct ggml_cgraph * build_dbrx() {
  9920. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9921. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9922. int32_t n_tokens = this->n_tokens;
  9923. const int64_t n_embd_head = hparams.n_embd_head_v;
  9924. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9925. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9926. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9927. struct ggml_tensor * cur;
  9928. struct ggml_tensor * inpL;
  9929. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9930. // inp_pos - contains the positions
  9931. struct ggml_tensor * inp_pos = build_inp_pos();
  9932. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9933. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9934. for (int il = 0; il < n_layer; ++il) {
  9935. struct ggml_tensor * inpSA = inpL;
  9936. // norm
  9937. cur = llm_build_norm(ctx0, inpL, hparams,
  9938. model.layers[il].attn_norm, NULL,
  9939. LLM_NORM, cb, il);
  9940. cb(cur, "attn_norm", il);
  9941. // self-attention
  9942. {
  9943. struct ggml_tensor * Qcur = nullptr;
  9944. struct ggml_tensor * Kcur = nullptr;
  9945. struct ggml_tensor * Vcur = nullptr;
  9946. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9947. cb(cur, "wqkv", il);
  9948. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  9949. cb(cur, "wqkv_clamped", il);
  9950. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9951. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9952. 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)));
  9953. cb(Qcur, "Qcur", il);
  9954. cb(Kcur, "Kcur", il);
  9955. cb(Vcur, "Vcur", il);
  9956. Qcur = ggml_rope_ext(
  9957. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9958. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9959. ext_factor, attn_factor, beta_fast, beta_slow
  9960. );
  9961. cb(Qcur, "Qcur", il);
  9962. Kcur = ggml_rope_ext(
  9963. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9964. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9965. ext_factor, attn_factor, beta_fast, beta_slow
  9966. );
  9967. cb(Kcur, "Kcur", il);
  9968. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9969. model.layers[il].wo, NULL,
  9970. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9971. }
  9972. if (il == n_layer - 1) {
  9973. // skip computing output for unused tokens
  9974. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9975. n_tokens = n_outputs;
  9976. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9977. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9978. }
  9979. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9980. cb(ffn_inp, "ffn_inp", il);
  9981. // feed-forward network
  9982. // MoE branch
  9983. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9984. model.layers[il].attn_out_norm, NULL,
  9985. LLM_NORM, cb, il);
  9986. cb(cur, "attn_out_norm", il);
  9987. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9988. model.layers[il].ffn_gate_inp,
  9989. model.layers[il].ffn_up_exps,
  9990. model.layers[il].ffn_gate_exps,
  9991. model.layers[il].ffn_down_exps,
  9992. n_expert, n_expert_used,
  9993. LLM_FFN_SILU, true,
  9994. false, 0.0,
  9995. cb, il);
  9996. cb(cur, "ffn_moe_out", il);
  9997. cur = ggml_add(ctx0, cur, ffn_inp);
  9998. cb(cur, "ffn_out", il);
  9999. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10000. cb(cur, "l_out", il);
  10001. // input for next layer
  10002. inpL = cur;
  10003. }
  10004. cur = inpL;
  10005. cur = llm_build_norm(ctx0, cur, hparams,
  10006. model.output_norm, NULL,
  10007. LLM_NORM, cb, -1);
  10008. cb(cur, "result_norm", -1);
  10009. // lm_head
  10010. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10011. cb(cur, "result_output", -1);
  10012. ggml_build_forward_expand(gf, cur);
  10013. return gf;
  10014. }
  10015. struct ggml_cgraph * build_starcoder() {
  10016. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10017. const int64_t n_embd_head = hparams.n_embd_head_v;
  10018. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10019. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10020. struct ggml_tensor * cur;
  10021. struct ggml_tensor * inpL;
  10022. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10023. // inp_pos - contains the positions
  10024. struct ggml_tensor * inp_pos = build_inp_pos();
  10025. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10026. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10027. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10028. cb(pos, "pos_embd", -1);
  10029. inpL = ggml_add(ctx0, inpL, pos);
  10030. cb(inpL, "inpL", -1);
  10031. for (int il = 0; il < n_layer; ++il) {
  10032. cur = llm_build_norm(ctx0, inpL, hparams,
  10033. model.layers[il].attn_norm,
  10034. model.layers[il].attn_norm_b,
  10035. LLM_NORM, cb, il);
  10036. cb(cur, "attn_norm", il);
  10037. // self-attention
  10038. {
  10039. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10040. cb(cur, "wqkv", il);
  10041. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10042. cb(cur, "bqkv", il);
  10043. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10044. 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)));
  10045. 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)));
  10046. cb(Qcur, "Qcur", il);
  10047. cb(Kcur, "Kcur", il);
  10048. cb(Vcur, "Vcur", il);
  10049. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10050. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10051. model.layers[il].wo, model.layers[il].bo,
  10052. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10053. }
  10054. if (il == n_layer - 1) {
  10055. // skip computing output for unused tokens
  10056. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10057. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10058. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10059. }
  10060. // add the input
  10061. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10062. cb(ffn_inp, "ffn_inp", il);
  10063. // FF
  10064. {
  10065. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10066. model.layers[il].ffn_norm,
  10067. model.layers[il].ffn_norm_b,
  10068. LLM_NORM, cb, il);
  10069. cb(cur, "ffn_norm", il);
  10070. cur = llm_build_ffn(ctx0, lctx, cur,
  10071. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10072. NULL, NULL, NULL,
  10073. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10074. NULL,
  10075. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10076. cb(cur, "ffn_out", il);
  10077. }
  10078. cur = ggml_add(ctx0, cur, ffn_inp);
  10079. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10080. cb(cur, "l_out", il);
  10081. // input for next layer
  10082. inpL = cur;
  10083. }
  10084. cur = llm_build_norm(ctx0, inpL, hparams,
  10085. model.output_norm,
  10086. model.output_norm_b,
  10087. LLM_NORM, cb, -1);
  10088. cb(cur, "result_norm", -1);
  10089. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10090. cb(cur, "result_output", -1);
  10091. ggml_build_forward_expand(gf, cur);
  10092. return gf;
  10093. }
  10094. struct ggml_cgraph * build_refact() {
  10095. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10096. const int64_t n_embd_head = hparams.n_embd_head_v;
  10097. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10098. struct ggml_tensor * cur;
  10099. struct ggml_tensor * inpL;
  10100. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10101. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10102. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10103. for (int il = 0; il < n_layer; ++il) {
  10104. struct ggml_tensor * inpSA = inpL;
  10105. cur = llm_build_norm(ctx0, inpL, hparams,
  10106. model.layers[il].attn_norm, NULL,
  10107. LLM_NORM_RMS, cb, il);
  10108. cb(cur, "attn_norm", il);
  10109. // self-attention
  10110. {
  10111. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10112. cb(Qcur, "Qcur", il);
  10113. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10114. cb(Kcur, "Kcur", il);
  10115. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10116. cb(Vcur, "Vcur", il);
  10117. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10118. cb(Kcur, "Kcur", il);
  10119. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10120. cb(Qcur, "Qcur", il);
  10121. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10122. model.layers[il].wo, NULL,
  10123. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10124. }
  10125. if (il == n_layer - 1) {
  10126. // skip computing output for unused tokens
  10127. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10128. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10129. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10130. }
  10131. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10132. cb(ffn_inp, "ffn_inp", il);
  10133. // feed-forward network
  10134. {
  10135. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10136. model.layers[il].ffn_norm, NULL,
  10137. LLM_NORM_RMS, cb, il);
  10138. cb(cur, "ffn_norm", il);
  10139. cur = llm_build_ffn(ctx0, lctx, cur,
  10140. model.layers[il].ffn_up, NULL, NULL,
  10141. model.layers[il].ffn_gate, NULL, NULL,
  10142. model.layers[il].ffn_down, NULL, NULL,
  10143. NULL,
  10144. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10145. cb(cur, "ffn_out", il);
  10146. }
  10147. cur = ggml_add(ctx0, cur, ffn_inp);
  10148. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10149. cb(cur, "l_out", il);
  10150. // input for next layer
  10151. inpL = cur;
  10152. }
  10153. cur = inpL;
  10154. cur = llm_build_norm(ctx0, cur, hparams,
  10155. model.output_norm, NULL,
  10156. LLM_NORM_RMS, cb, -1);
  10157. cb(cur, "result_norm", -1);
  10158. // lm_head
  10159. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10160. cb(cur, "result_output", -1);
  10161. ggml_build_forward_expand(gf, cur);
  10162. return gf;
  10163. }
  10164. struct ggml_cgraph * build_bert() {
  10165. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10166. const int64_t n_embd_head = hparams.n_embd_head_v;
  10167. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10168. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10169. struct ggml_tensor * cur;
  10170. struct ggml_tensor * inpL;
  10171. struct ggml_tensor * inp_pos = nullptr;
  10172. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  10173. inp_pos = build_inp_pos();
  10174. }
  10175. // construct input embeddings (token, type, position)
  10176. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10177. // token types are hardcoded to zero ("Sentence A")
  10178. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  10179. inpL = ggml_add(ctx0, inpL, type_row0);
  10180. if (model.arch == LLM_ARCH_BERT) {
  10181. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  10182. }
  10183. cb(inpL, "inp_embd", -1);
  10184. // embed layer norm
  10185. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  10186. cb(inpL, "inp_norm", -1);
  10187. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10188. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  10189. // iterate layers
  10190. for (int il = 0; il < n_layer; ++il) {
  10191. struct ggml_tensor * cur = inpL;
  10192. struct ggml_tensor * Qcur;
  10193. struct ggml_tensor * Kcur;
  10194. struct ggml_tensor * Vcur;
  10195. // self-attention
  10196. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  10197. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  10198. cb(Qcur, "Qcur", il);
  10199. if (model.layers[il].attn_q_norm) {
  10200. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10201. model.layers[il].attn_q_norm,
  10202. model.layers[il].attn_q_norm_b,
  10203. LLM_NORM, cb, il);
  10204. }
  10205. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  10206. cb(Kcur, "Kcur", il);
  10207. if (model.layers[il].attn_k_norm) {
  10208. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10209. model.layers[il].attn_k_norm,
  10210. model.layers[il].attn_k_norm_b,
  10211. LLM_NORM, cb, il);
  10212. }
  10213. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  10214. cb(Vcur, "Vcur", il);
  10215. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10216. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10217. } else {
  10218. // compute Q and K and RoPE them
  10219. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10220. cb(cur, "wqkv", il);
  10221. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10222. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10223. 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)));
  10224. cb(Qcur, "Qcur", il);
  10225. cb(Kcur, "Kcur", il);
  10226. cb(Vcur, "Vcur", il);
  10227. Qcur = ggml_rope_ext(
  10228. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10229. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10230. ext_factor, attn_factor, beta_fast, beta_slow
  10231. );
  10232. cb(Qcur, "Qcur", il);
  10233. Kcur = ggml_rope_ext(
  10234. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10235. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10236. ext_factor, attn_factor, beta_fast, beta_slow
  10237. );
  10238. cb(Kcur, "Kcur", il);
  10239. }
  10240. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10241. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10242. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10243. cb(kq, "kq", il);
  10244. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  10245. cb(kq, "kq_soft_max_ext", il);
  10246. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10247. cb(v, "v", il);
  10248. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10249. cb(kqv, "kqv", il);
  10250. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10251. cb(kqv_merged, "kqv_merged", il);
  10252. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10253. cb(cur, "kqv_merged_cont", il);
  10254. ggml_build_forward_expand(gf, cur);
  10255. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10256. if (model.layers[il].bo) {
  10257. cb(cur, "kqv_wo", il);
  10258. }
  10259. if (model.layers[il].bo) {
  10260. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10261. }
  10262. cb(cur, "kqv_out", il);
  10263. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  10264. // skip computing output for unused tokens
  10265. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10266. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10267. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10268. }
  10269. // re-add the layer input
  10270. cur = ggml_add(ctx0, cur, inpL);
  10271. // attention layer norm
  10272. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  10273. if (model.layers[il].attn_norm_2 != nullptr) {
  10274. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  10275. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  10276. }
  10277. struct ggml_tensor * ffn_inp = cur;
  10278. cb(ffn_inp, "ffn_inp", il);
  10279. // feed-forward network
  10280. if (model.arch == LLM_ARCH_BERT) {
  10281. cur = llm_build_ffn(ctx0, lctx, cur,
  10282. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10283. NULL, NULL, NULL,
  10284. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10285. NULL,
  10286. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10287. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  10288. cur = llm_build_ffn(ctx0, lctx, cur,
  10289. model.layers[il].ffn_up, NULL, NULL,
  10290. model.layers[il].ffn_gate, NULL, NULL,
  10291. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10292. NULL,
  10293. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10294. } else {
  10295. cur = llm_build_ffn(ctx0, lctx, cur,
  10296. model.layers[il].ffn_up, NULL, NULL,
  10297. model.layers[il].ffn_gate, NULL, NULL,
  10298. model.layers[il].ffn_down, NULL, NULL,
  10299. NULL,
  10300. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10301. }
  10302. cb(cur, "ffn_out", il);
  10303. // attentions bypass the intermediate layer
  10304. cur = ggml_add(ctx0, cur, ffn_inp);
  10305. // output layer norm
  10306. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  10307. // input for next layer
  10308. inpL = cur;
  10309. }
  10310. cur = inpL;
  10311. cb(cur, "result_embd", -1);
  10312. ggml_build_forward_expand(gf, cur);
  10313. return gf;
  10314. }
  10315. struct ggml_cgraph * build_bloom() {
  10316. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10317. const int64_t n_embd_head = hparams.n_embd_head_v;
  10318. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10319. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10320. struct ggml_tensor * cur;
  10321. struct ggml_tensor * inpL;
  10322. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10323. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10324. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10325. inpL = llm_build_norm(ctx0, inpL, hparams,
  10326. model.tok_norm,
  10327. model.tok_norm_b,
  10328. LLM_NORM, cb, -1);
  10329. cb(inpL, "inp_norm", -1);
  10330. for (int il = 0; il < n_layer; ++il) {
  10331. cur = llm_build_norm(ctx0, inpL, hparams,
  10332. model.layers[il].attn_norm,
  10333. model.layers[il].attn_norm_b,
  10334. LLM_NORM, cb, il);
  10335. cb(cur, "attn_norm", il);
  10336. // self-attention
  10337. {
  10338. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10339. cb(cur, "wqkv", il);
  10340. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10341. cb(cur, "bqkv", il);
  10342. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10343. 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)));
  10344. 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)));
  10345. cb(Qcur, "Qcur", il);
  10346. cb(Kcur, "Kcur", il);
  10347. cb(Vcur, "Vcur", il);
  10348. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10349. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10350. model.layers[il].wo, model.layers[il].bo,
  10351. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10352. }
  10353. if (il == n_layer - 1) {
  10354. // skip computing output for unused tokens
  10355. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10356. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10357. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10358. }
  10359. // Add the input
  10360. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10361. cb(ffn_inp, "ffn_inp", il);
  10362. // FF
  10363. {
  10364. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10365. model.layers[il].ffn_norm,
  10366. model.layers[il].ffn_norm_b,
  10367. LLM_NORM, cb, il);
  10368. cb(cur, "ffn_norm", il);
  10369. cur = llm_build_ffn(ctx0, lctx, cur,
  10370. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10371. NULL, NULL, NULL,
  10372. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10373. NULL,
  10374. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10375. cb(cur, "ffn_out", il);
  10376. }
  10377. cur = ggml_add(ctx0, cur, ffn_inp);
  10378. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10379. cb(cur, "l_out", il);
  10380. // input for next layer
  10381. inpL = cur;
  10382. }
  10383. cur = llm_build_norm(ctx0, inpL, hparams,
  10384. model.output_norm,
  10385. model.output_norm_b,
  10386. LLM_NORM, cb, -1);
  10387. cb(cur, "result_norm", -1);
  10388. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10389. cb(cur, "result_output", -1);
  10390. ggml_build_forward_expand(gf, cur);
  10391. return gf;
  10392. }
  10393. struct ggml_cgraph * build_mpt() {
  10394. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10395. const int64_t n_embd_head = hparams.n_embd_head_v;
  10396. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10397. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10398. struct ggml_tensor * cur;
  10399. struct ggml_tensor * pos;
  10400. struct ggml_tensor * inpL;
  10401. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10402. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10403. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10404. if (model.pos_embd) {
  10405. // inp_pos - contains the positions
  10406. struct ggml_tensor * inp_pos = build_inp_pos();
  10407. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10408. cb(pos, "pos_embd", -1);
  10409. inpL = ggml_add(ctx0, inpL, pos);
  10410. cb(inpL, "inpL", -1);
  10411. }
  10412. for (int il = 0; il < n_layer; ++il) {
  10413. struct ggml_tensor * attn_norm;
  10414. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10415. model.layers[il].attn_norm,
  10416. model.layers[il].attn_norm_b,
  10417. LLM_NORM, cb, il);
  10418. cb(attn_norm, "attn_norm", il);
  10419. // self-attention
  10420. {
  10421. cur = attn_norm;
  10422. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10423. cb(cur, "wqkv", il);
  10424. if (model.layers[il].bqkv){
  10425. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10426. cb(cur, "bqkv", il);
  10427. }
  10428. if (hparams.f_clamp_kqv > 0.0f) {
  10429. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10430. cb(cur, "wqkv_clamped", il);
  10431. }
  10432. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10433. 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)));
  10434. 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)));
  10435. cb(Qcur, "Qcur", il);
  10436. cb(Kcur, "Kcur", il);
  10437. cb(Vcur, "Vcur", il);
  10438. // Q/K Layernorm
  10439. if (model.layers[il].attn_q_norm) {
  10440. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10441. model.layers[il].attn_q_norm,
  10442. model.layers[il].attn_q_norm_b,
  10443. LLM_NORM, cb, il);
  10444. cb(Qcur, "Qcur", il);
  10445. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10446. model.layers[il].attn_k_norm,
  10447. model.layers[il].attn_k_norm_b,
  10448. LLM_NORM, cb, il);
  10449. cb(Kcur, "Kcur", il);
  10450. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10451. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10452. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10453. model.layers[il].wo, model.layers[il].bo,
  10454. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10455. } else {
  10456. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10457. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10458. model.layers[il].wo, model.layers[il].bo,
  10459. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10460. }
  10461. }
  10462. if (il == n_layer - 1) {
  10463. // skip computing output for unused tokens
  10464. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10465. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10466. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10467. }
  10468. // Add the input
  10469. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10470. cb(ffn_inp, "ffn_inp", il);
  10471. // feed forward
  10472. {
  10473. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10474. model.layers[il].ffn_norm,
  10475. model.layers[il].ffn_norm_b,
  10476. LLM_NORM, cb, il);
  10477. cb(cur, "ffn_norm", il);
  10478. cur = llm_build_ffn(ctx0, lctx, cur,
  10479. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10480. NULL, NULL, NULL,
  10481. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10482. model.layers[il].ffn_act,
  10483. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10484. cb(cur, "ffn_out", il);
  10485. }
  10486. cur = ggml_add(ctx0, cur, ffn_inp);
  10487. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10488. cb(cur, "l_out", il);
  10489. // input for next layer
  10490. inpL = cur;
  10491. }
  10492. cur = inpL;
  10493. cur = llm_build_norm(ctx0, cur, hparams,
  10494. model.output_norm,
  10495. model.output_norm_b,
  10496. LLM_NORM, cb, -1);
  10497. cb(cur, "result_norm", -1);
  10498. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10499. cb(cur, "result_output", -1);
  10500. ggml_build_forward_expand(gf, cur);
  10501. return gf;
  10502. }
  10503. struct ggml_cgraph * build_stablelm() {
  10504. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10505. const int64_t n_embd_head = hparams.n_embd_head_v;
  10506. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10507. struct ggml_tensor * cur;
  10508. struct ggml_tensor * inpL;
  10509. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10510. // inp_pos - contains the positions
  10511. struct ggml_tensor * inp_pos = build_inp_pos();
  10512. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10513. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10514. for (int il = 0; il < n_layer; ++il) {
  10515. // norm
  10516. cur = llm_build_norm(ctx0, inpL, hparams,
  10517. model.layers[il].attn_norm,
  10518. model.layers[il].attn_norm_b,
  10519. LLM_NORM, cb, il);
  10520. cb(cur, "attn_norm", il);
  10521. struct ggml_tensor * inpSA = cur;
  10522. // self-attention
  10523. {
  10524. // compute Q and K and RoPE them
  10525. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10526. cb(Qcur, "Qcur", il);
  10527. if (model.layers[il].bq) {
  10528. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10529. cb(Qcur, "Qcur", il);
  10530. }
  10531. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10532. cb(Kcur, "Kcur", il);
  10533. if (model.layers[il].bk) {
  10534. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10535. cb(Kcur, "Kcur", il);
  10536. }
  10537. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10538. cb(Vcur, "Vcur", il);
  10539. if (model.layers[il].bv) {
  10540. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10541. cb(Vcur, "Vcur", il);
  10542. }
  10543. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10544. cb(Qcur, "Qcur", il);
  10545. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10546. cb(Kcur, "Kcur", il);
  10547. if (model.layers[il].attn_q_norm) {
  10548. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10549. model.layers[il].attn_q_norm,
  10550. NULL,
  10551. LLM_NORM, cb, il);
  10552. cb(Qcur, "Qcur", il);
  10553. }
  10554. if (model.layers[il].attn_k_norm) {
  10555. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10556. model.layers[il].attn_k_norm,
  10557. NULL,
  10558. LLM_NORM, cb, il);
  10559. cb(Kcur, "Kcur", il);
  10560. }
  10561. Qcur = ggml_rope_ext(
  10562. ctx0, Qcur, inp_pos, nullptr,
  10563. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10564. ext_factor, attn_factor, beta_fast, beta_slow
  10565. );
  10566. cb(Qcur, "Qcur", il);
  10567. Kcur = ggml_rope_ext(
  10568. ctx0, Kcur, inp_pos, nullptr,
  10569. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10570. ext_factor, attn_factor, beta_fast, beta_slow
  10571. );
  10572. cb(Kcur, "Kcur", il);
  10573. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10574. model.layers[il].wo, NULL,
  10575. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10576. }
  10577. if (il == n_layer - 1) {
  10578. // skip computing output for unused tokens
  10579. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10580. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10581. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10582. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10583. }
  10584. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10585. cb(ffn_inp, "ffn_inp", il);
  10586. // feed-forward network
  10587. {
  10588. if (model.layers[il].ffn_norm) {
  10589. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10590. model.layers[il].ffn_norm,
  10591. model.layers[il].ffn_norm_b,
  10592. LLM_NORM, cb, il);
  10593. cb(cur, "ffn_norm", il);
  10594. } else {
  10595. // parallel residual
  10596. cur = inpSA;
  10597. }
  10598. cur = llm_build_ffn(ctx0, lctx, cur,
  10599. model.layers[il].ffn_up, NULL, NULL,
  10600. model.layers[il].ffn_gate, NULL, NULL,
  10601. model.layers[il].ffn_down, NULL, NULL,
  10602. NULL,
  10603. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10604. cb(cur, "ffn_out", il);
  10605. }
  10606. cur = ggml_add(ctx0, cur, ffn_inp);
  10607. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10608. cb(cur, "l_out", il);
  10609. // input for next layer
  10610. inpL = cur;
  10611. }
  10612. cur = inpL;
  10613. cur = llm_build_norm(ctx0, cur, hparams,
  10614. model.output_norm,
  10615. model.output_norm_b,
  10616. LLM_NORM, cb, -1);
  10617. cb(cur, "result_norm", -1);
  10618. // lm_head
  10619. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10620. cb(cur, "result_output", -1);
  10621. ggml_build_forward_expand(gf, cur);
  10622. return gf;
  10623. }
  10624. struct ggml_cgraph * build_qwen() {
  10625. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10626. const int64_t n_embd_head = hparams.n_embd_head_v;
  10627. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10628. struct ggml_tensor * cur;
  10629. struct ggml_tensor * inpL;
  10630. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10631. // inp_pos - contains the positions
  10632. struct ggml_tensor * inp_pos = build_inp_pos();
  10633. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10634. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10635. for (int il = 0; il < n_layer; ++il) {
  10636. struct ggml_tensor * inpSA = inpL;
  10637. cur = llm_build_norm(ctx0, inpL, hparams,
  10638. model.layers[il].attn_norm, NULL,
  10639. LLM_NORM_RMS, cb, il);
  10640. cb(cur, "attn_norm", il);
  10641. // self-attention
  10642. {
  10643. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10644. cb(cur, "wqkv", il);
  10645. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10646. cb(cur, "bqkv", il);
  10647. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10648. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10649. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  10650. cb(Qcur, "Qcur", il);
  10651. cb(Kcur, "Kcur", il);
  10652. cb(Vcur, "Vcur", il);
  10653. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10654. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10655. // using mode = 2 for neox mode
  10656. Qcur = ggml_rope_ext(
  10657. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10658. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10659. );
  10660. cb(Qcur, "Qcur", il);
  10661. Kcur = ggml_rope_ext(
  10662. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10663. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10664. );
  10665. cb(Kcur, "Kcur", il);
  10666. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10667. model.layers[il].wo, NULL,
  10668. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10669. }
  10670. if (il == n_layer - 1) {
  10671. // skip computing output for unused tokens
  10672. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10673. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10674. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10675. }
  10676. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10677. cb(ffn_inp, "ffn_inp", il);
  10678. // feed-forward forward
  10679. {
  10680. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10681. model.layers[il].ffn_norm, NULL,
  10682. LLM_NORM_RMS, cb, il);
  10683. cb(cur, "ffn_norm", il);
  10684. cur = llm_build_ffn(ctx0, lctx, cur,
  10685. model.layers[il].ffn_up, NULL, NULL,
  10686. model.layers[il].ffn_gate, NULL, NULL,
  10687. model.layers[il].ffn_down, NULL, NULL,
  10688. NULL,
  10689. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10690. cb(cur, "ffn_out", il);
  10691. }
  10692. cur = ggml_add(ctx0, cur, ffn_inp);
  10693. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10694. cb(cur, "l_out", il);
  10695. // input for next layer
  10696. inpL = cur;
  10697. }
  10698. cur = inpL;
  10699. cur = llm_build_norm(ctx0, cur, hparams,
  10700. model.output_norm, NULL,
  10701. LLM_NORM_RMS, cb, -1);
  10702. cb(cur, "result_norm", -1);
  10703. // lm_head
  10704. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10705. cb(cur, "result_output", -1);
  10706. ggml_build_forward_expand(gf, cur);
  10707. return gf;
  10708. }
  10709. struct ggml_cgraph * build_qwen2() {
  10710. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10711. const int64_t n_embd_head = hparams.n_embd_head_v;
  10712. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10713. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10714. struct ggml_tensor * cur;
  10715. struct ggml_tensor * inpL;
  10716. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10717. // inp_pos - contains the positions
  10718. struct ggml_tensor * inp_pos = build_inp_pos();
  10719. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10720. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10721. for (int il = 0; il < n_layer; ++il) {
  10722. struct ggml_tensor * inpSA = inpL;
  10723. // norm
  10724. cur = llm_build_norm(ctx0, inpL, hparams,
  10725. model.layers[il].attn_norm, NULL,
  10726. LLM_NORM_RMS, cb, il);
  10727. cb(cur, "attn_norm", il);
  10728. // self-attention
  10729. {
  10730. // compute Q and K and RoPE them
  10731. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10732. cb(Qcur, "Qcur", il);
  10733. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10734. cb(Qcur, "Qcur", il);
  10735. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10736. cb(Kcur, "Kcur", il);
  10737. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10738. cb(Kcur, "Kcur", il);
  10739. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10740. cb(Vcur, "Vcur", il);
  10741. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10742. cb(Vcur, "Vcur", il);
  10743. Qcur = ggml_rope_ext(
  10744. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10745. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10746. ext_factor, attn_factor, beta_fast, beta_slow
  10747. );
  10748. cb(Qcur, "Qcur", il);
  10749. Kcur = ggml_rope_ext(
  10750. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10751. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10752. ext_factor, attn_factor, beta_fast, beta_slow
  10753. );
  10754. cb(Kcur, "Kcur", il);
  10755. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10756. model.layers[il].wo, model.layers[il].bo,
  10757. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10758. }
  10759. if (il == n_layer - 1) {
  10760. // skip computing output for unused tokens
  10761. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10762. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10763. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10764. }
  10765. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10766. cb(ffn_inp, "ffn_inp", il);
  10767. // feed-forward network
  10768. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10769. model.layers[il].ffn_norm, NULL,
  10770. LLM_NORM_RMS, cb, il);
  10771. cb(cur, "ffn_norm", il);
  10772. cur = llm_build_ffn(ctx0, lctx, cur,
  10773. model.layers[il].ffn_up, NULL, NULL,
  10774. model.layers[il].ffn_gate, NULL, NULL,
  10775. model.layers[il].ffn_down, NULL, NULL,
  10776. NULL,
  10777. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10778. cb(cur, "ffn_out", il);
  10779. cur = ggml_add(ctx0, cur, ffn_inp);
  10780. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10781. cb(cur, "l_out", il);
  10782. // input for next layer
  10783. inpL = cur;
  10784. }
  10785. cur = inpL;
  10786. cur = llm_build_norm(ctx0, cur, hparams,
  10787. model.output_norm, NULL,
  10788. LLM_NORM_RMS, cb, -1);
  10789. cb(cur, "result_norm", -1);
  10790. // lm_head
  10791. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10792. cb(cur, "result_output", -1);
  10793. ggml_build_forward_expand(gf, cur);
  10794. return gf;
  10795. }
  10796. struct ggml_cgraph * build_qwen2moe() {
  10797. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10798. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10799. int32_t n_tokens = this->n_tokens;
  10800. const int64_t n_embd_head = hparams.n_embd_head_v;
  10801. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10802. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10803. struct ggml_tensor * cur;
  10804. struct ggml_tensor * inpL;
  10805. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10806. // inp_pos - contains the positions
  10807. struct ggml_tensor * inp_pos = build_inp_pos();
  10808. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10809. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10810. for (int il = 0; il < n_layer; ++il) {
  10811. struct ggml_tensor * inpSA = inpL;
  10812. // norm
  10813. cur = llm_build_norm(ctx0, inpL, hparams,
  10814. model.layers[il].attn_norm, NULL,
  10815. LLM_NORM_RMS, cb, il);
  10816. cb(cur, "attn_norm", il);
  10817. // self_attention
  10818. {
  10819. // compute Q and K and RoPE them
  10820. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10821. cb(Qcur, "Qcur", il);
  10822. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10823. cb(Qcur, "Qcur", il);
  10824. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10825. cb(Kcur, "Kcur", il);
  10826. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10827. cb(Kcur, "Kcur", il);
  10828. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10829. cb(Vcur, "Vcur", il);
  10830. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10831. cb(Vcur, "Vcur", il);
  10832. Qcur = ggml_rope_ext(
  10833. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10834. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10835. ext_factor, attn_factor, beta_fast, beta_slow
  10836. );
  10837. cb(Qcur, "Qcur", il);
  10838. Kcur = ggml_rope_ext(
  10839. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10840. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10841. ext_factor, attn_factor, beta_fast, beta_slow
  10842. );
  10843. cb(Kcur, "Kcur", il);
  10844. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10845. model.layers[il].wo, model.layers[il].bo,
  10846. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10847. }
  10848. if (il == n_layer - 1) {
  10849. // skip computing output for unused tokens
  10850. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10851. n_tokens = n_outputs;
  10852. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10853. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10854. }
  10855. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10856. cb(ffn_inp, "ffn_inp", il);
  10857. // MoE branch
  10858. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10859. model.layers[il].ffn_norm, NULL,
  10860. LLM_NORM_RMS, cb, il);
  10861. cb(cur, "ffn_norm", il);
  10862. ggml_tensor * moe_out =
  10863. llm_build_moe_ffn(ctx0, lctx, cur,
  10864. model.layers[il].ffn_gate_inp,
  10865. model.layers[il].ffn_up_exps,
  10866. model.layers[il].ffn_gate_exps,
  10867. model.layers[il].ffn_down_exps,
  10868. n_expert, n_expert_used,
  10869. LLM_FFN_SILU, false,
  10870. false, 0.0,
  10871. cb, il);
  10872. cb(cur, "ffn_moe_out", il);
  10873. // FFN shared expert
  10874. {
  10875. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  10876. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  10877. // sigmoid
  10878. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  10879. cb(cur_gate, "ffn_shexp_gate", il);
  10880. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  10881. model.layers[il].ffn_up_shexp, NULL, NULL,
  10882. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10883. model.layers[il].ffn_down_shexp, NULL, NULL,
  10884. NULL,
  10885. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10886. cb(cur_ffn, "ffn_shexp", il);
  10887. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  10888. cb(ffn_shexp_out, "ffn_shexp_out", il);
  10889. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  10890. cb(moe_out, "ffn_out", il);
  10891. cur = moe_out;
  10892. }
  10893. cur = ggml_add(ctx0, cur, ffn_inp);
  10894. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10895. cb(cur, "l_out", il);
  10896. // input for next layer
  10897. inpL = cur;
  10898. }
  10899. cur = inpL;
  10900. cur = llm_build_norm(ctx0, cur, hparams,
  10901. model.output_norm, NULL,
  10902. LLM_NORM_RMS, cb, -1);
  10903. cb(cur, "result_norm", -1);
  10904. // lm_head
  10905. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10906. cb(cur, "result_output", -1);
  10907. ggml_build_forward_expand(gf, cur);
  10908. return gf;
  10909. }
  10910. struct ggml_cgraph * build_phi2() {
  10911. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10912. const int64_t n_embd_head = hparams.n_embd_head_v;
  10913. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10914. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10915. struct ggml_tensor * cur;
  10916. struct ggml_tensor * attn_norm_output;
  10917. struct ggml_tensor * ffn_output;
  10918. struct ggml_tensor * inpL;
  10919. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10920. // inp_pos - contains the positions
  10921. struct ggml_tensor * inp_pos = build_inp_pos();
  10922. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10923. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10924. for (int il = 0; il < n_layer; ++il) {
  10925. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  10926. model.layers[il].attn_norm,
  10927. model.layers[il].attn_norm_b,
  10928. LLM_NORM, cb, il);
  10929. cb(attn_norm_output, "attn_norm", il);
  10930. // self-attention
  10931. {
  10932. struct ggml_tensor * Qcur = nullptr;
  10933. struct ggml_tensor * Kcur = nullptr;
  10934. struct ggml_tensor * Vcur = nullptr;
  10935. if (model.layers[il].wqkv) {
  10936. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  10937. cb(cur, "wqkv", il);
  10938. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10939. cb(cur, "bqkv", il);
  10940. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10941. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10942. 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)));
  10943. } else {
  10944. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  10945. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  10946. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  10947. }
  10948. cb(Qcur, "Qcur", il);
  10949. cb(Kcur, "Kcur", il);
  10950. cb(Vcur, "Vcur", il);
  10951. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10952. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10953. Qcur = ggml_rope_ext(
  10954. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10955. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10956. );
  10957. cb(Qcur, "Qcur", il);
  10958. // with phi2, we scale the Q to avoid precision issues
  10959. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  10960. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  10961. cb(Qcur, "Qcur", il);
  10962. Kcur = ggml_rope_ext(
  10963. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10964. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10965. );
  10966. cb(Kcur, "Kcur", il);
  10967. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10968. model.layers[il].wo, model.layers[il].bo,
  10969. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10970. }
  10971. if (il == n_layer - 1) {
  10972. // skip computing output for unused tokens
  10973. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10974. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10975. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10976. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  10977. }
  10978. // FF
  10979. {
  10980. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  10981. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10982. NULL, NULL, NULL,
  10983. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10984. NULL,
  10985. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10986. cb(ffn_output, "ffn_out", il);
  10987. }
  10988. cur = ggml_add(ctx0, cur, ffn_output);
  10989. cur = ggml_add(ctx0, cur, inpL);
  10990. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10991. cb(cur, "l_out", il);
  10992. // input for next layer
  10993. inpL = cur;
  10994. }
  10995. cur = llm_build_norm(ctx0, inpL, hparams,
  10996. model.output_norm,
  10997. model.output_norm_b,
  10998. LLM_NORM, cb, -1);
  10999. cb(cur, "result_norm", -1);
  11000. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11001. cb(cur, "result_output_no_bias", -1);
  11002. cur = ggml_add(ctx0, cur, model.output_b);
  11003. cb(cur, "result_output", -1);
  11004. ggml_build_forward_expand(gf, cur);
  11005. return gf;
  11006. }
  11007. struct ggml_cgraph * build_phi3() {
  11008. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11009. const int64_t n_embd_head = hparams.n_embd_head_v;
  11010. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11011. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11012. struct ggml_tensor * cur;
  11013. struct ggml_tensor * inpL;
  11014. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11015. // inp_pos - contains the positions
  11016. struct ggml_tensor * inp_pos = build_inp_pos();
  11017. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11018. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  11019. for (int il = 0; il < n_layer; ++il) {
  11020. auto residual = inpL;
  11021. // self-attention
  11022. {
  11023. // rope freq factors for 128k context
  11024. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11025. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  11026. model.layers[il].attn_norm,
  11027. NULL,
  11028. LLM_NORM_RMS, cb, il);
  11029. cb(attn_norm_output, "attn_norm", il);
  11030. struct ggml_tensor * Qcur = nullptr;
  11031. struct ggml_tensor * Kcur = nullptr;
  11032. struct ggml_tensor * Vcur = nullptr;
  11033. if (model.layers[il].wqkv) {
  11034. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  11035. cb(cur, "wqkv", il);
  11036. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  11037. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  11038. 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)));
  11039. }
  11040. else {
  11041. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  11042. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  11043. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  11044. }
  11045. cb(Qcur, "Qcur", il);
  11046. cb(Kcur, "Kcur", il);
  11047. cb(Vcur, "Vcur", il);
  11048. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11049. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11050. Qcur = ggml_rope_ext(
  11051. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11052. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11053. );
  11054. cb(Qcur, "Qcur", il);
  11055. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  11056. cb(Qcur, "Qcur", il);
  11057. Kcur = ggml_rope_ext(
  11058. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  11059. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11060. );
  11061. cb(Kcur, "Kcur", il);
  11062. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11063. model.layers[il].wo, model.layers[il].bo,
  11064. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11065. }
  11066. if (il == n_layer - 1) {
  11067. // skip computing output for unused tokens
  11068. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  11069. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11070. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11071. }
  11072. cur = ggml_add(ctx0, cur, residual);
  11073. residual = cur;
  11074. cur = llm_build_norm(ctx0, cur, hparams,
  11075. model.layers[il].ffn_norm, NULL,
  11076. LLM_NORM_RMS, cb, il);
  11077. cb(cur, "ffn_norm", il);
  11078. // FF
  11079. // special-case: the up and gate tensors are merged into a single tensor
  11080. // TOOD: support into llm_build_ffn
  11081. {
  11082. cur = llm_build_ffn(ctx0, lctx, cur,
  11083. model.layers[il].ffn_up, NULL, NULL,
  11084. NULL, NULL, NULL,
  11085. model.layers[il].ffn_down, NULL, NULL,
  11086. NULL,
  11087. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11088. cb(cur, "ffn_out", il);
  11089. }
  11090. cur = ggml_add(ctx0, residual, cur);
  11091. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11092. cb(cur, "l_out", il);
  11093. // input for next layer
  11094. inpL = cur;
  11095. }
  11096. cur = llm_build_norm(ctx0, inpL, hparams,
  11097. model.output_norm,
  11098. NULL,
  11099. LLM_NORM_RMS, cb, -1);
  11100. cb(cur, "result_norm", -1);
  11101. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11102. cb(cur, "result_output", -1);
  11103. ggml_build_forward_expand(gf, cur);
  11104. return gf;
  11105. }
  11106. struct ggml_cgraph * build_plamo() {
  11107. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  11108. const int64_t n_embd_head = hparams.n_embd_head_v;
  11109. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11110. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11111. struct ggml_tensor * cur;
  11112. struct ggml_tensor * inpL;
  11113. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11114. // inp_pos - contains the positions
  11115. struct ggml_tensor * inp_pos = build_inp_pos();
  11116. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11117. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11118. for (int il = 0; il < n_layer; ++il) {
  11119. // norm
  11120. cur = llm_build_norm(ctx0, inpL, hparams,
  11121. model.layers[il].attn_norm, NULL,
  11122. LLM_NORM_RMS, cb, il);
  11123. cb(cur, "attn_norm", il);
  11124. struct ggml_tensor * attention_norm = cur;
  11125. // self-attention
  11126. {
  11127. // compute Q and K and RoPE them
  11128. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11129. cb(Qcur, "Qcur", il);
  11130. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11131. cb(Kcur, "Kcur", il);
  11132. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11133. cb(Vcur, "Vcur", il);
  11134. Qcur = ggml_rope_ext(
  11135. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  11136. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11137. ext_factor, attn_factor, beta_fast, beta_slow);
  11138. cb(Qcur, "Qcur", il);
  11139. Kcur = ggml_rope_ext(
  11140. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  11141. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  11142. ext_factor, attn_factor, beta_fast, beta_slow);
  11143. cb(Kcur, "Kcur", il);
  11144. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11145. model.layers[il].wo, NULL,
  11146. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11147. }
  11148. struct ggml_tensor * sa_out = cur;
  11149. cur = attention_norm;
  11150. if (il == n_layer - 1) {
  11151. // skip computing output for unused tokens
  11152. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11153. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11154. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  11155. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11156. }
  11157. // feed-forward network
  11158. {
  11159. cur = llm_build_ffn(ctx0, lctx, cur,
  11160. model.layers[il].ffn_up, NULL, NULL,
  11161. model.layers[il].ffn_gate, NULL, NULL,
  11162. model.layers[il].ffn_down, NULL, NULL,
  11163. NULL,
  11164. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11165. cb(cur, "ffn_out", il);
  11166. }
  11167. cur = ggml_add(ctx0, cur, sa_out);
  11168. cur = ggml_add(ctx0, cur, inpL);
  11169. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11170. cb(cur, "l_out", il);
  11171. // input for next layer
  11172. inpL = cur;
  11173. }
  11174. cur = inpL;
  11175. cur = llm_build_norm(ctx0, cur, hparams,
  11176. model.output_norm, NULL,
  11177. LLM_NORM_RMS, cb, -1);
  11178. cb(cur, "result_norm", -1);
  11179. // lm_head
  11180. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11181. cb(cur, "result_output", -1);
  11182. ggml_build_forward_expand(gf, cur);
  11183. return gf;
  11184. }
  11185. struct ggml_cgraph * build_gpt2() {
  11186. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11187. const int64_t n_embd_head = hparams.n_embd_head_v;
  11188. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11189. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11190. struct ggml_tensor * cur;
  11191. struct ggml_tensor * pos;
  11192. struct ggml_tensor * inpL;
  11193. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11194. // inp_pos - contains the positions
  11195. struct ggml_tensor * inp_pos = build_inp_pos();
  11196. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11197. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11198. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  11199. cb(pos, "pos_embd", -1);
  11200. inpL = ggml_add(ctx0, inpL, pos);
  11201. cb(inpL, "inpL", -1);
  11202. for (int il = 0; il < n_layer; ++il) {
  11203. cur = llm_build_norm(ctx0, inpL, hparams,
  11204. model.layers[il].attn_norm,
  11205. model.layers[il].attn_norm_b,
  11206. LLM_NORM, cb, il);
  11207. cb(cur, "attn_norm", il);
  11208. // self-attention
  11209. {
  11210. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11211. cb(cur, "wqkv", il);
  11212. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11213. cb(cur, "bqkv", il);
  11214. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11215. 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)));
  11216. 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)));
  11217. cb(Qcur, "Qcur", il);
  11218. cb(Kcur, "Kcur", il);
  11219. cb(Vcur, "Vcur", il);
  11220. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11221. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11222. model.layers[il].wo, model.layers[il].bo,
  11223. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11224. }
  11225. if (il == n_layer - 1) {
  11226. // skip computing output for unused tokens
  11227. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11228. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11229. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11230. }
  11231. // add the input
  11232. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11233. cb(ffn_inp, "ffn_inp", il);
  11234. // FF
  11235. {
  11236. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11237. model.layers[il].ffn_norm,
  11238. model.layers[il].ffn_norm_b,
  11239. LLM_NORM, cb, il);
  11240. cb(cur, "ffn_norm", il);
  11241. cur = llm_build_ffn(ctx0, lctx, cur,
  11242. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11243. NULL, NULL, NULL,
  11244. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11245. NULL,
  11246. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11247. cb(cur, "ffn_out", il);
  11248. }
  11249. cur = ggml_add(ctx0, cur, ffn_inp);
  11250. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11251. cb(cur, "l_out", il);
  11252. // input for next layer
  11253. inpL = cur;
  11254. }
  11255. cur = llm_build_norm(ctx0, inpL, hparams,
  11256. model.output_norm,
  11257. model.output_norm_b,
  11258. LLM_NORM, cb, -1);
  11259. cb(cur, "result_norm", -1);
  11260. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11261. cb(cur, "result_output", -1);
  11262. ggml_build_forward_expand(gf, cur);
  11263. return gf;
  11264. }
  11265. struct ggml_cgraph * build_codeshell() {
  11266. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11267. const int64_t n_embd_head = hparams.n_embd_head_v;
  11268. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11269. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11270. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11271. struct ggml_tensor * cur;
  11272. struct ggml_tensor * inpL;
  11273. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11274. // inp_pos - contains the positions
  11275. struct ggml_tensor * inp_pos = build_inp_pos();
  11276. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11277. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11278. for (int il = 0; il < n_layer; ++il) {
  11279. cur = llm_build_norm(ctx0, inpL, hparams,
  11280. model.layers[il].attn_norm,
  11281. model.layers[il].attn_norm_b,
  11282. LLM_NORM, cb, il);
  11283. cb(cur, "attn_norm", il);
  11284. // self-attention
  11285. {
  11286. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11287. cb(cur, "wqkv", il);
  11288. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11289. cb(cur, "bqkv", il);
  11290. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11291. 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)));
  11292. 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)));
  11293. cb(tmpq, "tmpq", il);
  11294. cb(tmpk, "tmpk", il);
  11295. cb(Vcur, "Vcur", il);
  11296. struct ggml_tensor * Qcur = ggml_rope_ext(
  11297. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11298. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11299. ext_factor, attn_factor, beta_fast, beta_slow
  11300. );
  11301. cb(Qcur, "Qcur", il);
  11302. struct ggml_tensor * Kcur = ggml_rope_ext(
  11303. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11304. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11305. ext_factor, attn_factor, beta_fast, beta_slow
  11306. );
  11307. cb(Kcur, "Kcur", il);
  11308. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11309. model.layers[il].wo, model.layers[il].bo,
  11310. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11311. }
  11312. if (il == n_layer - 1) {
  11313. // skip computing output for unused tokens
  11314. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11315. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11316. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11317. }
  11318. // add the input
  11319. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11320. cb(ffn_inp, "ffn_inp", il);
  11321. // FF
  11322. {
  11323. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11324. model.layers[il].ffn_norm,
  11325. model.layers[il].ffn_norm_b,
  11326. LLM_NORM, cb, il);
  11327. cb(cur, "ffn_norm", il);
  11328. cur = llm_build_ffn(ctx0, lctx, cur,
  11329. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11330. NULL, NULL, NULL,
  11331. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11332. NULL,
  11333. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11334. cb(cur, "ffn_out", il);
  11335. }
  11336. cur = ggml_add(ctx0, cur, ffn_inp);
  11337. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11338. cb(cur, "l_out", il);
  11339. // input for next layer
  11340. inpL = cur;
  11341. }
  11342. cur = llm_build_norm(ctx0, inpL, hparams,
  11343. model.output_norm,
  11344. model.output_norm_b,
  11345. LLM_NORM, cb, -1);
  11346. cb(cur, "result_norm", -1);
  11347. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11348. cb(cur, "result_output", -1);
  11349. ggml_build_forward_expand(gf, cur);
  11350. return gf;
  11351. }
  11352. struct ggml_cgraph * build_orion() {
  11353. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11354. const int64_t n_embd_head = hparams.n_embd_head_v;
  11355. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11356. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11357. struct ggml_tensor * cur;
  11358. struct ggml_tensor * inpL;
  11359. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11360. // inp_pos - contains the positions
  11361. struct ggml_tensor * inp_pos = build_inp_pos();
  11362. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11363. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11364. for (int il = 0; il < n_layer; ++il) {
  11365. struct ggml_tensor * inpSA = inpL;
  11366. // norm
  11367. cur = llm_build_norm(ctx0, inpL, hparams,
  11368. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11369. LLM_NORM, cb, il);
  11370. cb(cur, "attn_norm", il);
  11371. // self-attention
  11372. {
  11373. // compute Q and K and RoPE them
  11374. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11375. cb(Qcur, "Qcur", il);
  11376. // if (model.layers[il].bq) {
  11377. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11378. // cb(Qcur, "Qcur", il);
  11379. // }
  11380. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11381. cb(Kcur, "Kcur", il);
  11382. // if (model.layers[il].bk) {
  11383. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11384. // cb(Kcur, "Kcur", il);
  11385. // }
  11386. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11387. cb(Vcur, "Vcur", il);
  11388. // if (model.layers[il].bv) {
  11389. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11390. // cb(Vcur, "Vcur", il);
  11391. // }
  11392. Qcur = ggml_rope_ext(
  11393. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11394. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11395. ext_factor, attn_factor, beta_fast, beta_slow
  11396. );
  11397. cb(Qcur, "Qcur", il);
  11398. Kcur = ggml_rope_ext(
  11399. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11400. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11401. ext_factor, attn_factor, beta_fast, beta_slow
  11402. );
  11403. cb(Kcur, "Kcur", il);
  11404. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11405. model.layers[il].wo, NULL,
  11406. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11407. }
  11408. if (il == n_layer - 1) {
  11409. // skip computing output for unused tokens
  11410. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11411. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11412. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11413. }
  11414. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11415. cb(ffn_inp, "ffn_inp", il);
  11416. // feed-forward network
  11417. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11418. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11419. LLM_NORM, cb, il);
  11420. cb(cur, "ffn_norm", il);
  11421. cur = llm_build_ffn(ctx0, lctx, cur,
  11422. model.layers[il].ffn_up, NULL, NULL,
  11423. model.layers[il].ffn_gate, NULL, NULL,
  11424. model.layers[il].ffn_down, NULL, NULL,
  11425. NULL,
  11426. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11427. cb(cur, "ffn_out", il);
  11428. cur = ggml_add(ctx0, cur, ffn_inp);
  11429. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11430. cb(cur, "l_out", il);
  11431. // input for next layer
  11432. inpL = cur;
  11433. }
  11434. cur = inpL;
  11435. cur = llm_build_norm(ctx0, cur, hparams,
  11436. model.output_norm, model.output_norm_b,
  11437. LLM_NORM, cb, -1);
  11438. cb(cur, "result_norm", -1);
  11439. // lm_head
  11440. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11441. cb(cur, "result_output", -1);
  11442. ggml_build_forward_expand(gf, cur);
  11443. return gf;
  11444. }
  11445. struct ggml_cgraph * build_internlm2() {
  11446. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11447. const int64_t n_embd_head = hparams.n_embd_head_v;
  11448. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11449. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11450. struct ggml_tensor * cur;
  11451. struct ggml_tensor * inpL;
  11452. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11453. // inp_pos - contains the positions
  11454. struct ggml_tensor * inp_pos = build_inp_pos();
  11455. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11456. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11457. for (int il = 0; il < n_layer; ++il) {
  11458. struct ggml_tensor * inpSA = inpL;
  11459. // norm
  11460. cur = llm_build_norm(ctx0, inpL, hparams,
  11461. model.layers[il].attn_norm, NULL,
  11462. LLM_NORM_RMS, cb, il);
  11463. cb(cur, "attn_norm", il);
  11464. // self-attention
  11465. {
  11466. // compute Q and K and RoPE them
  11467. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11468. cb(Qcur, "Qcur", il);
  11469. if (model.layers[il].bq) {
  11470. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11471. cb(Qcur, "Qcur", il);
  11472. }
  11473. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11474. cb(Kcur, "Kcur", il);
  11475. if (model.layers[il].bk) {
  11476. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11477. cb(Kcur, "Kcur", il);
  11478. }
  11479. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11480. cb(Vcur, "Vcur", il);
  11481. if (model.layers[il].bv) {
  11482. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11483. cb(Vcur, "Vcur", il);
  11484. }
  11485. Qcur = ggml_rope_ext(
  11486. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11487. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11488. ext_factor, attn_factor, beta_fast, beta_slow
  11489. );
  11490. cb(Qcur, "Qcur", il);
  11491. Kcur = ggml_rope_ext(
  11492. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11493. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11494. ext_factor, attn_factor, beta_fast, beta_slow
  11495. );
  11496. cb(Kcur, "Kcur", il);
  11497. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11498. model.layers[il].wo, model.layers[il].bo,
  11499. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11500. }
  11501. if (il == n_layer - 1) {
  11502. // skip computing output for unused tokens
  11503. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11504. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11505. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11506. }
  11507. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11508. cb(ffn_inp, "ffn_inp", il);
  11509. // feed-forward network
  11510. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11511. model.layers[il].ffn_norm, NULL,
  11512. LLM_NORM_RMS, cb, il);
  11513. cb(cur, "ffn_norm", il);
  11514. cur = llm_build_ffn(ctx0, lctx, cur,
  11515. model.layers[il].ffn_up, NULL, NULL,
  11516. model.layers[il].ffn_gate, NULL, NULL,
  11517. model.layers[il].ffn_down, NULL, NULL,
  11518. NULL,
  11519. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11520. cb(cur, "ffn_out", il);
  11521. cur = ggml_add(ctx0, cur, ffn_inp);
  11522. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11523. cb(cur, "l_out", il);
  11524. // input for next layer
  11525. inpL = cur;
  11526. }
  11527. cur = inpL;
  11528. cur = llm_build_norm(ctx0, cur, hparams,
  11529. model.output_norm, NULL,
  11530. LLM_NORM_RMS, cb, -1);
  11531. cb(cur, "result_norm", -1);
  11532. // lm_head
  11533. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11534. cb(cur, "result_output", -1);
  11535. ggml_build_forward_expand(gf, cur);
  11536. return gf;
  11537. }
  11538. // ref: https://arxiv.org/abs/2203.03466
  11539. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  11540. // based on the original build_llama() function
  11541. struct ggml_cgraph * build_minicpm() {
  11542. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11543. const int64_t n_embd_head = hparams.n_embd_head_v;
  11544. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11545. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11546. const int64_t n_embd = hparams.n_embd;
  11547. //TODO: if the model varies, these parameters need to be read from the model
  11548. const int64_t n_embd_base = 256;
  11549. const float scale_embd = 12.0f;
  11550. const float scale_depth = 1.4f;
  11551. struct ggml_tensor * cur;
  11552. struct ggml_tensor * inpL;
  11553. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11554. // scale the input embeddings
  11555. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11556. cb(inpL, "inp_scaled", -1);
  11557. // inp_pos - contains the positions
  11558. struct ggml_tensor * inp_pos = build_inp_pos();
  11559. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11560. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11561. for (int il = 0; il < n_layer; ++il) {
  11562. struct ggml_tensor * inpSA = inpL;
  11563. // norm
  11564. cur = llm_build_norm(ctx0, inpL, hparams,
  11565. model.layers[il].attn_norm, NULL,
  11566. LLM_NORM_RMS, cb, il);
  11567. cb(cur, "attn_norm", il);
  11568. // self-attention
  11569. {
  11570. // compute Q and K and RoPE them
  11571. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11572. cb(Qcur, "Qcur", il);
  11573. if (model.layers[il].bq) {
  11574. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11575. cb(Qcur, "Qcur", il);
  11576. }
  11577. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11578. cb(Kcur, "Kcur", il);
  11579. if (model.layers[il].bk) {
  11580. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11581. cb(Kcur, "Kcur", il);
  11582. }
  11583. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11584. cb(Vcur, "Vcur", il);
  11585. if (model.layers[il].bv) {
  11586. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11587. cb(Vcur, "Vcur", il);
  11588. }
  11589. Qcur = ggml_rope_ext(
  11590. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11591. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11592. ext_factor, attn_factor, beta_fast, beta_slow
  11593. );
  11594. cb(Qcur, "Qcur", il);
  11595. Kcur = ggml_rope_ext(
  11596. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11597. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11598. ext_factor, attn_factor, beta_fast, beta_slow
  11599. );
  11600. cb(Kcur, "Kcur", il);
  11601. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11602. model.layers[il].wo, model.layers[il].bo,
  11603. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11604. }
  11605. if (il == n_layer - 1) {
  11606. // skip computing output for unused tokens
  11607. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11608. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11609. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11610. }
  11611. // scale_res - scale the hidden states for residual connection
  11612. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11613. cur = ggml_scale(ctx0, cur, scale_res);
  11614. cb(cur, "hidden_scaled", -1);
  11615. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11616. cb(ffn_inp, "ffn_inp", il);
  11617. // feed-forward network
  11618. {
  11619. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11620. model.layers[il].ffn_norm, NULL,
  11621. LLM_NORM_RMS, cb, il);
  11622. cb(cur, "ffn_norm", il);
  11623. cur = llm_build_ffn(ctx0, lctx, cur,
  11624. model.layers[il].ffn_up, NULL, NULL,
  11625. model.layers[il].ffn_gate, NULL, NULL,
  11626. model.layers[il].ffn_down, NULL, NULL,
  11627. NULL,
  11628. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11629. cb(cur, "ffn_out", il);
  11630. }
  11631. // scale the hidden states for residual connection
  11632. cur = ggml_scale(ctx0, cur, scale_res);
  11633. cb(cur, "hidden_scaled_ffn", -1);
  11634. cur = ggml_add(ctx0, cur, ffn_inp);
  11635. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11636. cb(cur, "l_out", il);
  11637. // input for next layer
  11638. inpL = cur;
  11639. }
  11640. cur = inpL;
  11641. cur = llm_build_norm(ctx0, cur, hparams,
  11642. model.output_norm, NULL,
  11643. LLM_NORM_RMS, cb, -1);
  11644. cb(cur, "result_norm", -1);
  11645. // lm_head scaling
  11646. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11647. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11648. cb(cur, "lmhead_scaling", -1);
  11649. // lm_head
  11650. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11651. cb(cur, "result_output", -1);
  11652. ggml_build_forward_expand(gf, cur);
  11653. return gf;
  11654. }
  11655. struct ggml_cgraph * build_minicpm3() {
  11656. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11657. //TODO: if the model varies, these parameters need to be read from the model
  11658. const int64_t n_embd_base = 256;
  11659. const float scale_embd = 12.0f;
  11660. const float scale_depth = 1.4f;
  11661. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  11662. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  11663. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  11664. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  11665. struct ggml_tensor * cur;
  11666. struct ggml_tensor * inpL;
  11667. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11668. // scale the input embeddings
  11669. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11670. cb(inpL, "inp_scaled", -1);
  11671. // inp_pos - contains the positions
  11672. struct ggml_tensor * inp_pos = build_inp_pos();
  11673. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11674. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11675. for (int il = 0; il < n_layer; ++il) {
  11676. struct ggml_tensor * inpSA = inpL;
  11677. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11678. // norm
  11679. cur = llm_build_norm(ctx0, inpL, hparams,
  11680. model.layers[il].attn_norm, NULL,
  11681. LLM_NORM_RMS, cb, il);
  11682. cb(cur, "attn_norm", il);
  11683. // self_attention
  11684. {
  11685. struct ggml_tensor * q = NULL;
  11686. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  11687. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  11688. cb(q, "q", il);
  11689. q = llm_build_norm(ctx0, q, hparams,
  11690. model.layers[il].attn_q_a_norm, NULL,
  11691. LLM_NORM_RMS, cb, il);
  11692. cb(q, "q", il);
  11693. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  11694. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  11695. cb(q, "q", il);
  11696. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11697. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  11698. ggml_row_size(q->type, hparams.n_embd_head_k),
  11699. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11700. 0);
  11701. cb(q_nope, "q_nope", il);
  11702. // and {n_head * n_embd_head_qk_rope, n_tokens}
  11703. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  11704. ggml_row_size(q->type, hparams.n_embd_head_k),
  11705. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11706. ggml_row_size(q->type, n_embd_head_qk_nope));
  11707. cb(q_pe, "q_pe", il);
  11708. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  11709. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  11710. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  11711. // split into {kv_lora_rank, n_tokens}
  11712. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  11713. kv_pe_compresseed->nb[1],
  11714. 0);
  11715. cb(kv_compressed, "kv_compressed", il);
  11716. // and {n_embd_head_qk_rope, n_tokens}
  11717. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  11718. kv_pe_compresseed->nb[1],
  11719. kv_pe_compresseed->nb[1],
  11720. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  11721. cb(k_pe, "k_pe", il);
  11722. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  11723. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  11724. model.layers[il].attn_kv_a_norm, NULL,
  11725. LLM_NORM_RMS, cb, il);
  11726. cb(kv_compressed, "kv_compressed", il);
  11727. // {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}
  11728. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  11729. cb(kv, "kv", il);
  11730. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11731. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  11732. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  11733. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11734. 0);
  11735. cb(k_nope, "k_nope", il);
  11736. // and {n_head * n_embd_head_v, n_tokens}
  11737. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  11738. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11739. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  11740. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  11741. cb(v_states, "v_states", il);
  11742. v_states = ggml_cont(ctx0, v_states);
  11743. cb(v_states, "v_states", il);
  11744. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  11745. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  11746. 0);
  11747. cb(v_states, "v_states", il);
  11748. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11749. q_pe = ggml_rope_ext(
  11750. ctx0, q_pe, inp_pos, rope_factors,
  11751. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11752. ext_factor, attn_factor, beta_fast, beta_slow
  11753. );
  11754. cb(q_pe, "q_pe", il);
  11755. // shared RoPE key
  11756. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11757. k_pe = ggml_rope_ext(
  11758. ctx0, k_pe, inp_pos, rope_factors,
  11759. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11760. ext_factor, attn_factor, beta_fast, beta_slow
  11761. );
  11762. cb(k_pe, "k_pe", il);
  11763. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  11764. cb(q_states, "q_states", il);
  11765. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  11766. cb(k_states, "k_states", il);
  11767. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11768. model.layers[il].wo, NULL,
  11769. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  11770. }
  11771. if (il == n_layer - 1) {
  11772. // skip computing output for unused tokens
  11773. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11774. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11775. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11776. }
  11777. // scale_res - scale the hidden states for residual connection
  11778. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11779. cur = ggml_scale(ctx0, cur, scale_res);
  11780. cb(cur, "hidden_scaled", il);
  11781. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11782. cb(ffn_inp, "ffn_inp", il);
  11783. // feed-forward network
  11784. {
  11785. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11786. model.layers[il].ffn_norm, NULL,
  11787. LLM_NORM_RMS, cb, il);
  11788. cb(cur, "ffn_norm", il);
  11789. cur = llm_build_ffn(ctx0, lctx, cur,
  11790. model.layers[il].ffn_up, NULL, NULL,
  11791. model.layers[il].ffn_gate, NULL, NULL,
  11792. model.layers[il].ffn_down, NULL, NULL,
  11793. NULL,
  11794. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11795. cb(cur, "ffn_out", il);
  11796. }
  11797. // scale the hidden states for residual connection
  11798. cur = ggml_scale(ctx0, cur, scale_res);
  11799. cb(cur, "hidden_scaled_ffn", il);
  11800. cur = ggml_add(ctx0, cur, ffn_inp);
  11801. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11802. cb(cur, "l_out", il);
  11803. // input for next layer
  11804. inpL = cur;
  11805. }
  11806. cur = inpL;
  11807. cur = llm_build_norm(ctx0, cur, hparams,
  11808. model.output_norm, NULL,
  11809. LLM_NORM_RMS, cb, -1);
  11810. cb(cur, "result_norm", -1);
  11811. // lm_head scaling
  11812. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11813. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11814. cb(cur, "lmhead_scaling", -1);
  11815. // lm_head
  11816. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11817. cb(cur, "result_output", -1);
  11818. ggml_build_forward_expand(gf, cur);
  11819. return gf;
  11820. }
  11821. struct ggml_cgraph * build_gemma() {
  11822. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11823. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11824. struct ggml_tensor * cur;
  11825. struct ggml_tensor * inpL;
  11826. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11827. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11828. cb(inpL, "inp_scaled", -1);
  11829. // inp_pos - contains the positions
  11830. struct ggml_tensor * inp_pos = build_inp_pos();
  11831. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11832. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11833. for (int il = 0; il < n_layer; ++il) {
  11834. // norm
  11835. cur = llm_build_norm(ctx0, inpL, hparams,
  11836. model.layers[il].attn_norm, NULL,
  11837. LLM_NORM_RMS, cb, il);
  11838. cb(cur, "attn_norm", il);
  11839. // self-attention
  11840. {
  11841. // compute Q and K and RoPE them
  11842. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11843. cb(Qcur, "Qcur", il);
  11844. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11845. cb(Kcur, "Kcur", il);
  11846. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11847. cb(Vcur, "Vcur", il);
  11848. Qcur = ggml_rope_ext(
  11849. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11850. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11851. ext_factor, attn_factor, beta_fast, beta_slow);
  11852. cb(Qcur, "Qcur", il);
  11853. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  11854. cb(Qcur, "Qcur_scaled", il);
  11855. Kcur = ggml_rope_ext(
  11856. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11857. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11858. ext_factor, attn_factor, beta_fast, beta_slow);
  11859. cb(Kcur, "Kcur", il);
  11860. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11861. model.layers[il].wo, NULL,
  11862. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11863. }
  11864. if (il == n_layer - 1) {
  11865. // skip computing output for unused tokens
  11866. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11867. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11868. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11869. }
  11870. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11871. cb(sa_out, "sa_out", il);
  11872. cur = llm_build_norm(ctx0, sa_out, hparams,
  11873. model.layers[il].ffn_norm, NULL,
  11874. LLM_NORM_RMS, cb, il);
  11875. cb(cur, "ffn_norm", il);
  11876. // feed-forward network
  11877. {
  11878. cur = llm_build_ffn(ctx0, lctx, cur,
  11879. model.layers[il].ffn_up, NULL, NULL,
  11880. model.layers[il].ffn_gate, NULL, NULL,
  11881. model.layers[il].ffn_down, NULL, NULL,
  11882. NULL,
  11883. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11884. cb(cur, "ffn_out", il);
  11885. }
  11886. cur = ggml_add(ctx0, cur, sa_out);
  11887. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11888. cb(cur, "l_out", il);
  11889. // input for next layer
  11890. inpL = cur;
  11891. }
  11892. cur = inpL;
  11893. cur = llm_build_norm(ctx0, cur, hparams,
  11894. model.output_norm, NULL,
  11895. LLM_NORM_RMS, cb, -1);
  11896. cb(cur, "result_norm", -1);
  11897. // lm_head
  11898. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11899. cb(cur, "result_output", -1);
  11900. ggml_build_forward_expand(gf, cur);
  11901. return gf;
  11902. }
  11903. struct ggml_cgraph * build_gemma2() {
  11904. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11905. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11906. struct ggml_tensor * cur;
  11907. struct ggml_tensor * inpL;
  11908. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11909. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11910. cb(inpL, "inp_scaled", -1);
  11911. // inp_pos - contains the positions
  11912. struct ggml_tensor * inp_pos = build_inp_pos();
  11913. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11914. // gemma 2 requires different mask for layers using sliding window (SWA)
  11915. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  11916. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  11917. for (int il = 0; il < n_layer; ++il) {
  11918. // (il % 2) layers use SWA
  11919. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  11920. // norm
  11921. cur = llm_build_norm(ctx0, inpL, hparams,
  11922. model.layers[il].attn_norm, NULL,
  11923. LLM_NORM_RMS, cb, il);
  11924. cb(cur, "attn_norm", il);
  11925. // self-attention
  11926. {
  11927. // compute Q and K and RoPE them
  11928. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11929. cb(Qcur, "Qcur", il);
  11930. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11931. cb(Kcur, "Kcur", il);
  11932. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11933. cb(Vcur, "Vcur", il);
  11934. Qcur = ggml_rope_ext(
  11935. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11936. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11937. ext_factor, attn_factor, beta_fast, beta_slow);
  11938. cb(Qcur, "Qcur", il);
  11939. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  11940. switch (model.type) {
  11941. case e_model::MODEL_2B:
  11942. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  11943. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  11944. default: GGML_ABORT("fatal error");
  11945. };
  11946. cb(Qcur, "Qcur_scaled", il);
  11947. Kcur = ggml_rope_ext(
  11948. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11949. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11950. ext_factor, attn_factor, beta_fast, beta_slow);
  11951. cb(Kcur, "Kcur", il);
  11952. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11953. model.layers[il].wo, NULL,
  11954. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11955. }
  11956. cur = llm_build_norm(ctx0, cur, hparams,
  11957. model.layers[il].attn_post_norm, NULL,
  11958. LLM_NORM_RMS, cb, il);
  11959. cb(cur, "attn_post_norm", il);
  11960. if (il == n_layer - 1) {
  11961. // skip computing output for unused tokens
  11962. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11963. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11964. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11965. }
  11966. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11967. cb(sa_out, "sa_out", il);
  11968. cur = llm_build_norm(ctx0, sa_out, hparams,
  11969. model.layers[il].ffn_norm, NULL,
  11970. LLM_NORM_RMS, cb, il);
  11971. cb(cur, "ffn_norm", il);
  11972. // feed-forward network
  11973. {
  11974. cur = llm_build_ffn(ctx0, lctx, cur,
  11975. model.layers[il].ffn_up, NULL, NULL,
  11976. model.layers[il].ffn_gate, NULL, NULL,
  11977. model.layers[il].ffn_down, NULL, NULL,
  11978. NULL,
  11979. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11980. cb(cur, "ffn_out", il);
  11981. }
  11982. cur = llm_build_norm(ctx0, cur, hparams,
  11983. model.layers[il].ffn_post_norm, NULL,
  11984. LLM_NORM_RMS, cb, -1);
  11985. cb(cur, "ffn_post_norm", -1);
  11986. cur = ggml_add(ctx0, cur, sa_out);
  11987. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11988. cb(cur, "l_out", il);
  11989. // input for next layer
  11990. inpL = cur;
  11991. }
  11992. cur = inpL;
  11993. cur = llm_build_norm(ctx0, cur, hparams,
  11994. model.output_norm, NULL,
  11995. LLM_NORM_RMS, cb, -1);
  11996. cb(cur, "result_norm", -1);
  11997. // lm_head
  11998. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11999. // final logit soft-capping
  12000. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  12001. cur = ggml_tanh(ctx0, cur);
  12002. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  12003. cb(cur, "result_output", -1);
  12004. ggml_build_forward_expand(gf, cur);
  12005. return gf;
  12006. }
  12007. struct ggml_cgraph * build_starcoder2() {
  12008. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12009. const int64_t n_embd_head = hparams.n_embd_head_v;
  12010. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12011. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12012. struct ggml_tensor * cur;
  12013. struct ggml_tensor * inpL;
  12014. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12015. // inp_pos - contains the positions
  12016. struct ggml_tensor * inp_pos = build_inp_pos();
  12017. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12018. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12019. for (int il = 0; il < n_layer; ++il) {
  12020. struct ggml_tensor * inpSA = inpL;
  12021. // norm
  12022. cur = llm_build_norm(ctx0, inpL, hparams,
  12023. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  12024. LLM_NORM, cb, il);
  12025. cb(cur, "attn_norm", il);
  12026. // self-attention
  12027. {
  12028. // compute Q and K and RoPE them
  12029. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12030. cb(Qcur, "Qcur", il);
  12031. if (model.layers[il].bq) {
  12032. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12033. cb(Qcur, "Qcur", il);
  12034. }
  12035. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12036. cb(Kcur, "Kcur", il);
  12037. if (model.layers[il].bk) {
  12038. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12039. cb(Kcur, "Kcur", il);
  12040. }
  12041. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12042. cb(Vcur, "Vcur", il);
  12043. if (model.layers[il].bv) {
  12044. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12045. cb(Vcur, "Vcur", il);
  12046. }
  12047. Qcur = ggml_rope_ext(
  12048. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12049. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12050. ext_factor, attn_factor, beta_fast, beta_slow
  12051. );
  12052. cb(Qcur, "Qcur", il);
  12053. Kcur = ggml_rope_ext(
  12054. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12055. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12056. ext_factor, attn_factor, beta_fast, beta_slow
  12057. );
  12058. cb(Kcur, "Kcur", il);
  12059. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12060. model.layers[il].wo, model.layers[il].bo,
  12061. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12062. }
  12063. if (il == n_layer - 1) {
  12064. // skip computing output for unused tokens
  12065. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12066. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12067. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12068. }
  12069. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12070. cb(ffn_inp, "ffn_inp", il);
  12071. // feed-forward network
  12072. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12073. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  12074. LLM_NORM, cb, il);
  12075. cb(cur, "ffn_norm", il);
  12076. cur = llm_build_ffn(ctx0, lctx, cur,
  12077. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12078. NULL, NULL, NULL,
  12079. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12080. NULL,
  12081. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12082. cb(cur, "ffn_out", il);
  12083. cur = ggml_add(ctx0, cur, ffn_inp);
  12084. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12085. cb(cur, "l_out", il);
  12086. // input for next layer
  12087. inpL = cur;
  12088. }
  12089. cur = inpL;
  12090. cur = llm_build_norm(ctx0, cur, hparams,
  12091. model.output_norm, model.output_norm_b,
  12092. LLM_NORM, cb, -1);
  12093. cb(cur, "result_norm", -1);
  12094. // lm_head
  12095. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12096. cb(cur, "result_output", -1);
  12097. ggml_build_forward_expand(gf, cur);
  12098. return gf;
  12099. }
  12100. struct ggml_cgraph * build_mamba() {
  12101. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12102. struct ggml_tensor * cur;
  12103. struct ggml_tensor * inpL;
  12104. // {n_embd, n_tokens}
  12105. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12106. struct ggml_tensor * state_copy = build_inp_s_copy();
  12107. struct ggml_tensor * state_mask = build_inp_s_mask();
  12108. for (int il = 0; il < n_layer; ++il) {
  12109. // norm
  12110. cur = llm_build_norm(ctx0, inpL, hparams,
  12111. model.layers[il].attn_norm, NULL,
  12112. LLM_NORM_RMS, cb, il);
  12113. cb(cur, "attn_norm", il);
  12114. cur = llm_build_mamba(ctx0, lctx, batch, gf, cur,
  12115. state_copy, state_mask,
  12116. kv_head, n_kv, cb, il);
  12117. if (il == n_layer - 1) {
  12118. // skip computing output for unused tokens
  12119. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12120. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12121. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12122. }
  12123. // residual
  12124. cur = ggml_add(ctx0, cur, inpL);
  12125. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12126. cb(cur, "l_out", il);
  12127. // input for next layer
  12128. inpL = cur;
  12129. }
  12130. // final rmsnorm
  12131. cur = llm_build_norm(ctx0, inpL, hparams,
  12132. model.output_norm, NULL,
  12133. LLM_NORM_RMS, cb, -1);
  12134. cb(cur, "result_norm", -1);
  12135. // lm_head
  12136. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12137. cb(cur, "result_output", -1);
  12138. ggml_build_forward_expand(gf, cur);
  12139. return gf;
  12140. }
  12141. struct ggml_cgraph * build_command_r() {
  12142. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12143. const int64_t n_embd_head = hparams.n_embd_head_v;
  12144. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12145. const float f_logit_scale = hparams.f_logit_scale;
  12146. struct ggml_tensor * cur;
  12147. struct ggml_tensor * inpL;
  12148. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12149. // inp_pos - contains the positions
  12150. struct ggml_tensor * inp_pos = build_inp_pos();
  12151. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12152. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12153. for (int il = 0; il < n_layer; ++il) {
  12154. // norm
  12155. cur = llm_build_norm(ctx0, inpL, hparams,
  12156. model.layers[il].attn_norm, NULL,
  12157. LLM_NORM, cb, il);
  12158. cb(cur, "attn_norm", il);
  12159. struct ggml_tensor * ffn_inp = cur;
  12160. // self-attention
  12161. {
  12162. // compute Q and K and RoPE them
  12163. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12164. cb(Qcur, "Qcur", il);
  12165. if (model.layers[il].bq) {
  12166. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12167. cb(Qcur, "Qcur", il);
  12168. }
  12169. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12170. cb(Kcur, "Kcur", il);
  12171. if (model.layers[il].bk) {
  12172. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12173. cb(Kcur, "Kcur", il);
  12174. }
  12175. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12176. cb(Vcur, "Vcur", il);
  12177. if (model.layers[il].bv) {
  12178. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12179. cb(Vcur, "Vcur", il);
  12180. }
  12181. if (model.layers[il].attn_q_norm) {
  12182. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  12183. ggml_element_size(Qcur) * n_embd_head,
  12184. ggml_element_size(Qcur) * n_embd_head * n_head,
  12185. 0);
  12186. cb(Qcur, "Qcur", il);
  12187. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  12188. ggml_element_size(Kcur) * n_embd_head,
  12189. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  12190. 0);
  12191. cb(Kcur, "Kcur", il);
  12192. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12193. model.layers[il].attn_q_norm,
  12194. NULL,
  12195. LLM_NORM, cb, il);
  12196. cb(Qcur, "Qcur", il);
  12197. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12198. model.layers[il].attn_k_norm,
  12199. NULL,
  12200. LLM_NORM, cb, il);
  12201. cb(Kcur, "Kcur", il);
  12202. }
  12203. Qcur = ggml_rope_ext(
  12204. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12205. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12206. ext_factor, attn_factor, beta_fast, beta_slow
  12207. );
  12208. cb(Qcur, "Qcur", il);
  12209. Kcur = ggml_rope_ext(
  12210. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12211. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12212. ext_factor, attn_factor, beta_fast, beta_slow
  12213. );
  12214. cb(Kcur, "Kcur", il);
  12215. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12216. model.layers[il].wo, model.layers[il].bo,
  12217. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12218. }
  12219. if (il == n_layer - 1) {
  12220. // skip computing output for unused tokens
  12221. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12222. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12223. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12224. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  12225. }
  12226. struct ggml_tensor * attn_out = cur;
  12227. // feed-forward network
  12228. {
  12229. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  12230. model.layers[il].ffn_up, NULL, NULL,
  12231. model.layers[il].ffn_gate, NULL, NULL,
  12232. model.layers[il].ffn_down, NULL, NULL,
  12233. NULL,
  12234. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12235. cb(cur, "ffn_out", il);
  12236. }
  12237. // add together residual + FFN + self-attention
  12238. cur = ggml_add(ctx0, cur, inpL);
  12239. cur = ggml_add(ctx0, cur, attn_out);
  12240. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12241. cb(cur, "l_out", il);
  12242. // input for next layer
  12243. inpL = cur;
  12244. }
  12245. cur = inpL;
  12246. cur = llm_build_norm(ctx0, cur, hparams,
  12247. model.output_norm, NULL,
  12248. LLM_NORM, cb, -1);
  12249. cb(cur, "result_norm", -1);
  12250. // lm_head
  12251. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12252. if (f_logit_scale) {
  12253. cur = ggml_scale(ctx0, cur, f_logit_scale);
  12254. }
  12255. cb(cur, "result_output", -1);
  12256. ggml_build_forward_expand(gf, cur);
  12257. return gf;
  12258. }
  12259. // ref: https://allenai.org/olmo
  12260. // based on the original build_llama() function, changes:
  12261. // * non-parametric layer norm
  12262. // * clamp qkv
  12263. // * removed bias
  12264. // * removed MoE
  12265. struct ggml_cgraph * build_olmo() {
  12266. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12267. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12268. int32_t n_tokens = this->n_tokens;
  12269. const int64_t n_embd_head = hparams.n_embd_head_v;
  12270. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12271. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12272. struct ggml_tensor * cur;
  12273. struct ggml_tensor * inpL;
  12274. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12275. // inp_pos - contains the positions
  12276. struct ggml_tensor * inp_pos = build_inp_pos();
  12277. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12278. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12279. for (int il = 0; il < n_layer; ++il) {
  12280. struct ggml_tensor * inpSA = inpL;
  12281. // norm
  12282. cur = llm_build_norm(ctx0, inpL, hparams,
  12283. NULL, NULL,
  12284. LLM_NORM, cb, il);
  12285. cb(cur, "attn_norm", il);
  12286. // self-attention
  12287. {
  12288. // compute Q and K and RoPE them
  12289. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12290. cb(Qcur, "Qcur", il);
  12291. if (hparams.f_clamp_kqv > 0.0f) {
  12292. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12293. cb(Qcur, "Qcur", il);
  12294. }
  12295. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12296. cb(Kcur, "Kcur", il);
  12297. if (hparams.f_clamp_kqv > 0.0f) {
  12298. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12299. cb(Kcur, "Kcur", il);
  12300. }
  12301. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12302. cb(Vcur, "Vcur", il);
  12303. if (hparams.f_clamp_kqv > 0.0f) {
  12304. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  12305. cb(Vcur, "Vcur", il);
  12306. }
  12307. Qcur = ggml_rope_ext(
  12308. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12309. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12310. ext_factor, attn_factor, beta_fast, beta_slow
  12311. );
  12312. cb(Qcur, "Qcur", il);
  12313. Kcur = ggml_rope_ext(
  12314. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12315. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12316. ext_factor, attn_factor, beta_fast, beta_slow
  12317. );
  12318. cb(Kcur, "Kcur", il);
  12319. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12320. model.layers[il].wo, nullptr,
  12321. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12322. }
  12323. if (il == n_layer - 1) {
  12324. // skip computing output for unused tokens
  12325. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12326. n_tokens = n_outputs;
  12327. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12328. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12329. }
  12330. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12331. cb(ffn_inp, "ffn_inp", il);
  12332. // feed-forward network
  12333. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12334. NULL, NULL,
  12335. LLM_NORM, cb, il);
  12336. cb(cur, "ffn_norm", il);
  12337. cur = llm_build_ffn(ctx0, lctx, cur,
  12338. model.layers[il].ffn_up, NULL, NULL,
  12339. model.layers[il].ffn_gate, NULL, NULL,
  12340. model.layers[il].ffn_down, NULL, NULL,
  12341. NULL,
  12342. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12343. cb(cur, "ffn_out", il);
  12344. cur = ggml_add(ctx0, cur, ffn_inp);
  12345. cb(cur, "ffn_out", il);
  12346. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12347. cb(cur, "l_out", il);
  12348. // input for next layer
  12349. inpL = cur;
  12350. }
  12351. cur = inpL;
  12352. cur = llm_build_norm(ctx0, cur, hparams,
  12353. NULL, NULL,
  12354. LLM_NORM, cb, -1);
  12355. cb(cur, "result_norm", -1);
  12356. // lm_head
  12357. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12358. cb(cur, "result_output", -1);
  12359. ggml_build_forward_expand(gf, cur);
  12360. return gf;
  12361. }
  12362. // based on the build_qwen2moe() function, changes:
  12363. // * removed shared experts
  12364. // * removed bias
  12365. // * added q, k norm
  12366. struct ggml_cgraph * build_olmoe() {
  12367. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12368. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12369. int32_t n_tokens = this->n_tokens;
  12370. const int64_t n_embd_head = hparams.n_embd_head_v;
  12371. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12372. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12373. struct ggml_tensor * cur;
  12374. struct ggml_tensor * inpL;
  12375. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12376. // inp_pos - contains the positions
  12377. struct ggml_tensor * inp_pos = build_inp_pos();
  12378. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12379. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12380. for (int il = 0; il < n_layer; ++il) {
  12381. struct ggml_tensor * inpSA = inpL;
  12382. // norm
  12383. cur = llm_build_norm(ctx0, inpL, hparams,
  12384. model.layers[il].attn_norm, NULL,
  12385. LLM_NORM_RMS, cb, il);
  12386. cb(cur, "attn_norm", il);
  12387. // self_attention
  12388. {
  12389. // compute Q and K and RoPE them
  12390. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12391. cb(Qcur, "Qcur", il);
  12392. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12393. cb(Kcur, "Kcur", il);
  12394. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12395. cb(Vcur, "Vcur", il);
  12396. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12397. LLM_NORM_RMS, cb, il);
  12398. cb(Qcur, "Qcur_normed", il);
  12399. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12400. LLM_NORM_RMS, cb, il);
  12401. cb(Kcur, "Kcur_normed", il);
  12402. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12403. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12404. Qcur = ggml_rope_ext(
  12405. ctx0, Qcur, inp_pos, nullptr,
  12406. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12407. ext_factor, attn_factor, beta_fast, beta_slow
  12408. );
  12409. cb(Qcur, "Qcur_rope", il);
  12410. Kcur = ggml_rope_ext(
  12411. ctx0, Kcur, inp_pos, nullptr,
  12412. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12413. ext_factor, attn_factor, beta_fast, beta_slow
  12414. );
  12415. cb(Kcur, "Kcur_rope", il);
  12416. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12417. model.layers[il].wo, NULL,
  12418. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12419. }
  12420. if (il == n_layer - 1) {
  12421. // skip computing output for unused tokens
  12422. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12423. n_tokens = n_outputs;
  12424. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12425. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12426. }
  12427. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12428. cb(ffn_inp, "ffn_inp", il);
  12429. // MoE branch
  12430. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12431. model.layers[il].ffn_norm, NULL,
  12432. LLM_NORM_RMS, cb, il);
  12433. cb(cur, "ffn_norm", il);
  12434. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12435. model.layers[il].ffn_gate_inp,
  12436. model.layers[il].ffn_up_exps,
  12437. model.layers[il].ffn_gate_exps,
  12438. model.layers[il].ffn_down_exps,
  12439. n_expert, n_expert_used,
  12440. LLM_FFN_SILU, false,
  12441. false, 0.0,
  12442. cb, il);
  12443. cb(cur, "ffn_moe_out", il);
  12444. cur = ggml_add(ctx0, cur, ffn_inp);
  12445. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12446. cb(cur, "l_out", il);
  12447. // input for next layer
  12448. inpL = cur;
  12449. }
  12450. cur = inpL;
  12451. cur = llm_build_norm(ctx0, cur, hparams,
  12452. model.output_norm, NULL,
  12453. LLM_NORM_RMS, cb, -1);
  12454. cb(cur, "result_norm", -1);
  12455. // lm_head
  12456. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12457. cb(cur, "result_output", -1);
  12458. ggml_build_forward_expand(gf, cur);
  12459. return gf;
  12460. }
  12461. struct ggml_cgraph * build_openelm() {
  12462. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12463. const int64_t n_embd_head = hparams.n_embd_head_v;
  12464. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12465. struct ggml_tensor * cur;
  12466. struct ggml_tensor * inpL;
  12467. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12468. // inp_pos - contains the positions
  12469. struct ggml_tensor * inp_pos = build_inp_pos();
  12470. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12471. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12472. for (int il = 0; il < n_layer; ++il) {
  12473. const int64_t n_head = hparams.n_head(il);
  12474. const int64_t n_head_kv = hparams.n_head_kv(il);
  12475. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12476. cur = inpL;
  12477. struct ggml_tensor * residual = cur;
  12478. // norm
  12479. cur = llm_build_norm(ctx0, inpL, hparams,
  12480. model.layers[il].attn_norm, NULL,
  12481. LLM_NORM_RMS, cb, il);
  12482. cb(cur, "attn_norm", il);
  12483. // self-attention
  12484. {
  12485. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12486. cb(cur, "wqkv", il);
  12487. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12488. 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));
  12489. cb(Qcur, "Qcur", il);
  12490. 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));
  12491. cb(Kcur, "Kcur", il);
  12492. 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)));
  12493. cb(Vcur, "Vcur", il);
  12494. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12495. model.layers[il].attn_q_norm, NULL,
  12496. LLM_NORM_RMS, cb, il);
  12497. cb(Qcur, "Qcur", il);
  12498. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12499. model.layers[il].attn_k_norm, NULL,
  12500. LLM_NORM_RMS, cb, il);
  12501. cb(Kcur, "Kcur", il);
  12502. Qcur = ggml_rope_ext(
  12503. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12504. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12505. );
  12506. cb(Qcur, "Qcur", il);
  12507. Kcur = ggml_rope_ext(
  12508. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12509. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12510. );
  12511. cb(Kcur, "Kcur", il);
  12512. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12513. cb(Qcur, "Vcur", il);
  12514. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12515. model.layers[il].wo, NULL,
  12516. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12517. }
  12518. if (il == n_layer - 1) {
  12519. // skip computing output for unused tokens
  12520. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12521. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  12522. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12523. }
  12524. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  12525. cb(ffn_inp, "ffn_inp", il);
  12526. // feed-forward network
  12527. {
  12528. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12529. model.layers[il].ffn_norm, NULL,
  12530. LLM_NORM_RMS, cb, il);
  12531. cb(cur, "ffn_norm", il);
  12532. cur = llm_build_ffn(ctx0, lctx, cur,
  12533. model.layers[il].ffn_up, NULL, NULL,
  12534. model.layers[il].ffn_gate, NULL, NULL,
  12535. model.layers[il].ffn_down, NULL, NULL,
  12536. NULL,
  12537. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12538. cb(cur, "ffn_out", il);
  12539. }
  12540. cur = ggml_add(ctx0, cur, ffn_inp);
  12541. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12542. cb(cur, "l_out", il);
  12543. inpL = cur;
  12544. }
  12545. cur = inpL;
  12546. // norm
  12547. cur = llm_build_norm(ctx0, cur, hparams,
  12548. model.output_norm, NULL,
  12549. LLM_NORM_RMS, cb, -1);
  12550. cb(cur, "result_norm", -1);
  12551. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12552. cb(cur, "result_output", -1);
  12553. ggml_build_forward_expand(gf, cur);
  12554. return gf;
  12555. }
  12556. struct ggml_cgraph * build_gptneox() {
  12557. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12558. const int64_t n_embd_head = hparams.n_embd_head_v;
  12559. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12560. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12561. struct ggml_tensor * cur;
  12562. struct ggml_tensor * inpL;
  12563. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12564. // inp_pos - contains the positions
  12565. struct ggml_tensor * inp_pos = build_inp_pos();
  12566. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12567. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12568. for (int il = 0; il < n_layer; ++il) {
  12569. cur = llm_build_norm(ctx0, inpL, hparams,
  12570. model.layers[il].attn_norm,
  12571. model.layers[il].attn_norm_b,
  12572. LLM_NORM, cb, il);
  12573. cb(cur, "attn_norm", il);
  12574. // self-attention
  12575. {
  12576. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12577. cb(cur, "wqkv", il);
  12578. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  12579. cb(cur, "bqkv", il);
  12580. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  12581. 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)));
  12582. 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)));
  12583. cb(Qcur, "Qcur", il);
  12584. cb(Kcur, "Kcur", il);
  12585. cb(Vcur, "Vcur", il);
  12586. Qcur = ggml_rope_ext(
  12587. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12588. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12589. ext_factor, attn_factor, beta_fast, beta_slow
  12590. );
  12591. cb(Qcur, "Qcur", il);
  12592. Kcur = ggml_rope_ext(
  12593. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12594. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12595. ext_factor, attn_factor, beta_fast, beta_slow
  12596. );
  12597. cb(Kcur, "Kcur", il);
  12598. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12599. model.layers[il].wo, model.layers[il].bo,
  12600. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12601. }
  12602. if (il == n_layer - 1) {
  12603. // skip computing output for unused tokens
  12604. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12605. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12606. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12607. }
  12608. // ffn
  12609. if (hparams.use_par_res) {
  12610. // attention and ffn are computed in parallel
  12611. // x = x + attn(ln1(x)) + ffn(ln2(x))
  12612. struct ggml_tensor * attn_out = cur;
  12613. cur = llm_build_norm(ctx0, inpL, hparams,
  12614. model.layers[il].ffn_norm,
  12615. model.layers[il].ffn_norm_b,
  12616. LLM_NORM, cb, il);
  12617. cb(cur, "ffn_norm", il);
  12618. cur = llm_build_ffn(ctx0, lctx, cur,
  12619. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12620. NULL, NULL, NULL,
  12621. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12622. NULL,
  12623. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12624. cb(cur, "ffn_out", il);
  12625. cur = ggml_add(ctx0, cur, inpL);
  12626. cb(cur, "ffn_out", il);
  12627. cur = ggml_add(ctx0, cur, attn_out);
  12628. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12629. cb(cur, "l_out", il);
  12630. // input for next layer
  12631. inpL = cur;
  12632. } else {
  12633. // attention and ffn are computed sequentially
  12634. // x = x + attn(ln1(x))
  12635. // x = x + ffn(ln2(x))
  12636. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  12637. cb(ffn_inp, "ffn_inp", il);
  12638. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12639. model.layers[il].ffn_norm,
  12640. model.layers[il].ffn_norm_b,
  12641. LLM_NORM, cb, il);
  12642. cb(cur, "ffn_norm", il);
  12643. cur = llm_build_ffn(ctx0, lctx, cur,
  12644. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12645. NULL, NULL, NULL,
  12646. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12647. NULL,
  12648. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12649. cb(cur, "ffn_out", il);
  12650. cur = ggml_add(ctx0, cur, ffn_inp);
  12651. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12652. cb(cur, "l_out", il);
  12653. // input for next layer
  12654. inpL = cur;
  12655. }
  12656. }
  12657. cur = llm_build_norm(ctx0, inpL, hparams,
  12658. model.output_norm,
  12659. model.output_norm_b,
  12660. LLM_NORM, cb, -1);
  12661. cb(cur, "result_norm", -1);
  12662. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12663. cb(cur, "result_output", -1);
  12664. ggml_build_forward_expand(gf, cur);
  12665. return gf;
  12666. }
  12667. struct ggml_cgraph * build_arctic() {
  12668. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12669. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12670. int32_t n_tokens = this->n_tokens;
  12671. const int64_t n_embd_head = hparams.n_embd_head_v;
  12672. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12673. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12674. struct ggml_tensor * cur;
  12675. struct ggml_tensor * inpL;
  12676. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12677. // inp_pos - contains the positions
  12678. struct ggml_tensor * inp_pos = build_inp_pos();
  12679. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12680. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12681. for (int il = 0; il < n_layer; ++il) {
  12682. struct ggml_tensor * inpSA = inpL;
  12683. // norm
  12684. cur = llm_build_norm(ctx0, inpL, hparams,
  12685. model.layers[il].attn_norm, NULL,
  12686. LLM_NORM_RMS, cb, il);
  12687. cb(cur, "attn_norm", il);
  12688. // self-attention
  12689. {
  12690. // compute Q and K and RoPE them
  12691. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12692. cb(Qcur, "Qcur", il);
  12693. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12694. cb(Kcur, "Kcur", il);
  12695. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12696. cb(Vcur, "Vcur", il);
  12697. Qcur = ggml_rope_ext(
  12698. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12699. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12700. ext_factor, attn_factor, beta_fast, beta_slow
  12701. );
  12702. cb(Qcur, "Qcur", il);
  12703. Kcur = ggml_rope_ext(
  12704. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12705. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12706. ext_factor, attn_factor, beta_fast, beta_slow
  12707. );
  12708. cb(Kcur, "Kcur", il);
  12709. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12710. model.layers[il].wo, NULL,
  12711. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12712. }
  12713. if (il == n_layer - 1) {
  12714. // skip computing output for unused tokens
  12715. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12716. n_tokens = n_outputs;
  12717. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12718. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12719. }
  12720. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12721. cb(ffn_inp, "ffn_inp", il);
  12722. // feed-forward network
  12723. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12724. model.layers[il].ffn_norm, NULL,
  12725. LLM_NORM_RMS, cb, il);
  12726. cb(cur, "ffn_norm", il);
  12727. cur = llm_build_ffn(ctx0, lctx, cur,
  12728. model.layers[il].ffn_up, NULL, NULL,
  12729. model.layers[il].ffn_gate, NULL, NULL,
  12730. model.layers[il].ffn_down, NULL, NULL,
  12731. NULL,
  12732. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12733. cb(cur, "ffn_out", il);
  12734. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  12735. cb(ffn_out, "ffn_out", il);
  12736. // MoE
  12737. cur = llm_build_norm(ctx0, inpSA, hparams,
  12738. model.layers[il].ffn_norm_exps, NULL,
  12739. LLM_NORM_RMS, cb, il);
  12740. cb(cur, "ffn_norm_exps", il);
  12741. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12742. model.layers[il].ffn_gate_inp,
  12743. model.layers[il].ffn_up_exps,
  12744. model.layers[il].ffn_gate_exps,
  12745. model.layers[il].ffn_down_exps,
  12746. n_expert, n_expert_used,
  12747. LLM_FFN_SILU, true,
  12748. false, 0.0,
  12749. cb, il);
  12750. cb(cur, "ffn_moe_out", il);
  12751. cur = ggml_add(ctx0, cur, ffn_out);
  12752. cb(cur, "ffn_out", il);
  12753. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12754. cb(cur, "l_out", il);
  12755. // input for next layer
  12756. inpL = cur;
  12757. }
  12758. cur = inpL;
  12759. cur = llm_build_norm(ctx0, cur, hparams,
  12760. model.output_norm, NULL,
  12761. LLM_NORM_RMS, cb, -1);
  12762. cb(cur, "result_norm", -1);
  12763. // lm_head
  12764. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12765. cb(cur, "result_output", -1);
  12766. ggml_build_forward_expand(gf, cur);
  12767. return gf;
  12768. }
  12769. struct ggml_cgraph * build_deepseek2() {
  12770. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12771. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12772. int32_t n_tokens = this->n_tokens;
  12773. bool is_lite = (hparams.n_layer == 27);
  12774. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  12775. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  12776. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  12777. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  12778. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  12779. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12780. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12781. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12782. struct ggml_tensor * cur;
  12783. struct ggml_tensor * inpL;
  12784. // {n_embd, n_tokens}
  12785. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12786. // inp_pos - contains the positions
  12787. struct ggml_tensor * inp_pos = build_inp_pos();
  12788. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12789. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12790. for (int il = 0; il < n_layer; ++il) {
  12791. struct ggml_tensor * inpSA = inpL;
  12792. // norm
  12793. cur = llm_build_norm(ctx0, inpL, hparams,
  12794. model.layers[il].attn_norm, NULL,
  12795. LLM_NORM_RMS, cb, il);
  12796. cb(cur, "attn_norm", il);
  12797. // self_attention
  12798. {
  12799. struct ggml_tensor * q = NULL;
  12800. if (!is_lite) {
  12801. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12802. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12803. cb(q, "q", il);
  12804. q = llm_build_norm(ctx0, q, hparams,
  12805. model.layers[il].attn_q_a_norm, NULL,
  12806. LLM_NORM_RMS, cb, il);
  12807. cb(q, "q", il);
  12808. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12809. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12810. cb(q, "q", il);
  12811. } else {
  12812. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  12813. cb(q, "q", il);
  12814. }
  12815. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12816. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12817. ggml_row_size(q->type, hparams.n_embd_head_k),
  12818. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12819. 0);
  12820. cb(q_nope, "q_nope", il);
  12821. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12822. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12823. ggml_row_size(q->type, hparams.n_embd_head_k),
  12824. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12825. ggml_row_size(q->type, n_embd_head_qk_nope));
  12826. cb(q_pe, "q_pe", il);
  12827. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12828. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12829. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12830. // split into {kv_lora_rank, n_tokens}
  12831. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12832. kv_pe_compresseed->nb[1],
  12833. 0);
  12834. cb(kv_compressed, "kv_compressed", il);
  12835. // and {n_embd_head_qk_rope, n_tokens}
  12836. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12837. kv_pe_compresseed->nb[1],
  12838. kv_pe_compresseed->nb[1],
  12839. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12840. cb(k_pe, "k_pe", il);
  12841. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12842. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12843. model.layers[il].attn_kv_a_norm, NULL,
  12844. LLM_NORM_RMS, cb, il);
  12845. cb(kv_compressed, "kv_compressed", il);
  12846. // {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}
  12847. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12848. cb(kv, "kv", il);
  12849. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12850. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12851. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12852. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12853. 0);
  12854. cb(k_nope, "k_nope", il);
  12855. // and {n_head * n_embd_head_v, n_tokens}
  12856. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12857. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12858. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12859. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12860. cb(v_states, "v_states", il);
  12861. v_states = ggml_cont(ctx0, v_states);
  12862. cb(v_states, "v_states", il);
  12863. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12864. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12865. 0);
  12866. cb(v_states, "v_states", il);
  12867. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12868. q_pe = ggml_rope_ext(
  12869. ctx0, q_pe, inp_pos, nullptr,
  12870. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12871. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12872. );
  12873. cb(q_pe, "q_pe", il);
  12874. // shared RoPE key
  12875. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12876. k_pe = ggml_rope_ext(
  12877. ctx0, k_pe, inp_pos, nullptr,
  12878. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12879. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12880. );
  12881. cb(k_pe, "k_pe", il);
  12882. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12883. cb(q_states, "q_states", il);
  12884. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12885. cb(k_states, "k_states", il);
  12886. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12887. model.layers[il].wo, NULL,
  12888. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12889. }
  12890. if (il == n_layer - 1) {
  12891. // skip computing output for unused tokens
  12892. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12893. n_tokens = n_outputs;
  12894. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12895. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12896. }
  12897. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12898. cb(ffn_inp, "ffn_inp", il);
  12899. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12900. model.layers[il].ffn_norm, NULL,
  12901. LLM_NORM_RMS, cb, il);
  12902. cb(cur, "ffn_norm", il);
  12903. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  12904. cur = llm_build_ffn(ctx0, lctx, cur,
  12905. model.layers[il].ffn_up, NULL, NULL,
  12906. model.layers[il].ffn_gate, NULL, NULL,
  12907. model.layers[il].ffn_down, NULL, NULL,
  12908. NULL,
  12909. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12910. cb(cur, "ffn_out", il);
  12911. } else {
  12912. // MoE branch
  12913. ggml_tensor * moe_out =
  12914. llm_build_moe_ffn(ctx0, lctx, cur,
  12915. model.layers[il].ffn_gate_inp,
  12916. model.layers[il].ffn_up_exps,
  12917. model.layers[il].ffn_gate_exps,
  12918. model.layers[il].ffn_down_exps,
  12919. n_expert, n_expert_used,
  12920. LLM_FFN_SILU, false,
  12921. true, hparams.expert_weights_scale,
  12922. cb, il);
  12923. cb(moe_out, "ffn_moe_out", il);
  12924. // FFN shared expert
  12925. {
  12926. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  12927. model.layers[il].ffn_up_shexp, NULL, NULL,
  12928. model.layers[il].ffn_gate_shexp, NULL, NULL,
  12929. model.layers[il].ffn_down_shexp, NULL, NULL,
  12930. NULL,
  12931. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12932. cb(ffn_shexp, "ffn_shexp", il);
  12933. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  12934. cb(cur, "ffn_out", il);
  12935. }
  12936. }
  12937. cur = ggml_add(ctx0, cur, ffn_inp);
  12938. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12939. cb(cur, "l_out", il);
  12940. // input for next layer
  12941. inpL = cur;
  12942. }
  12943. cur = inpL;
  12944. cur = llm_build_norm(ctx0, cur, hparams,
  12945. model.output_norm, NULL,
  12946. LLM_NORM_RMS, cb, -1);
  12947. cb(cur, "result_norm", -1);
  12948. // lm_head
  12949. cur = ggml_mul_mat(ctx0, model.output, cur);
  12950. cb(cur, "result_output", -1);
  12951. ggml_build_forward_expand(gf, cur);
  12952. return gf;
  12953. }
  12954. struct ggml_cgraph * build_bitnet() {
  12955. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12956. const int64_t n_embd_head = hparams.n_embd_head_v;
  12957. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12958. struct ggml_tensor * cur;
  12959. struct ggml_tensor * inpL;
  12960. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12961. // inp_pos - contains the positions
  12962. struct ggml_tensor * inp_pos = build_inp_pos();
  12963. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12964. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12965. for (int il = 0; il < n_layer; ++il) {
  12966. struct ggml_tensor * inpSA = inpL;
  12967. cur = llm_build_norm(ctx0, inpL, hparams,
  12968. model.layers[il].attn_norm, NULL,
  12969. LLM_NORM_RMS, cb, il);
  12970. cb(cur, "attn_norm", il);
  12971. // self-attention
  12972. {
  12973. // compute Q and K and RoPE them
  12974. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12975. if (model.layers[il].wq_scale) {
  12976. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  12977. }
  12978. cb(Qcur, "Qcur", il);
  12979. if (model.layers[il].bq) {
  12980. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12981. cb(Qcur, "Qcur", il);
  12982. }
  12983. // B1.K
  12984. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12985. if (model.layers[il].wk_scale) {
  12986. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  12987. }
  12988. cb(Kcur, "Kcur", il);
  12989. if (model.layers[il].bk) {
  12990. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12991. cb(Kcur, "Kcur", il);
  12992. }
  12993. // B1.V
  12994. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12995. if (model.layers[il].wv_scale) {
  12996. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  12997. }
  12998. cb(Vcur, "Vcur", il);
  12999. if (model.layers[il].bv) {
  13000. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13001. cb(Vcur, "Vcur", il);
  13002. }
  13003. Qcur = ggml_rope_ext(
  13004. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13005. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13006. ext_factor, attn_factor, beta_fast, beta_slow
  13007. );
  13008. cb(Qcur, "Qcur", il);
  13009. Kcur = ggml_rope_ext(
  13010. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13011. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13012. ext_factor, attn_factor, beta_fast, beta_slow
  13013. );
  13014. cb(Kcur, "Kcur", il);
  13015. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13016. NULL, NULL,
  13017. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13018. cur = llm_build_norm(ctx0, cur, hparams,
  13019. model.layers[il].attn_sub_norm, NULL,
  13020. LLM_NORM_RMS, cb, il);
  13021. cb(cur, "attn_sub_norm", il);
  13022. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13023. if (model.layers[il].wo_scale) {
  13024. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  13025. }
  13026. if (model.layers[il].bo) {
  13027. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  13028. }
  13029. cb(cur, "attn_o_out", il);
  13030. }
  13031. if (il == n_layer - 1) {
  13032. // skip computing output for unused tokens
  13033. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13034. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13035. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13036. }
  13037. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13038. cb(ffn_inp, "ffn_inp", il);
  13039. // feed-forward forward
  13040. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13041. model.layers[il].ffn_norm, NULL,
  13042. LLM_NORM_RMS, cb, il);
  13043. cb(cur, "ffn_norm", il);
  13044. cur = llm_build_ffn(ctx0, lctx, cur,
  13045. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  13046. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  13047. NULL, NULL, NULL,
  13048. NULL,
  13049. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13050. cb(cur, "ffn_sub_out", il);
  13051. cur = llm_build_norm(ctx0, cur, hparams,
  13052. model.layers[il].ffn_sub_norm, NULL,
  13053. LLM_NORM_RMS, cb, il);
  13054. cb(cur, "ffn_sub_norm", il);
  13055. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  13056. if (model.layers[il].ffn_down_scale) {
  13057. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  13058. }
  13059. cb(cur, "ffn_down", il);
  13060. cur = ggml_add(ctx0, cur, ffn_inp);
  13061. cb(cur, "l_out", il);
  13062. // input for next layer
  13063. inpL = cur;
  13064. }
  13065. cur = inpL;
  13066. cur = llm_build_norm(ctx0, cur, hparams,
  13067. model.output_norm, NULL,
  13068. LLM_NORM_RMS, cb, -1);
  13069. cb(cur, "result_norm", -1);
  13070. // lm_head
  13071. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  13072. cb(cur, "result_output", -1);
  13073. ggml_build_forward_expand(gf, cur);
  13074. return gf;
  13075. }
  13076. struct ggml_cgraph * build_t5_encoder() {
  13077. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13078. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13079. int32_t n_tokens = this->n_tokens;
  13080. const int64_t n_embd_head = hparams.n_embd_head_v;
  13081. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13082. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13083. struct ggml_tensor * cur;
  13084. struct ggml_tensor * inpL;
  13085. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13086. GGML_ASSERT(lctx.is_encoding);
  13087. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  13088. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13089. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  13090. for (int il = 0; il < n_layer; ++il) {
  13091. struct ggml_tensor * inpSA = inpL;
  13092. // norm
  13093. cur = llm_build_norm(ctx0, inpL, hparams,
  13094. model.layers[il].attn_norm_enc, NULL,
  13095. LLM_NORM_RMS, cb, il);
  13096. cb(cur, "attn_norm", il);
  13097. // self-attention
  13098. {
  13099. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  13100. cb(Qcur, "Qcur", il);
  13101. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  13102. cb(Kcur, "Kcur", il);
  13103. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  13104. cb(Vcur, "Vcur", il);
  13105. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13106. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  13107. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13108. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13109. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13110. cb(kq, "kq", il);
  13111. 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;
  13112. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  13113. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13114. cb(kq_b, "kq_b", il);
  13115. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  13116. cb(kq, "kq_soft_max_ext", il);
  13117. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  13118. cb(v, "v", il);
  13119. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  13120. cb(kqv, "kqv", il);
  13121. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13122. cb(kqv_merged, "kqv_merged", il);
  13123. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13124. cb(cur, "kqv_merged_cont", il);
  13125. ggml_build_forward_expand(gf, cur);
  13126. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  13127. cb(cur, "kqv_out", il);
  13128. }
  13129. if (il == n_layer - 1) {
  13130. // skip computing output for unused tokens
  13131. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13132. n_tokens = n_outputs;
  13133. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13134. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13135. }
  13136. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13137. cb(ffn_inp, "ffn_inp", il);
  13138. // feed-forward network
  13139. {
  13140. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13141. model.layers[il].ffn_norm_enc, NULL,
  13142. LLM_NORM_RMS, cb, il);
  13143. cb(cur, "ffn_norm", il);
  13144. // T5 uses relu, flan-T5 uses gelu-gated
  13145. cur = llm_build_ffn(ctx0, lctx, cur,
  13146. model.layers[il].ffn_up_enc, NULL, NULL,
  13147. model.layers[il].ffn_gate_enc, NULL, NULL,
  13148. model.layers[il].ffn_down_enc, NULL, NULL,
  13149. NULL,
  13150. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13151. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13152. cb, il);
  13153. cb(cur, "ffn_out", il);
  13154. }
  13155. cur = ggml_add(ctx0, cur, ffn_inp);
  13156. cb(cur, "ffn_out", il);
  13157. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13158. if (layer_dir != nullptr) {
  13159. cur = ggml_add(ctx0, cur, layer_dir);
  13160. }
  13161. cb(cur, "l_out", il);
  13162. // input for next layer
  13163. inpL = cur;
  13164. }
  13165. cur = inpL;
  13166. cb(cur, "result_embd", -1);
  13167. cur = llm_build_norm(ctx0, cur, hparams,
  13168. model.output_norm_enc, NULL,
  13169. LLM_NORM_RMS, cb, -1);
  13170. cb(cur, "result_norm", -1);
  13171. ggml_build_forward_expand(gf, cur);
  13172. return gf;
  13173. }
  13174. struct ggml_cgraph * build_t5_decoder() {
  13175. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13176. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13177. int32_t n_tokens = this->n_tokens;
  13178. const int64_t n_embd_head = hparams.n_embd_head_v;
  13179. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13180. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13181. struct ggml_tensor * cur;
  13182. struct ggml_tensor * inpL;
  13183. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13184. GGML_ASSERT(!lctx.is_encoding);
  13185. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  13186. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  13187. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  13188. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  13189. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  13190. for (int il = 0; il < n_layer; ++il) {
  13191. struct ggml_tensor * inpSA = inpL;
  13192. // norm
  13193. cur = llm_build_norm(ctx0, inpL, hparams,
  13194. model.layers[il].attn_norm, NULL,
  13195. LLM_NORM_RMS, cb, il);
  13196. cb(cur, "attn_norm", il);
  13197. // self-attention
  13198. {
  13199. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13200. cb(Qcur, "Qcur", il);
  13201. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13202. cb(Kcur, "Kcur", il);
  13203. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13204. cb(Vcur, "Vcur", il);
  13205. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  13206. struct ggml_tensor * k =
  13207. ggml_view_3d(ctx0, kv_self.k_l[il],
  13208. n_embd_head_k, n_kv, n_head_kv,
  13209. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  13210. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  13211. 0);
  13212. cb(k, "k", il);
  13213. struct ggml_tensor * v =
  13214. ggml_view_3d(ctx0, kv_self.v_l[il],
  13215. n_kv, n_embd_head_v, n_head_kv,
  13216. ggml_element_size(kv_self.v_l[il])*n_ctx,
  13217. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  13218. 0);
  13219. cb(v, "v", il);
  13220. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13221. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13222. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13223. cb(kq, "kq", il);
  13224. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  13225. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  13226. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  13227. cb(kq_b, "kq_b", il);
  13228. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  13229. cb(kq, "kq_soft_max_ext", il);
  13230. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  13231. cb(kqv, "kqv", il);
  13232. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13233. cb(kqv_merged, "kqv_merged", il);
  13234. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13235. cb(cur, "kqv_merged_cont", il);
  13236. ggml_build_forward_expand(gf, cur);
  13237. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  13238. cb(cur, "kqv_out", il);
  13239. }
  13240. cur = ggml_add(ctx0, cur, inpSA);
  13241. cb(cur, "cross_inp", il);
  13242. struct ggml_tensor * inpCA = cur;
  13243. // norm
  13244. cur = llm_build_norm(ctx0, cur, hparams,
  13245. model.layers[il].attn_norm_cross, NULL,
  13246. LLM_NORM_RMS, cb, il);
  13247. cb(cur, "attn_norm_cross", il);
  13248. // cross-attention
  13249. {
  13250. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  13251. cb(Qcur, "Qcur", il);
  13252. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  13253. cb(Kcur, "Kcur", il);
  13254. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  13255. cb(Vcur, "Vcur", il);
  13256. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13257. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  13258. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  13259. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  13260. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  13261. cb(kq, "kq", il);
  13262. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  13263. cb(kq, "kq_soft_max_ext", il);
  13264. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  13265. cb(v, "v", il);
  13266. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  13267. cb(kqv, "kqv", il);
  13268. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  13269. cb(kqv_merged, "kqv_merged", il);
  13270. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  13271. cb(cur, "kqv_merged_cont", il);
  13272. ggml_build_forward_expand(gf, cur);
  13273. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  13274. cb(cur, "kqv_out", il);
  13275. }
  13276. if (il == n_layer - 1) {
  13277. // skip computing output for unused tokens
  13278. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13279. n_tokens = n_outputs;
  13280. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13281. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13282. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  13283. }
  13284. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  13285. cb(ffn_inp, "ffn_inp", il);
  13286. // feed-forward network
  13287. {
  13288. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13289. model.layers[il].ffn_norm, NULL,
  13290. LLM_NORM_RMS, cb, il);
  13291. cb(cur, "ffn_norm", il);
  13292. // T5 uses relu, flan-T5 uses gelu-gated
  13293. cur = llm_build_ffn(ctx0, lctx, cur,
  13294. model.layers[il].ffn_up, NULL, NULL,
  13295. model.layers[il].ffn_gate, NULL, NULL,
  13296. model.layers[il].ffn_down, NULL, NULL,
  13297. NULL,
  13298. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  13299. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  13300. cb, il);
  13301. cb(cur, "ffn_out", il);
  13302. }
  13303. cur = ggml_add(ctx0, cur, ffn_inp);
  13304. cb(cur, "ffn_out", il);
  13305. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  13306. if (layer_dir != nullptr) {
  13307. cur = ggml_add(ctx0, cur, layer_dir);
  13308. }
  13309. cb(cur, "l_out", il);
  13310. // input for next layer
  13311. inpL = cur;
  13312. }
  13313. cur = inpL;
  13314. cb(cur, "result_embd", -1);
  13315. cur = llm_build_norm(ctx0, cur, hparams,
  13316. model.output_norm, NULL,
  13317. LLM_NORM_RMS, cb, -1);
  13318. cb(cur, "result_norm", -1);
  13319. // lm_head
  13320. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13321. cb(cur, "result_output", -1);
  13322. ggml_build_forward_expand(gf, cur);
  13323. return gf;
  13324. }
  13325. struct ggml_cgraph * build_jais() {
  13326. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13327. const int64_t n_embd_head = hparams.n_embd_head_v;
  13328. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13329. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13330. struct ggml_tensor * cur;
  13331. struct ggml_tensor * inpL;
  13332. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13333. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13334. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13335. for (int il = 0; il < n_layer; ++il) {
  13336. cur = llm_build_norm(ctx0, inpL, hparams,
  13337. model.layers[il].attn_norm,
  13338. model.layers[il].attn_norm_b,
  13339. LLM_NORM, cb, il);
  13340. cb(cur, "attn_norm", il);
  13341. // self-attention
  13342. {
  13343. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13344. cb(cur, "wqkv", il);
  13345. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13346. cb(cur, "bqkv", il);
  13347. 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)));
  13348. 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)));
  13349. 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)));
  13350. cb(Qcur, "Qcur", il);
  13351. cb(Kcur, "Kcur", il);
  13352. cb(Vcur, "Vcur", il);
  13353. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  13354. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13355. model.layers[il].wo, model.layers[il].bo,
  13356. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  13357. }
  13358. if (il == n_layer - 1) {
  13359. // skip computing output for unused tokens
  13360. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13361. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13362. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  13363. }
  13364. // add the input
  13365. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  13366. cb(ffn_inp, "ffn_inp", il);
  13367. // FF
  13368. {
  13369. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13370. model.layers[il].ffn_norm,
  13371. model.layers[il].ffn_norm_b,
  13372. LLM_NORM, cb, il);
  13373. cb(cur, "ffn_norm", il);
  13374. cur = llm_build_ffn(ctx0, lctx, cur,
  13375. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13376. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  13377. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13378. NULL,
  13379. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13380. cb(cur, "ffn_out", il);
  13381. }
  13382. inpL = ggml_add(ctx0, cur, ffn_inp);
  13383. cb(inpL, "l_out", il);
  13384. }
  13385. cur = llm_build_norm(ctx0, inpL, hparams,
  13386. model.output_norm,
  13387. model.output_norm_b,
  13388. LLM_NORM, cb, -1);
  13389. cb(cur, "result_norm", -1);
  13390. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13391. cb(cur, "result_output", -1);
  13392. ggml_build_forward_expand(gf, cur);
  13393. return gf;
  13394. }
  13395. struct ggml_cgraph * build_chatglm() {
  13396. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13397. const int64_t n_embd_head = hparams.n_embd_head_v;
  13398. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13399. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13400. struct ggml_tensor * cur;
  13401. struct ggml_tensor * inpL;
  13402. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13403. // inp_pos - contains the positions
  13404. struct ggml_tensor * inp_pos = build_inp_pos();
  13405. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13406. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13407. for (int il = 0; il < n_layer; ++il) {
  13408. struct ggml_tensor * inpSA = inpL;
  13409. cur = llm_build_norm(ctx0, inpL, hparams,
  13410. model.layers[il].attn_norm,
  13411. NULL,
  13412. LLM_NORM_RMS, cb, il);
  13413. cb(cur, "attn_norm", il);
  13414. // self-attention
  13415. {
  13416. struct ggml_tensor * Qcur = nullptr;
  13417. struct ggml_tensor * Kcur = nullptr;
  13418. struct ggml_tensor * Vcur = nullptr;
  13419. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13420. cb(cur, "wqkv", il);
  13421. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13422. cb(cur, "bqkv", il);
  13423. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13424. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13425. 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)));
  13426. cb(Qcur, "Qcur", il);
  13427. cb(Kcur, "Kcur", il);
  13428. cb(Vcur, "Vcur", il);
  13429. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13430. Qcur = ggml_rope_ext(
  13431. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13432. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13433. ext_factor, attn_factor, beta_fast, beta_slow
  13434. );
  13435. cb(Qcur, "Qcur_rope", il);
  13436. Kcur = ggml_rope_ext(
  13437. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13438. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13439. ext_factor, attn_factor, beta_fast, beta_slow
  13440. );
  13441. cb(Kcur, "Kcur_rope", il);
  13442. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13443. model.layers[il].wo, NULL,
  13444. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13445. }
  13446. if (il == n_layer - 1) {
  13447. // skip computing output for unused tokens
  13448. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13449. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13450. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13451. }
  13452. // Add the input
  13453. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13454. cb(ffn_inp, "ffn_inp", il);
  13455. // FF
  13456. {
  13457. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13458. model.layers[il].ffn_norm,
  13459. NULL,
  13460. LLM_NORM_RMS, cb, il);
  13461. cb(cur, "ffn_norm", il);
  13462. cur = llm_build_ffn(ctx0, lctx, cur,
  13463. model.layers[il].ffn_up, NULL, NULL,
  13464. NULL, NULL, NULL,
  13465. model.layers[il].ffn_down, NULL, NULL,
  13466. NULL,
  13467. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13468. cb(cur, "ffn_out", il);
  13469. }
  13470. inpL = ggml_add(ctx0, cur, ffn_inp);
  13471. cb(inpL, "l_out", il);
  13472. }
  13473. cur = llm_build_norm(ctx0, inpL, hparams,
  13474. model.output_norm,
  13475. NULL,
  13476. LLM_NORM_RMS, cb, -1);
  13477. cb(cur, "result_norm", -1);
  13478. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13479. cb(cur, "result_output", -1);
  13480. ggml_build_forward_expand(gf, cur);
  13481. return gf;
  13482. }
  13483. struct ggml_cgraph * build_nemotron() {
  13484. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13485. const int64_t n_embd_head = hparams.n_embd_head_v;
  13486. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13487. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13488. struct ggml_tensor * cur;
  13489. struct ggml_tensor * inpL;
  13490. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13491. // inp_pos - contains the positions
  13492. struct ggml_tensor * inp_pos = build_inp_pos();
  13493. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13494. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13495. for (int il = 0; il < n_layer; ++il) {
  13496. struct ggml_tensor * inpSA = inpL;
  13497. // norm
  13498. cur = llm_build_norm(ctx0, inpL, hparams,
  13499. model.layers[il].attn_norm,
  13500. model.layers[il].attn_norm_b,
  13501. LLM_NORM, cb, il);
  13502. cb(cur, "attn_norm", il);
  13503. // self-attention
  13504. {
  13505. // compute Q and K and RoPE them
  13506. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13507. cb(Qcur, "Qcur", il);
  13508. if (model.layers[il].bq) {
  13509. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13510. cb(Qcur, "Qcur", il);
  13511. }
  13512. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13513. cb(Kcur, "Kcur", il);
  13514. if (model.layers[il].bk) {
  13515. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13516. cb(Kcur, "Kcur", il);
  13517. }
  13518. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13519. cb(Vcur, "Vcur", il);
  13520. if (model.layers[il].bv) {
  13521. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13522. cb(Vcur, "Vcur", il);
  13523. }
  13524. Qcur = ggml_rope_ext(
  13525. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13526. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13527. ext_factor, attn_factor, beta_fast, beta_slow
  13528. );
  13529. cb(Qcur, "Qcur", il);
  13530. Kcur = ggml_rope_ext(
  13531. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13532. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13533. ext_factor, attn_factor, beta_fast, beta_slow
  13534. );
  13535. cb(Kcur, "Kcur", il);
  13536. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13537. model.layers[il].wo, model.layers[il].bo,
  13538. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13539. }
  13540. if (il == n_layer - 1) {
  13541. // skip computing output for unused tokens
  13542. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13543. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13544. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13545. }
  13546. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13547. cb(ffn_inp, "ffn_inp", il);
  13548. // feed-forward network
  13549. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13550. model.layers[il].ffn_norm,
  13551. model.layers[il].ffn_norm_b,
  13552. LLM_NORM, cb, il);
  13553. cb(cur, "ffn_norm", il);
  13554. cur = llm_build_ffn(ctx0, lctx, cur,
  13555. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13556. NULL, NULL, NULL,
  13557. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13558. NULL,
  13559. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  13560. cur = ggml_add(ctx0, cur, ffn_inp);
  13561. cb(cur, "ffn_out", il);
  13562. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13563. cb(cur, "l_out", il);
  13564. // input for next layer
  13565. inpL = cur;
  13566. }
  13567. cur = inpL;
  13568. cur = llm_build_norm(ctx0, cur, hparams,
  13569. model.output_norm, model.output_norm_b,
  13570. LLM_NORM, cb, -1);
  13571. cb(cur, "result_norm", -1);
  13572. // lm_head
  13573. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13574. cb(cur, "result_output", -1);
  13575. ggml_build_forward_expand(gf, cur);
  13576. return gf;
  13577. }
  13578. struct ggml_cgraph * build_exaone() {
  13579. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13580. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13581. int32_t n_tokens = this->n_tokens;
  13582. const int64_t n_embd_head = hparams.n_embd_head_v;
  13583. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13584. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13585. struct ggml_tensor * cur;
  13586. struct ggml_tensor * inpL;
  13587. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13588. // inp_pos - contains the positions
  13589. struct ggml_tensor * inp_pos = build_inp_pos();
  13590. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13591. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13592. for (int il = 0; il < n_layer; ++il) {
  13593. struct ggml_tensor * inpSA = inpL;
  13594. // norm
  13595. cur = llm_build_norm(ctx0, inpL, hparams,
  13596. model.layers[il].attn_norm, NULL,
  13597. LLM_NORM_RMS, cb, il);
  13598. cb(cur, "attn_norm", il);
  13599. // self-attention
  13600. {
  13601. // rope freq factors for llama3; may return nullptr for llama2 and other models
  13602. struct ggml_tensor * rope_factors = build_rope_factors(il);
  13603. // compute Q and K and RoPE them
  13604. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13605. cb(Qcur, "Qcur", il);
  13606. if (model.layers[il].bq) {
  13607. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13608. cb(Qcur, "Qcur", il);
  13609. }
  13610. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13611. cb(Kcur, "Kcur", il);
  13612. if (model.layers[il].bk) {
  13613. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13614. cb(Kcur, "Kcur", il);
  13615. }
  13616. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13617. cb(Vcur, "Vcur", il);
  13618. if (model.layers[il].bv) {
  13619. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13620. cb(Vcur, "Vcur", il);
  13621. }
  13622. Qcur = ggml_rope_ext(
  13623. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  13624. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13625. ext_factor, attn_factor, beta_fast, beta_slow
  13626. );
  13627. cb(Qcur, "Qcur", il);
  13628. Kcur = ggml_rope_ext(
  13629. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  13630. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13631. ext_factor, attn_factor, beta_fast, beta_slow
  13632. );
  13633. cb(Kcur, "Kcur", il);
  13634. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13635. model.layers[il].wo, model.layers[il].bo,
  13636. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13637. }
  13638. if (il == n_layer - 1) {
  13639. // skip computing output for unused tokens
  13640. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13641. n_tokens = n_outputs;
  13642. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13643. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13644. }
  13645. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13646. cb(ffn_inp, "ffn_inp", il);
  13647. // feed-forward network
  13648. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13649. model.layers[il].ffn_norm, NULL,
  13650. LLM_NORM_RMS, cb, il);
  13651. cb(cur, "ffn_norm", il);
  13652. cur = llm_build_ffn(ctx0, lctx, cur,
  13653. model.layers[il].ffn_up, NULL, NULL,
  13654. model.layers[il].ffn_gate, NULL, NULL,
  13655. model.layers[il].ffn_down, NULL, NULL,
  13656. NULL,
  13657. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13658. cb(cur, "ffn_out", il);
  13659. cur = ggml_add(ctx0, cur, ffn_inp);
  13660. cb(cur, "ffn_out", il);
  13661. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13662. cb(cur, "l_out", il);
  13663. // input for next layer
  13664. inpL = cur;
  13665. }
  13666. cur = inpL;
  13667. cur = llm_build_norm(ctx0, cur, hparams,
  13668. model.output_norm, NULL,
  13669. LLM_NORM_RMS, cb, -1);
  13670. cb(cur, "result_norm", -1);
  13671. // lm_head
  13672. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13673. cb(cur, "result_output", -1);
  13674. ggml_build_forward_expand(gf, cur);
  13675. return gf;
  13676. }
  13677. ggml_cgraph * build_rwkv6() {
  13678. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13679. // Token shift state dimensions should be 2 * n_emb
  13680. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  13681. const int64_t n_seqs = batch.n_seqs;
  13682. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13683. const int64_t n_tokens = batch.n_tokens;
  13684. GGML_ASSERT(n_seqs != 0);
  13685. GGML_ASSERT(batch.equal_seqs);
  13686. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  13687. struct ggml_tensor * cur;
  13688. struct ggml_tensor * inpL;
  13689. struct ggml_tensor * state_copy = build_inp_s_copy();
  13690. struct ggml_tensor * state_mask = build_inp_s_mask();
  13691. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13692. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  13693. for (int il = 0; il < n_layer; ++il) {
  13694. const llama_layer * layer = &model.layers[il];
  13695. // (ab)using the KV cache to store the states
  13696. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  13697. gf, kv_self.k_l[il], state_copy, state_mask,
  13698. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13699. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  13700. gf, kv_self.v_l[il], state_copy, state_mask,
  13701. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13702. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  13703. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  13704. 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);
  13705. 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));
  13706. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  13707. struct ggml_tensor * x_prev = ggml_concat(
  13708. ctx0,
  13709. att_shift,
  13710. 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),
  13711. 1
  13712. );
  13713. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  13714. ggml_build_forward_expand(gf, cur);
  13715. ggml_build_forward_expand(
  13716. gf,
  13717. ggml_cpy(
  13718. ctx0,
  13719. wkv_states,
  13720. ggml_view_1d(
  13721. ctx0,
  13722. kv_self.v_l[il],
  13723. hparams.n_embd_v_s() * n_seqs,
  13724. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  13725. )
  13726. )
  13727. );
  13728. 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);
  13729. x_prev = ggml_concat(
  13730. ctx0,
  13731. ffn_shift,
  13732. 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),
  13733. 1
  13734. );
  13735. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  13736. ggml_build_forward_expand(gf, cur);
  13737. 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));
  13738. 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));
  13739. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  13740. ggml_build_forward_expand(
  13741. gf,
  13742. ggml_cpy(
  13743. ctx0,
  13744. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  13745. 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]))
  13746. )
  13747. );
  13748. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  13749. cur = ggml_scale(ctx0, cur, 0.5F);
  13750. }
  13751. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13752. cb(cur, "l_out", il);
  13753. // input for next layer
  13754. inpL = cur;
  13755. }
  13756. cur = inpL;
  13757. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13758. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  13759. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13760. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  13761. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13762. cb(cur, "result_output", -1);
  13763. ggml_build_forward_expand(gf, cur);
  13764. return gf;
  13765. }
  13766. // ref: https://github.com/facebookresearch/chameleon
  13767. // based on the original build_llama() function, changes:
  13768. // * qk-norm
  13769. // * swin-norm
  13770. // * removed bias
  13771. // * removed MoE
  13772. struct ggml_cgraph * build_chameleon() {
  13773. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13774. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13775. int32_t n_tokens = this->n_tokens;
  13776. const int64_t n_embd_head = hparams.n_embd_head_v;
  13777. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13778. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13779. struct ggml_tensor * cur;
  13780. struct ggml_tensor * inpL;
  13781. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13782. // inp_pos - contains the positions
  13783. struct ggml_tensor * inp_pos = build_inp_pos();
  13784. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13785. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13786. for (int il = 0; il < n_layer; ++il) {
  13787. struct ggml_tensor * inpSA = inpL;
  13788. // norm
  13789. if (hparams.swin_norm) {
  13790. cur = inpL;
  13791. } else {
  13792. cur = llm_build_norm(ctx0, inpL, hparams,
  13793. model.layers[il].attn_norm, NULL,
  13794. LLM_NORM_RMS, cb, il);
  13795. cb(cur, "attn_norm", il);
  13796. }
  13797. // self-attention
  13798. {
  13799. // compute Q and K and RoPE them
  13800. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13801. cb(Qcur, "Qcur", il);
  13802. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13803. cb(Kcur, "Kcur", il);
  13804. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13805. cb(Vcur, "Vcur", il);
  13806. if (model.layers[il].attn_q_norm) {
  13807. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  13808. ggml_element_size(Qcur) * n_embd_head,
  13809. ggml_element_size(Qcur) * n_embd_head * n_head,
  13810. 0);
  13811. cb(Qcur, "Qcur", il);
  13812. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  13813. model.layers[il].attn_q_norm,
  13814. model.layers[il].attn_q_norm_b,
  13815. LLM_NORM, cb, il);
  13816. cb(Qcur, "Qcur", il);
  13817. }
  13818. if (model.layers[il].attn_k_norm) {
  13819. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  13820. ggml_element_size(Kcur) * n_embd_head,
  13821. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  13822. 0);
  13823. cb(Kcur, "Kcur", il);
  13824. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  13825. model.layers[il].attn_k_norm,
  13826. model.layers[il].attn_k_norm_b,
  13827. LLM_NORM, cb, il);
  13828. cb(Kcur, "Kcur", il);
  13829. }
  13830. Qcur = ggml_rope_ext(
  13831. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13832. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13833. ext_factor, attn_factor, beta_fast, beta_slow
  13834. );
  13835. cb(Qcur, "Qcur", il);
  13836. Kcur = ggml_rope_ext(
  13837. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13838. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13839. ext_factor, attn_factor, beta_fast, beta_slow
  13840. );
  13841. cb(Kcur, "Kcur", il);
  13842. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13843. model.layers[il].wo, nullptr,
  13844. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13845. if (hparams.swin_norm) {
  13846. cur = llm_build_norm(ctx0, cur, hparams,
  13847. model.layers[il].attn_norm, NULL,
  13848. LLM_NORM_RMS, cb, il);
  13849. }
  13850. }
  13851. if (il == n_layer - 1) {
  13852. // skip computing output for unused tokens
  13853. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13854. n_tokens = n_outputs;
  13855. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13856. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13857. }
  13858. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13859. cb(ffn_inp, "ffn_inp", il);
  13860. // feed-forward network
  13861. if (!hparams.swin_norm) {
  13862. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13863. model.layers[il].ffn_norm, NULL,
  13864. LLM_NORM_RMS, cb, il);
  13865. cb(cur, "ffn_norm", il);
  13866. }
  13867. cur = llm_build_ffn(ctx0, lctx, cur,
  13868. model.layers[il].ffn_up, NULL, NULL,
  13869. model.layers[il].ffn_gate, NULL, NULL,
  13870. model.layers[il].ffn_down, NULL, NULL,
  13871. NULL,
  13872. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13873. cb(cur, "ffn_out", il);
  13874. if (hparams.swin_norm) {
  13875. cur = llm_build_norm(ctx0, cur, hparams,
  13876. model.layers[il].ffn_norm, NULL,
  13877. LLM_NORM_RMS, cb, il);
  13878. cb(cur, "ffn_norm", il);
  13879. }
  13880. cur = ggml_add(ctx0, cur, ffn_inp);
  13881. cb(cur, "ffn_out", il);
  13882. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13883. cb(cur, "l_out", il);
  13884. // input for next layer
  13885. inpL = cur;
  13886. }
  13887. cur = inpL;
  13888. cur = llm_build_norm(ctx0, cur, hparams,
  13889. model.output_norm, NULL,
  13890. LLM_NORM_RMS, cb, -1);
  13891. cb(cur, "result_norm", -1);
  13892. // lm_head
  13893. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13894. cb(cur, "result_output_with_img_logits", -1);
  13895. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  13896. // Needs to be removed once image outputs are supported.
  13897. int img_token_end_idx = 8196;
  13898. int img_token_start_idx = 4;
  13899. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  13900. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  13901. // which ensures that text token values are always at least larger than image token values
  13902. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  13903. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  13904. cb(img_logits, "img_logits", -1);
  13905. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  13906. cb(cur, "result_output", -1);
  13907. ggml_build_forward_expand(gf, cur);
  13908. return gf;
  13909. }
  13910. ggml_cgraph * build_solar() {
  13911. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13912. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13913. int32_t n_tokens = this->n_tokens;
  13914. const int64_t n_embd_head = hparams.n_embd_head_v;
  13915. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13916. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13917. struct ggml_tensor * cur;
  13918. struct ggml_tensor * inpL;
  13919. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13920. // inp_pos - contains the positions
  13921. struct ggml_tensor * inp_pos = build_inp_pos();
  13922. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13923. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13924. struct ggml_tensor * bskcn_1;
  13925. struct ggml_tensor * bskcn_2;
  13926. for (int il = 0; il < n_layer; ++il) {
  13927. struct ggml_tensor * inpSA = inpL;
  13928. if (hparams.n_bskcn(0, il)) {
  13929. bskcn_1 = inpSA;
  13930. }
  13931. if (hparams.n_bskcn(1, il)) {
  13932. bskcn_2 = inpSA;
  13933. }
  13934. if (hparams.n_bskcn(2, il)) {
  13935. inpSA = ggml_add(
  13936. ctx0,
  13937. ggml_mul(ctx0, bskcn_1, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  13938. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  13939. }
  13940. if (hparams.n_bskcn(3, il)) {
  13941. inpSA = ggml_add(
  13942. ctx0,
  13943. ggml_mul(ctx0, bskcn_2, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, 0)),
  13944. ggml_mul(ctx0, inpSA, ggml_view_1d(ctx0, model.layers[il].bskcn_tv, 1, ggml_element_size(model.layers[il].bskcn_tv))));
  13945. }
  13946. // norm
  13947. cur = llm_build_norm(ctx0, inpL, hparams,
  13948. model.layers[il].attn_norm, NULL,
  13949. LLM_NORM_RMS, cb, il);
  13950. cb(cur, "attn_norm", il);
  13951. // self-attention
  13952. {
  13953. // rope freq factors for llama3; may return nullptr for llama2 and other models
  13954. struct ggml_tensor * rope_factors = build_rope_factors(il);
  13955. // compute Q and K and RoPE them
  13956. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13957. cb(Qcur, "Qcur", il);
  13958. if (model.layers[il].bq) {
  13959. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13960. cb(Qcur, "Qcur", il);
  13961. }
  13962. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13963. cb(Kcur, "Kcur", il);
  13964. if (model.layers[il].bk) {
  13965. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13966. cb(Kcur, "Kcur", il);
  13967. }
  13968. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13969. cb(Vcur, "Vcur", il);
  13970. if (model.layers[il].bv) {
  13971. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13972. cb(Vcur, "Vcur", il);
  13973. }
  13974. Qcur = ggml_rope_ext(
  13975. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  13976. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13977. ext_factor, attn_factor, beta_fast, beta_slow
  13978. );
  13979. cb(Qcur, "Qcur", il);
  13980. Kcur = ggml_rope_ext(
  13981. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  13982. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13983. ext_factor, attn_factor, beta_fast, beta_slow
  13984. );
  13985. cb(Kcur, "Kcur", il);
  13986. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13987. model.layers[il].wo, model.layers[il].bo,
  13988. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13989. }
  13990. if (il == n_layer - 1) {
  13991. // skip computing output for unused tokens
  13992. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13993. n_tokens = n_outputs;
  13994. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13995. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13996. }
  13997. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13998. cb(ffn_inp, "ffn_inp", il);
  13999. // feed-forward network
  14000. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  14001. model.layers[il].ffn_norm, NULL,
  14002. LLM_NORM_RMS, cb, il);
  14003. cb(cur, "ffn_norm", il);
  14004. cur = llm_build_ffn(ctx0, lctx, cur,
  14005. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  14006. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  14007. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  14008. NULL,
  14009. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  14010. cb(cur, "ffn_out", il);
  14011. cur = ggml_add(ctx0, cur, ffn_inp);
  14012. cb(cur, "ffn_out", il);
  14013. cur = lctx.cvec.apply_to(ctx0, cur, il);
  14014. cb(cur, "l_out", il);
  14015. // input for next layer
  14016. inpL = cur;
  14017. }
  14018. cur = inpL;
  14019. cur = llm_build_norm(ctx0, cur, hparams,
  14020. model.output_norm, NULL,
  14021. LLM_NORM_RMS, cb, -1);
  14022. cb(cur, "result_norm", -1);
  14023. // lm_head
  14024. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  14025. cb(cur, "result_output", -1);
  14026. ggml_build_forward_expand(gf, cur);
  14027. return gf;
  14028. }
  14029. };
  14030. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  14031. llama_ubatch dummy = {};
  14032. dummy.equal_seqs = true;
  14033. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14034. struct llm_build_context llm(lctx, dummy, cb, false);
  14035. llm.init();
  14036. struct ggml_cgraph * result = llm.build_defrag(ids);
  14037. llm.free();
  14038. return result;
  14039. }
  14040. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  14041. llama_ubatch dummy = {};
  14042. dummy.equal_seqs = true;
  14043. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  14044. struct llm_build_context llm(lctx, dummy, cb, false);
  14045. llm.init();
  14046. struct ggml_cgraph * result = llm.build_k_shift();
  14047. llm.free();
  14048. return result;
  14049. }
  14050. static struct ggml_cgraph * llama_build_graph(
  14051. llama_context & lctx,
  14052. const llama_ubatch & batch,
  14053. bool worst_case) {
  14054. const auto & model = lctx.model;
  14055. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  14056. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  14057. if (il >= 0) {
  14058. ggml_format_name(cur, "%s-%d", name, il);
  14059. } else {
  14060. ggml_set_name(cur, name);
  14061. }
  14062. if (!lctx.cparams.offload_kqv) {
  14063. if (strcmp(name, "kqv_merged_cont") == 0) {
  14064. // all nodes between the KV store and the attention output are run on the CPU
  14065. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  14066. }
  14067. }
  14068. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  14069. // FIXME: fix in ggml_backend_sched
  14070. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  14071. if (batch.n_tokens < 32 || full_offload) {
  14072. if (il != -1 && strcmp(name, "norm") == 0) {
  14073. for (auto * backend : lctx.backends) {
  14074. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  14075. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  14076. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  14077. break;
  14078. }
  14079. }
  14080. }
  14081. }
  14082. };
  14083. struct ggml_cgraph * result = NULL;
  14084. struct llm_build_context llm(lctx, batch, cb, worst_case);
  14085. llm.init();
  14086. switch (model.arch) {
  14087. case LLM_ARCH_LLAMA:
  14088. case LLM_ARCH_GRANITE:
  14089. case LLM_ARCH_GRANITE_MOE:
  14090. {
  14091. result = llm.build_llama();
  14092. } break;
  14093. case LLM_ARCH_MLLAMA:
  14094. {
  14095. result = llm.build_mllama();
  14096. } break;
  14097. case LLM_ARCH_BAICHUAN:
  14098. {
  14099. result = llm.build_baichuan();
  14100. } break;
  14101. case LLM_ARCH_FALCON:
  14102. {
  14103. result = llm.build_falcon();
  14104. } break;
  14105. case LLM_ARCH_GROK:
  14106. {
  14107. result = llm.build_grok();
  14108. } break;
  14109. case LLM_ARCH_STARCODER:
  14110. {
  14111. result = llm.build_starcoder();
  14112. } break;
  14113. case LLM_ARCH_REFACT:
  14114. {
  14115. result = llm.build_refact();
  14116. } break;
  14117. case LLM_ARCH_BERT:
  14118. case LLM_ARCH_JINA_BERT_V2:
  14119. case LLM_ARCH_NOMIC_BERT:
  14120. {
  14121. result = llm.build_bert();
  14122. } break;
  14123. case LLM_ARCH_BLOOM:
  14124. {
  14125. result = llm.build_bloom();
  14126. } break;
  14127. case LLM_ARCH_MPT:
  14128. {
  14129. result = llm.build_mpt();
  14130. } break;
  14131. case LLM_ARCH_STABLELM:
  14132. {
  14133. result = llm.build_stablelm();
  14134. } break;
  14135. case LLM_ARCH_QWEN:
  14136. {
  14137. result = llm.build_qwen();
  14138. } break;
  14139. case LLM_ARCH_QWEN2:
  14140. {
  14141. result = llm.build_qwen2();
  14142. } break;
  14143. case LLM_ARCH_QWEN2MOE:
  14144. {
  14145. result = llm.build_qwen2moe();
  14146. } break;
  14147. case LLM_ARCH_PHI2:
  14148. {
  14149. result = llm.build_phi2();
  14150. } break;
  14151. case LLM_ARCH_PHI3:
  14152. {
  14153. result = llm.build_phi3();
  14154. } break;
  14155. case LLM_ARCH_PLAMO:
  14156. {
  14157. result = llm.build_plamo();
  14158. } break;
  14159. case LLM_ARCH_GPT2:
  14160. {
  14161. result = llm.build_gpt2();
  14162. } break;
  14163. case LLM_ARCH_CODESHELL:
  14164. {
  14165. result = llm.build_codeshell();
  14166. } break;
  14167. case LLM_ARCH_ORION:
  14168. {
  14169. result = llm.build_orion();
  14170. } break;
  14171. case LLM_ARCH_INTERNLM2:
  14172. {
  14173. result = llm.build_internlm2();
  14174. } break;
  14175. case LLM_ARCH_MINICPM:
  14176. {
  14177. result = llm.build_minicpm();
  14178. } break;
  14179. case LLM_ARCH_MINICPM3:
  14180. {
  14181. result = llm.build_minicpm3();
  14182. } break;
  14183. case LLM_ARCH_GEMMA:
  14184. {
  14185. result = llm.build_gemma();
  14186. } break;
  14187. case LLM_ARCH_GEMMA2:
  14188. {
  14189. result = llm.build_gemma2();
  14190. } break;
  14191. case LLM_ARCH_STARCODER2:
  14192. {
  14193. result = llm.build_starcoder2();
  14194. } break;
  14195. case LLM_ARCH_MAMBA:
  14196. {
  14197. result = llm.build_mamba();
  14198. } break;
  14199. case LLM_ARCH_XVERSE:
  14200. {
  14201. result = llm.build_xverse();
  14202. } break;
  14203. case LLM_ARCH_COMMAND_R:
  14204. {
  14205. result = llm.build_command_r();
  14206. } break;
  14207. case LLM_ARCH_DBRX:
  14208. {
  14209. result = llm.build_dbrx();
  14210. } break;
  14211. case LLM_ARCH_OLMO:
  14212. {
  14213. result = llm.build_olmo();
  14214. } break;
  14215. case LLM_ARCH_OLMOE:
  14216. {
  14217. result = llm.build_olmoe();
  14218. } break;
  14219. case LLM_ARCH_OPENELM:
  14220. {
  14221. result = llm.build_openelm();
  14222. } break;
  14223. case LLM_ARCH_GPTNEOX:
  14224. {
  14225. result = llm.build_gptneox();
  14226. } break;
  14227. case LLM_ARCH_ARCTIC:
  14228. {
  14229. result = llm.build_arctic();
  14230. } break;
  14231. case LLM_ARCH_DEEPSEEK2:
  14232. {
  14233. result = llm.build_deepseek2();
  14234. } break;
  14235. case LLM_ARCH_CHATGLM:
  14236. {
  14237. result = llm.build_chatglm();
  14238. } break;
  14239. case LLM_ARCH_BITNET:
  14240. {
  14241. result = llm.build_bitnet();
  14242. } break;
  14243. case LLM_ARCH_T5:
  14244. {
  14245. if (lctx.is_encoding) {
  14246. result = llm.build_t5_encoder();
  14247. } else {
  14248. result = llm.build_t5_decoder();
  14249. }
  14250. } break;
  14251. case LLM_ARCH_T5ENCODER:
  14252. {
  14253. result = llm.build_t5_encoder();
  14254. } break;
  14255. case LLM_ARCH_JAIS:
  14256. {
  14257. result = llm.build_jais();
  14258. } break;
  14259. case LLM_ARCH_NEMOTRON:
  14260. {
  14261. result = llm.build_nemotron();
  14262. } break;
  14263. case LLM_ARCH_EXAONE:
  14264. {
  14265. result = llm.build_exaone();
  14266. } break;
  14267. case LLM_ARCH_RWKV6:
  14268. {
  14269. result = llm.build_rwkv6();
  14270. } break;
  14271. case LLM_ARCH_CHAMELEON:
  14272. {
  14273. result = llm.build_chameleon();
  14274. } break;
  14275. case LLM_ARCH_SOLAR:
  14276. {
  14277. result = llm.build_solar();
  14278. } break;
  14279. default:
  14280. GGML_ABORT("fatal error");
  14281. }
  14282. // add on pooling layer
  14283. if (lctx.cparams.embeddings) {
  14284. result = llm.append_pooling(result);
  14285. }
  14286. llm.free();
  14287. return result;
  14288. }
  14289. static void llama_set_k_shift(llama_context & lctx) {
  14290. const int64_t kv_size = lctx.kv_self.size;
  14291. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  14292. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  14293. for (int i = 0; i < kv_size; ++i) {
  14294. data[i] = lctx.kv_self.cells[i].delta;
  14295. }
  14296. }
  14297. static void llama_set_s_copy(llama_context & lctx) {
  14298. const int64_t kv_size = lctx.kv_self.size;
  14299. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14300. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14301. for (int i = 0; i < kv_size; ++i) {
  14302. data[i] = lctx.kv_self.cells[i].src;
  14303. }
  14304. }
  14305. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  14306. // TODO move to hparams if a T5 variant appears that uses a different value
  14307. const int64_t max_distance = 128;
  14308. if (bidirectional) {
  14309. n_buckets >>= 1;
  14310. }
  14311. const int64_t max_exact = n_buckets >> 1;
  14312. int32_t relative_position = x - y;
  14313. int32_t relative_bucket = 0;
  14314. if (bidirectional) {
  14315. relative_bucket += (relative_position > 0) * n_buckets;
  14316. relative_position = abs(relative_position);
  14317. } else {
  14318. relative_position = -std::min<int32_t>(relative_position, 0);
  14319. }
  14320. 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));
  14321. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  14322. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  14323. return relative_bucket;
  14324. }
  14325. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & batch) {
  14326. //
  14327. // set input data
  14328. //
  14329. const auto & hparams = lctx.model.hparams;
  14330. const auto & cparams = lctx.cparams;
  14331. const auto & kv_self = lctx.kv_self;
  14332. if (batch.token) {
  14333. const int64_t n_tokens = batch.n_tokens;
  14334. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  14335. }
  14336. if (batch.embd) {
  14337. if (lctx.inp_cross_attn_state && lctx.inp_cross_attn_state->buffer) {
  14338. ggml_backend_tensor_set(lctx.inp_cross_attn_state, batch.embd, 0, ggml_nbytes(lctx.inp_cross_attn_state));
  14339. // zero out inp_embd since it's not used
  14340. float * inp_embd_data = (float *)lctx.inp_embd->data;
  14341. for (int i = 0; i < ggml_nelements(lctx.inp_embd); ++i) {
  14342. inp_embd_data[i] = 0.0f;
  14343. }
  14344. } else {
  14345. const int64_t n_embd = hparams.n_embd;
  14346. const int64_t n_tokens = batch.n_tokens;
  14347. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  14348. }
  14349. }
  14350. if (batch.pos && lctx.inp_pos) {
  14351. const int64_t n_tokens = batch.n_tokens;
  14352. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  14353. }
  14354. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  14355. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  14356. const int64_t n_tokens = batch.n_tokens;
  14357. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  14358. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  14359. if (lctx.n_outputs == n_tokens) {
  14360. for (int i = 0; i < n_tokens; ++i) {
  14361. data[i] = i;
  14362. }
  14363. } else if (batch.output) {
  14364. int32_t n_outputs = 0;
  14365. for (int i = 0; i < n_tokens; ++i) {
  14366. if (batch.output[i]) {
  14367. data[n_outputs++] = i;
  14368. }
  14369. }
  14370. // the graph needs to have been passed the correct number of outputs
  14371. GGML_ASSERT(lctx.n_outputs == n_outputs);
  14372. } else if (lctx.n_outputs == 1) {
  14373. // only keep last output
  14374. data[0] = n_tokens - 1;
  14375. } else {
  14376. GGML_ASSERT(lctx.n_outputs == 0);
  14377. }
  14378. }
  14379. GGML_ASSERT(
  14380. // (!a || b) is a logical implication (a -> b)
  14381. // !hparams.causal_attn -> !cparams.causal_attn
  14382. (hparams.causal_attn || !cparams.causal_attn) &&
  14383. "causal attention is not supported by this model"
  14384. );
  14385. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  14386. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  14387. if (cparams.causal_attn && !lctx.is_encoding) {
  14388. const int64_t n_kv = kv_self.n;
  14389. const int64_t n_tokens = batch.n_tokens;
  14390. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14391. const int64_t n_seqs = batch.n_seqs;
  14392. float * data = nullptr;
  14393. float * data_swa = nullptr;
  14394. if (lctx.inp_KQ_mask) {
  14395. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14396. data = (float *) lctx.inp_KQ_mask->data;
  14397. }
  14398. if (lctx.inp_KQ_mask_swa) {
  14399. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  14400. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  14401. }
  14402. // For causal attention, use only the previous KV cells
  14403. // of the correct sequence for each token of the batch.
  14404. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  14405. for (int h = 0; h < 1; ++h) {
  14406. for (int s = 0; s < n_seqs; ++s) {
  14407. const llama_seq_id seq_id = batch.seq_id[s][0];
  14408. for (int j = 0; j < n_seq_tokens; ++j) {
  14409. const llama_pos pos = batch.pos[s*n_seq_tokens + j];
  14410. for (int i = 0; i < n_kv; ++i) {
  14411. float f;
  14412. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  14413. f = -INFINITY;
  14414. } else {
  14415. if (hparams.use_alibi) {
  14416. f = -std::abs(kv_self.cells[i].pos - pos);
  14417. } else {
  14418. f = 0.0f;
  14419. }
  14420. }
  14421. if (data) {
  14422. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14423. }
  14424. // may need to cut off old tokens for sliding window
  14425. if (data_swa) {
  14426. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  14427. f = -INFINITY;
  14428. }
  14429. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  14430. }
  14431. }
  14432. }
  14433. }
  14434. if (data) {
  14435. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14436. for (int j = 0; j < n_kv; ++j) {
  14437. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14438. }
  14439. }
  14440. }
  14441. if (data_swa) {
  14442. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14443. for (int j = 0; j < n_kv; ++j) {
  14444. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  14445. }
  14446. }
  14447. }
  14448. }
  14449. } else {
  14450. const int64_t n_tokens = batch.n_tokens;
  14451. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14452. const int64_t n_seqs = batch.n_seqs;
  14453. // when using kv cache, the mask needs to match the kv cache size
  14454. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  14455. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  14456. float * data = (float *) lctx.inp_KQ_mask->data;
  14457. for (int h = 0; h < 1; ++h) {
  14458. for (int s1 = 0; s1 < n_seqs; ++s1) {
  14459. const llama_seq_id seq_id = batch.seq_id[s1][0];
  14460. for (int j = 0; j < n_seq_tokens; ++j) {
  14461. const int32_t tj = s1*n_seq_tokens + j;
  14462. for (int s0 = 0; s0 < n_seqs; ++s0) {
  14463. for (int i = 0; i < n_seq_tokens; ++i) {
  14464. const int32_t ti = s0*n_seq_tokens + i;
  14465. float f = -INFINITY;
  14466. for (int s = 0; s < batch.n_seq_id[s0]; ++s) {
  14467. if (batch.seq_id[s0][s] == seq_id) {
  14468. if (hparams.use_alibi) {
  14469. f = -std::abs(batch.pos[ti] - batch.pos[tj]);
  14470. } else {
  14471. f = 0.0f;
  14472. }
  14473. break;
  14474. }
  14475. }
  14476. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  14477. }
  14478. }
  14479. for (int i = n_tokens; i < n_stride; ++i) {
  14480. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  14481. }
  14482. }
  14483. }
  14484. }
  14485. }
  14486. }
  14487. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  14488. const int64_t n_tokens = batch.n_tokens;
  14489. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14490. const int64_t n_seqs = batch.n_seqs;
  14491. GGML_ASSERT(lctx.inp_mean);
  14492. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  14493. float * data = (float *) lctx.inp_mean->data;
  14494. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  14495. std::vector<uint64_t> sum(n_tokens, 0);
  14496. for (int s = 0; s < n_seqs; ++s) {
  14497. const llama_seq_id seq_id = batch.seq_id[s][0];
  14498. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14499. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  14500. sum[seq_id] += batch.n_seq_tokens;
  14501. }
  14502. std::vector<float> div(n_tokens, 0.0f);
  14503. for (int i = 0; i < n_tokens; ++i) {
  14504. const uint64_t s = sum[i];
  14505. if (s > 0) {
  14506. div[i] = 1.0f/float(s);
  14507. }
  14508. }
  14509. for (int s = 0; s < n_seqs; ++s) {
  14510. const llama_seq_id seq_id = batch.seq_id[s][0];
  14511. for (int i = 0; i < n_seq_tokens; ++i) {
  14512. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  14513. }
  14514. }
  14515. }
  14516. if (cparams.embeddings && (
  14517. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  14518. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  14519. const int64_t n_tokens = batch.n_tokens;
  14520. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14521. const int64_t n_seqs = batch.n_seqs;
  14522. GGML_ASSERT(lctx.inp_cls);
  14523. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14524. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14525. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14526. for (int s = 0; s < n_seqs; ++s) {
  14527. const llama_seq_id seq_id = batch.seq_id[s][0];
  14528. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14529. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  14530. for (int i = 0; i < n_seq_tokens; ++i) {
  14531. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14532. if (pos == 0) {
  14533. data[seq_id] = s*n_seq_tokens + i;
  14534. }
  14535. }
  14536. }
  14537. }
  14538. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  14539. const int64_t n_tokens = batch.n_tokens;
  14540. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14541. const int64_t n_seqs = batch.n_seqs;
  14542. GGML_ASSERT(lctx.inp_cls);
  14543. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14544. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14545. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14546. std::vector<int> last_pos(n_tokens, -1);
  14547. std::vector<int> last_row(n_tokens, -1);
  14548. for (int s = 0; s < n_seqs; ++s) {
  14549. const llama_seq_id seq_id = batch.seq_id[s][0];
  14550. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14551. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  14552. for (int i = 0; i < n_seq_tokens; ++i) {
  14553. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14554. if (pos >= last_pos[seq_id]) {
  14555. last_pos[seq_id] = pos;
  14556. last_row[seq_id] = s*n_seq_tokens + i;
  14557. }
  14558. }
  14559. }
  14560. for (int i = 0; i < n_tokens; ++i) {
  14561. if (last_row[i] >= 0) {
  14562. data[i] = last_row[i];
  14563. }
  14564. }
  14565. }
  14566. if (kv_self.recurrent) {
  14567. const int64_t n_kv = kv_self.n;
  14568. if (lctx.inp_s_mask) {
  14569. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  14570. float * data = (float *) lctx.inp_s_mask->data;
  14571. // clear unused states
  14572. for (int i = 0; i < n_kv; ++i) {
  14573. const uint32_t cell_id = i + kv_self.head;
  14574. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14575. data[i] = (float) (kv_cell.src >= 0);
  14576. // only clear once
  14577. if (kv_cell.src < 0) {
  14578. kv_cell.src = cell_id;
  14579. }
  14580. }
  14581. }
  14582. if (lctx.inp_s_copy) {
  14583. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14584. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14585. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  14586. for (uint32_t i = 0; i < n_kv; ++i) {
  14587. const uint32_t cell_id = i + kv_self.head;
  14588. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14589. // prevent out-of-bound sources
  14590. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  14591. kv_cell.src = cell_id;
  14592. }
  14593. data[i] = kv_cell.src;
  14594. // ensure copy only happens once
  14595. if (kv_cell.src != (int32_t) cell_id) {
  14596. kv_cell.src = cell_id;
  14597. }
  14598. }
  14599. }
  14600. }
  14601. if (lctx.inp_pos_bucket) {
  14602. const int64_t n_tokens = batch.n_tokens;
  14603. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  14604. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14605. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  14606. if (!lctx.is_encoding) {
  14607. const int64_t n_kv = kv_self.n;
  14608. for (int h = 0; h < 1; ++h) {
  14609. for (int j = 0; j < n_tokens; ++j) {
  14610. for (int i = 0; i < n_kv; ++i) {
  14611. 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);
  14612. }
  14613. }
  14614. }
  14615. } else {
  14616. for (int h = 0; h < 1; ++h) {
  14617. for (int j = 0; j < n_tokens; ++j) {
  14618. for (int i = 0; i < n_tokens; ++i) {
  14619. 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);
  14620. }
  14621. }
  14622. }
  14623. }
  14624. }
  14625. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  14626. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  14627. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  14628. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  14629. }
  14630. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  14631. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  14632. const int64_t n_tokens = batch.n_tokens;
  14633. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  14634. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14635. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  14636. for (int h = 0; h < 1; ++h) {
  14637. for (int j = 0; j < n_tokens; ++j) {
  14638. for (int i = 0; i < n_output_enc; ++i) {
  14639. float f = -INFINITY;
  14640. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  14641. const llama_seq_id seq_id = batch.seq_id[j][s];
  14642. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  14643. f = 0.0f;
  14644. }
  14645. }
  14646. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  14647. }
  14648. }
  14649. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14650. for (int j = 0; j < n_output_enc; ++j) {
  14651. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  14652. }
  14653. }
  14654. }
  14655. }
  14656. }
  14657. // Make sure enough space is available for outputs.
  14658. // Returns max number of outputs for which space was reserved.
  14659. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  14660. const auto & cparams = lctx.cparams;
  14661. const auto & hparams = lctx.model.hparams;
  14662. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  14663. const auto n_batch = cparams.n_batch;
  14664. const auto n_vocab = hparams.n_vocab;
  14665. const auto n_embd = hparams.n_embd;
  14666. // TODO: use a per-batch flag for logits presence instead
  14667. const bool has_logits = cparams.causal_attn;
  14668. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  14669. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  14670. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  14671. if (lctx.output_ids.empty()) {
  14672. // init, never resized afterwards
  14673. lctx.output_ids.resize(n_batch);
  14674. }
  14675. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  14676. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  14677. // alloc only when more than the current capacity is required
  14678. // TODO: also consider shrinking the buffer
  14679. if (!lctx.buf_output || prev_size < new_size) {
  14680. if (lctx.buf_output) {
  14681. #ifndef NDEBUG
  14682. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  14683. 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);
  14684. #endif
  14685. ggml_backend_buffer_free(lctx.buf_output);
  14686. lctx.buf_output = nullptr;
  14687. lctx.logits = nullptr;
  14688. lctx.embd = nullptr;
  14689. }
  14690. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  14691. if (lctx.buf_output == nullptr) {
  14692. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  14693. return 0;
  14694. }
  14695. }
  14696. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  14697. lctx.logits = has_logits ? output_base : nullptr;
  14698. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  14699. lctx.output_size = n_outputs_max;
  14700. lctx.logits_size = logits_size;
  14701. lctx.embd_size = embd_size;
  14702. // set all ids as invalid (negative)
  14703. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  14704. ggml_backend_buffer_clear(lctx.buf_output, 0);
  14705. lctx.n_outputs = 0;
  14706. return n_outputs_max;
  14707. }
  14708. // make the outputs have the same order they had in the user-provided batch
  14709. static void llama_output_reorder(struct llama_context * ctx) {
  14710. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  14711. if (!out_ids.empty()) {
  14712. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  14713. uint32_t n_embd = ctx->model.hparams.n_embd;
  14714. int32_t n_outputs = ctx->n_outputs;
  14715. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  14716. // TODO: is there something more efficient which also minimizes swaps?
  14717. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  14718. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  14719. int32_t j_min = i;
  14720. for (int32_t j = i + 1; j < n_outputs; ++j) {
  14721. if (out_ids[j] < out_ids[j_min]) {
  14722. j_min = j;
  14723. }
  14724. }
  14725. if (j_min == i) { continue; }
  14726. std::swap(out_ids[i], out_ids[j_min]);
  14727. if (ctx->logits_size > 0) {
  14728. for (uint32_t k = 0; k < n_vocab; k++) {
  14729. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  14730. }
  14731. }
  14732. if (ctx->embd_size > 0) {
  14733. for (uint32_t k = 0; k < n_embd; k++) {
  14734. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  14735. }
  14736. }
  14737. }
  14738. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  14739. for (int32_t i = 0; i < n_outputs; ++i) {
  14740. ctx->output_ids[out_ids[i]] = i;
  14741. }
  14742. out_ids.clear();
  14743. }
  14744. }
  14745. static void llama_graph_compute(
  14746. llama_context & lctx,
  14747. ggml_cgraph * gf,
  14748. int n_threads,
  14749. ggml_threadpool * threadpool) {
  14750. if (lctx.backend_cpu != nullptr) {
  14751. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  14752. ggml_backend_cpu_set_threadpool(lctx.backend_cpu, threadpool);
  14753. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  14754. }
  14755. #ifdef GGML_USE_BLAS
  14756. if (lctx.backend_blas != nullptr) {
  14757. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  14758. }
  14759. #endif
  14760. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  14761. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  14762. }
  14763. // decode a batch of tokens by evaluating the transformer
  14764. //
  14765. // - lctx: llama context
  14766. // - batch: batch to evaluate
  14767. //
  14768. // return 0 on success
  14769. // return positive int on warning
  14770. // return negative int on error
  14771. //
  14772. static int llama_decode_internal(
  14773. llama_context & lctx,
  14774. llama_batch batch_all) { // TODO: rename back to batch
  14775. lctx.is_encoding = false;
  14776. const uint32_t n_tokens_all = batch_all.n_tokens;
  14777. if (n_tokens_all == 0) {
  14778. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  14779. return -1;
  14780. }
  14781. const auto & model = lctx.model;
  14782. const auto & hparams = model.hparams;
  14783. const auto & cparams = lctx.cparams;
  14784. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  14785. if (batch_all.token) {
  14786. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14787. if (batch_all.token[i] < 0 || (uint32_t)batch_all.token[i] >= model.vocab.n_vocab) {
  14788. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch_all.token[i]);
  14789. return -1;
  14790. }
  14791. }
  14792. }
  14793. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  14794. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  14795. if (lctx.t_compute_start_us == 0) {
  14796. lctx.t_compute_start_us = ggml_time_us();
  14797. }
  14798. lctx.n_queued_tokens += n_tokens_all;
  14799. auto & kv_self = lctx.kv_self;
  14800. const int64_t n_embd = hparams.n_embd;
  14801. const int64_t n_vocab = hparams.n_vocab;
  14802. uint32_t n_outputs = 0;
  14803. uint32_t n_outputs_prev = 0;
  14804. const auto n_ubatch = cparams.n_ubatch;
  14805. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  14806. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  14807. lctx.embd_seq.clear();
  14808. // count outputs
  14809. if (batch_all.logits && !embd_pooled) {
  14810. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14811. n_outputs += batch_all.logits[i] != 0;
  14812. }
  14813. } else if (lctx.logits_all || embd_pooled) {
  14814. n_outputs = n_tokens_all;
  14815. } else {
  14816. // keep last output only
  14817. n_outputs = 1;
  14818. }
  14819. lctx.sbatch.from_batch(batch_all, batch_all.n_embd,
  14820. /* simple_split */ !kv_self.recurrent,
  14821. /* logits_all */ n_outputs == n_tokens_all);
  14822. // reserve output buffer
  14823. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  14824. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  14825. return -2;
  14826. };
  14827. while (lctx.sbatch.n_tokens > 0) {
  14828. llama_ubatch ubatch;
  14829. if (kv_self.recurrent) {
  14830. if (embd_pooled) {
  14831. // Pooled embeddings cannot be split across ubatches (yet)
  14832. ubatch = lctx.sbatch.split_seq(n_ubatch);
  14833. } else {
  14834. // recurrent model architectures are easier to implement
  14835. // with equal-length sequences
  14836. ubatch = lctx.sbatch.split_equal(n_ubatch);
  14837. }
  14838. } else {
  14839. ubatch = lctx.sbatch.split_simple(n_ubatch);
  14840. }
  14841. const uint32_t n_tokens = ubatch.n_tokens;
  14842. // count the outputs in this u_batch
  14843. {
  14844. int32_t n_outputs_new = 0;
  14845. if (n_outputs == n_tokens_all) {
  14846. n_outputs_new = n_tokens;
  14847. } else {
  14848. GGML_ASSERT(ubatch.output);
  14849. for (uint32_t i = 0; i < n_tokens; i++) {
  14850. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  14851. }
  14852. }
  14853. // needs to happen before the graph is built
  14854. lctx.n_outputs = n_outputs_new;
  14855. }
  14856. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  14857. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  14858. GGML_ASSERT(n_threads > 0);
  14859. // non-causal masks do not use the KV cache
  14860. if (hparams.causal_attn) {
  14861. llama_kv_cache_update(&lctx);
  14862. // if we have enough unused cells before the current head ->
  14863. // better to start searching from the beginning of the cache, hoping to fill it
  14864. if (kv_self.head > kv_self.used + 2*n_tokens) {
  14865. kv_self.head = 0;
  14866. }
  14867. if (!llama_kv_cache_find_slot(kv_self, ubatch)) {
  14868. return 1;
  14869. }
  14870. if (!kv_self.recurrent) {
  14871. // a heuristic, to avoid attending the full cache if it is not yet utilized
  14872. // after enough generations, the benefit from this heuristic disappears
  14873. // if we start defragmenting the cache, the benefit from this will be more important
  14874. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  14875. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  14876. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  14877. }
  14878. }
  14879. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  14880. ggml_backend_sched_reset(lctx.sched);
  14881. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  14882. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  14883. // the output is always the last tensor in the graph
  14884. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  14885. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  14886. if (lctx.n_outputs == 0) {
  14887. // no output
  14888. res = nullptr;
  14889. embd = nullptr;
  14890. }
  14891. if (cparams.embeddings) {
  14892. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  14893. embd = ggml_graph_node(gf, i);
  14894. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  14895. break;
  14896. }
  14897. }
  14898. } else {
  14899. embd = nullptr; // do not extract embeddings when not needed
  14900. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  14901. }
  14902. if (!cparams.causal_attn) {
  14903. res = nullptr; // do not extract logits when not needed
  14904. }
  14905. // 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);
  14906. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  14907. llama_set_inputs(lctx, ubatch);
  14908. llama_graph_compute(lctx, gf, n_threads, threadpool);
  14909. // update the kv ring buffer
  14910. {
  14911. kv_self.head += n_tokens;
  14912. // Ensure kv cache head points to a valid index.
  14913. if (kv_self.head >= kv_self.size) {
  14914. kv_self.head = 0;
  14915. }
  14916. }
  14917. // plot the computation graph in dot format (for debugging purposes)
  14918. //if (n_past%100 == 0) {
  14919. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  14920. //}
  14921. // extract logits
  14922. if (res) {
  14923. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  14924. GGML_ASSERT(backend_res != nullptr);
  14925. GGML_ASSERT(lctx.logits != nullptr);
  14926. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  14927. const int32_t n_outputs_new = lctx.n_outputs;
  14928. if (n_outputs_new) {
  14929. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14930. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  14931. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  14932. }
  14933. }
  14934. // extract embeddings
  14935. if (embd) {
  14936. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  14937. GGML_ASSERT(backend_embd != nullptr);
  14938. switch (cparams.pooling_type) {
  14939. case LLAMA_POOLING_TYPE_NONE:
  14940. {
  14941. // extract token embeddings
  14942. GGML_ASSERT(lctx.embd != nullptr);
  14943. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  14944. const int32_t n_outputs_new = lctx.n_outputs;
  14945. if (n_outputs_new) {
  14946. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14947. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  14948. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  14949. }
  14950. } break;
  14951. case LLAMA_POOLING_TYPE_MEAN:
  14952. case LLAMA_POOLING_TYPE_CLS:
  14953. case LLAMA_POOLING_TYPE_LAST:
  14954. {
  14955. // extract sequence embeddings (cleared before processing each batch)
  14956. auto & embd_seq_out = lctx.embd_seq;
  14957. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14958. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14959. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14960. continue;
  14961. }
  14962. embd_seq_out[seq_id].resize(n_embd);
  14963. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  14964. }
  14965. } break;
  14966. case LLAMA_POOLING_TYPE_RANK:
  14967. {
  14968. // extract the rerank score - a single float per sequence
  14969. auto & embd_seq_out = lctx.embd_seq;
  14970. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14971. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14972. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14973. continue;
  14974. }
  14975. embd_seq_out[seq_id].resize(1);
  14976. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  14977. }
  14978. } break;
  14979. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  14980. {
  14981. GGML_ABORT("unknown pooling type");
  14982. }
  14983. }
  14984. }
  14985. n_outputs_prev += lctx.n_outputs;
  14986. }
  14987. // set output mappings
  14988. {
  14989. bool sorted_output = true;
  14990. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  14991. for (size_t i = 0; i < n_outputs; ++i) {
  14992. size_t out_id = lctx.sbatch.out_ids[i];
  14993. lctx.output_ids[out_id] = i;
  14994. if (out_id != i) {
  14995. sorted_output = false;
  14996. }
  14997. }
  14998. if (sorted_output) {
  14999. lctx.sbatch.out_ids.clear();
  15000. }
  15001. }
  15002. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  15003. lctx.n_outputs = n_outputs;
  15004. // wait for the computation to finish (automatically done when obtaining the model output)
  15005. //llama_synchronize(&lctx);
  15006. // decide if we need to defrag the kv cache
  15007. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  15008. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  15009. // queue defragmentation for next llama_kv_cache_update
  15010. if (fragmentation > cparams.defrag_thold) {
  15011. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  15012. llama_kv_cache_defrag(kv_self);
  15013. }
  15014. }
  15015. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15016. // overlap with device computation.
  15017. ggml_backend_sched_reset(lctx.sched);
  15018. return 0;
  15019. }
  15020. // encode a batch of tokens by evaluating the encoder part of the transformer
  15021. //
  15022. // - lctx: llama context
  15023. // - batch: batch to evaluate
  15024. //
  15025. // return 0 on success
  15026. // return positive int on warning
  15027. // return negative int on error
  15028. //
  15029. static int llama_encode_internal(
  15030. llama_context & lctx,
  15031. llama_batch batch) {
  15032. lctx.is_encoding = true;
  15033. const uint32_t n_tokens = batch.n_tokens;
  15034. if (n_tokens == 0) {
  15035. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  15036. return -1;
  15037. }
  15038. const auto & model = lctx.model;
  15039. const auto & hparams = model.hparams;
  15040. const auto & cparams = lctx.cparams;
  15041. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  15042. if (batch.token) {
  15043. for (uint32_t i = 0; i < n_tokens; ++i) {
  15044. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  15045. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  15046. return -1;
  15047. }
  15048. }
  15049. }
  15050. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  15051. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  15052. if (lctx.t_compute_start_us == 0) {
  15053. lctx.t_compute_start_us = ggml_time_us();
  15054. }
  15055. lctx.n_queued_tokens += n_tokens;
  15056. const int64_t n_embd = hparams.n_embd;
  15057. lctx.sbatch.from_batch(batch, batch.n_embd, /* simple_split */ true, /* logits_all */ true);
  15058. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  15059. // reserve output buffer
  15060. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  15061. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  15062. return -2;
  15063. };
  15064. for (uint32_t i = 0; i < n_tokens; ++i) {
  15065. lctx.output_ids[i] = i;
  15066. }
  15067. lctx.inp_embd_enc = NULL;
  15068. lctx.n_outputs = n_tokens;
  15069. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  15070. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  15071. GGML_ASSERT(n_threads > 0);
  15072. ggml_backend_sched_reset(lctx.sched);
  15073. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  15074. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  15075. // the output embeddings after the final encoder normalization
  15076. struct ggml_tensor * embd = nullptr;
  15077. // there are two cases here
  15078. if (llama_model_has_decoder(&lctx.model)) {
  15079. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  15080. embd = ggml_graph_node(gf, -1);
  15081. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  15082. } else {
  15083. // second case is an encoder-only T5 model
  15084. if (cparams.embeddings) {
  15085. // only output embeddings if required
  15086. embd = ggml_graph_node(gf, -1);
  15087. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  15088. embd = ggml_graph_node(gf, -2);
  15089. }
  15090. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  15091. }
  15092. }
  15093. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  15094. llama_set_inputs(lctx, ubatch);
  15095. llama_graph_compute(lctx, gf, n_threads, threadpool);
  15096. // extract embeddings
  15097. if (embd) {
  15098. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  15099. GGML_ASSERT(backend_embd != nullptr);
  15100. if (llama_model_has_decoder(&lctx.model)) {
  15101. lctx.embd_enc.resize(n_tokens*n_embd);
  15102. float * embd_out = lctx.embd_enc.data();
  15103. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15104. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15105. // remember the sequence ids used during the encoding - needed for cross attention later
  15106. lctx.seq_ids_enc.resize(n_tokens);
  15107. for (uint32_t i = 0; i < n_tokens; i++) {
  15108. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  15109. llama_seq_id seq_id = ubatch.seq_id[i][s];
  15110. lctx.seq_ids_enc[i].insert(seq_id);
  15111. }
  15112. }
  15113. } else {
  15114. GGML_ASSERT(lctx.embd != nullptr);
  15115. switch (cparams.pooling_type) {
  15116. case LLAMA_POOLING_TYPE_NONE:
  15117. {
  15118. // extract token embeddings
  15119. GGML_ASSERT(lctx.embd != nullptr);
  15120. float * embd_out = lctx.embd;
  15121. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  15122. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  15123. } break;
  15124. case LLAMA_POOLING_TYPE_MEAN:
  15125. case LLAMA_POOLING_TYPE_CLS:
  15126. case LLAMA_POOLING_TYPE_LAST:
  15127. {
  15128. // extract sequence embeddings
  15129. auto & embd_seq_out = lctx.embd_seq;
  15130. embd_seq_out.clear();
  15131. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  15132. for (uint32_t i = 0; i < n_tokens; i++) {
  15133. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  15134. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  15135. continue;
  15136. }
  15137. embd_seq_out[seq_id].resize(n_embd);
  15138. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  15139. }
  15140. } break;
  15141. case LLAMA_POOLING_TYPE_RANK:
  15142. {
  15143. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  15144. // wait for an encoder model that requires this pooling type in order to test it
  15145. // https://github.com/ggerganov/llama.cpp/pull/9510
  15146. GGML_ABORT("RANK pooling not implemented yet");
  15147. }
  15148. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  15149. {
  15150. GGML_ABORT("unknown pooling type");
  15151. }
  15152. }
  15153. }
  15154. }
  15155. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  15156. // overlap with device computation.
  15157. ggml_backend_sched_reset(lctx.sched);
  15158. return 0;
  15159. }
  15160. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  15161. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  15162. auto & kv_self = lctx.kv_self;
  15163. const auto & hparams = lctx.model.hparams;
  15164. const uint32_t n_layer = hparams.n_layer;
  15165. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  15166. const uint32_t n_used = kv_self.used;
  15167. assert(n_used <= n_kv);
  15168. //const int64_t t_start = ggml_time_us();
  15169. // number of cells moved
  15170. uint32_t n_moves = 0;
  15171. // each move requires 6*n_layer tensors (see build_defrag)
  15172. // - source view, destination view, copy operation
  15173. // - x2 for keys and values
  15174. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  15175. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  15176. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  15177. // determine which KV cells to move where
  15178. //
  15179. // cell i moves to ids[i]
  15180. //
  15181. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  15182. //
  15183. std::vector<uint32_t> ids(n_kv, n_kv);
  15184. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  15185. const auto & cell0 = kv_self.cells[i0];
  15186. if (!cell0.is_empty()) {
  15187. ids[i0] = i0;
  15188. continue;
  15189. }
  15190. // found a hole - fill it with data from the end of the cache
  15191. uint32_t nh = 1;
  15192. // determine the size of the hole
  15193. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  15194. nh++;
  15195. }
  15196. uint32_t nf = 0;
  15197. uint32_t is = n_kv - 1;
  15198. // starting from the end, find nh non-empty cells
  15199. for (; is > i0; --is) {
  15200. const auto & cell1 = kv_self.cells[is];
  15201. if (cell1.is_empty() || ids[is] != n_kv) {
  15202. continue;
  15203. }
  15204. // non-empty cell which is not yet moved
  15205. nf++;
  15206. if (nf == nh) {
  15207. break;
  15208. }
  15209. }
  15210. // this can only happen if `n_used` is not accurate, which would be a bug
  15211. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  15212. nf = 0;
  15213. uint32_t i1 = is;
  15214. // are we moving a continuous block of memory?
  15215. bool cont = false;
  15216. // should we stop searching for the next move?
  15217. bool stop = false;
  15218. // go back and move the nf cells to the hole
  15219. for (; i1 < n_kv; ++i1) {
  15220. auto & cell1 = kv_self.cells[i1];
  15221. if (cell1.is_empty() || ids[i1] != n_kv) {
  15222. if (n_moves == max_moves) {
  15223. stop = true;
  15224. break;
  15225. }
  15226. cont = false;
  15227. continue;
  15228. }
  15229. // this cell goes to (i0 + nf)
  15230. ids[i1] = i0 + nf;
  15231. // move the cell meta data
  15232. kv_self.cells[i0 + nf] = cell1;
  15233. // clear the old cell and move the head there
  15234. cell1 = llama_kv_cell();
  15235. kv_self.head = n_used;
  15236. if (!cont) {
  15237. n_moves++;
  15238. cont = true;
  15239. }
  15240. nf++;
  15241. if (nf == nh) {
  15242. break;
  15243. }
  15244. }
  15245. if (stop || n_moves == max_moves) {
  15246. break;
  15247. }
  15248. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  15249. i0 += nh - 1;
  15250. }
  15251. if (n_moves == 0) {
  15252. return;
  15253. }
  15254. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  15255. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  15256. #if 0
  15257. // CPU defrag
  15258. //
  15259. // TODO: optimizations are possible:
  15260. // - multiple threads
  15261. // - avoid copying to the host memory when already there
  15262. //
  15263. // likely not worth the effort, as we have ggml_graph based defrag
  15264. //
  15265. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  15266. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  15267. const uint32_t kv_size = kv_self.size;
  15268. std::vector<uint8_t> buf_k;
  15269. std::vector<uint8_t> buf_v;
  15270. for (uint32_t il = 0; il < n_layer; ++il) {
  15271. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15272. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  15273. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15274. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  15275. buf_k.resize(k_size);
  15276. buf_v.resize(v_size);
  15277. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15278. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15279. // batch move [i, i+nm) to [id, id+nm)
  15280. // note: cells can move only to a lower index
  15281. for (uint32_t i = 0; i < n_kv; ++i) {
  15282. const uint32_t id = ids[i];
  15283. if (i == id || id == n_kv) {
  15284. continue;
  15285. }
  15286. uint32_t nm = 1;
  15287. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  15288. nm++;
  15289. }
  15290. // move keys
  15291. {
  15292. const int64_t os = i*k_size_row;
  15293. const int64_t od = id*k_size_row;
  15294. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  15295. }
  15296. // move values (note: they are transposed)
  15297. {
  15298. const int64_t os = i;
  15299. const int64_t od = id;
  15300. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15301. 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);
  15302. }
  15303. }
  15304. i += nm - 1;
  15305. }
  15306. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  15307. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  15308. }
  15309. #else
  15310. // ggml_graph defrag
  15311. ggml_backend_sched_reset(lctx.sched);
  15312. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  15313. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15314. #endif
  15315. //const int64_t t_end = ggml_time_us();
  15316. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  15317. }
  15318. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  15319. bool need_reserve = false;
  15320. // apply K-shift if needed
  15321. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  15322. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  15323. GGML_ABORT("Deepseek2 does not support K-shift");
  15324. }
  15325. {
  15326. ggml_backend_sched_reset(lctx.sched);
  15327. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  15328. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  15329. llama_set_k_shift(lctx);
  15330. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  15331. need_reserve = true;
  15332. }
  15333. {
  15334. auto & kv_self = lctx.kv_self;
  15335. kv_self.has_shift = false;
  15336. for (uint32_t i = 0; i < kv_self.size; ++i) {
  15337. kv_self.cells[i].delta = 0;
  15338. }
  15339. }
  15340. }
  15341. // defragment the KV cache if needed
  15342. if (lctx.kv_self.do_defrag) {
  15343. llama_kv_cache_defrag_internal(lctx);
  15344. need_reserve = true;
  15345. lctx.kv_self.do_defrag = false;
  15346. }
  15347. // reserve a worst case graph again
  15348. if (need_reserve) {
  15349. // TODO: extract to a function
  15350. // build worst-case graph
  15351. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  15352. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  15353. 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
  15354. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  15355. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  15356. // initialize scheduler with the worst-case graph
  15357. ggml_backend_sched_reset(lctx.sched);
  15358. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  15359. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  15360. }
  15361. }
  15362. }
  15363. //
  15364. // quantization
  15365. //
  15366. struct quantize_state_internal {
  15367. const llama_model & model;
  15368. const llama_model_quantize_params * params;
  15369. int n_attention_wv = 0;
  15370. int n_ffn_down = 0;
  15371. int n_ffn_gate = 0;
  15372. int n_ffn_up = 0;
  15373. int i_attention_wv = 0;
  15374. int i_ffn_down = 0;
  15375. int i_ffn_gate = 0;
  15376. int i_ffn_up = 0;
  15377. int n_k_quantized = 0;
  15378. int n_fallback = 0;
  15379. bool has_imatrix = false;
  15380. // used to figure out if a model shares tok_embd with the output weight
  15381. bool has_output = false;
  15382. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  15383. : model(model)
  15384. , params(params)
  15385. {}
  15386. };
  15387. static void llama_tensor_dequantize_internal(
  15388. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  15389. const size_t nelements, const int nthread
  15390. ) {
  15391. if (output.size() < nelements) {
  15392. output.resize(nelements);
  15393. }
  15394. float * f32_output = (float *) output.data();
  15395. ggml_type_traits_t qtype;
  15396. if (ggml_is_quantized(tensor->type)) {
  15397. qtype = ggml_internal_get_type_traits(tensor->type);
  15398. if (qtype.to_float == NULL) {
  15399. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  15400. }
  15401. } else if (tensor->type != GGML_TYPE_F16 &&
  15402. tensor->type != GGML_TYPE_BF16) {
  15403. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  15404. }
  15405. if (nthread < 2) {
  15406. if (tensor->type == GGML_TYPE_F16) {
  15407. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  15408. } else if (tensor->type == GGML_TYPE_BF16) {
  15409. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  15410. } else if (ggml_is_quantized(tensor->type)) {
  15411. qtype.to_float(tensor->data, f32_output, nelements);
  15412. } else {
  15413. GGML_ABORT("fatal error"); // unreachable
  15414. }
  15415. return;
  15416. }
  15417. size_t block_size;
  15418. if (tensor->type == GGML_TYPE_F16 ||
  15419. tensor->type == GGML_TYPE_BF16) {
  15420. block_size = 1;
  15421. } else {
  15422. block_size = (size_t)ggml_blck_size(tensor->type);
  15423. }
  15424. size_t block_size_bytes = ggml_type_size(tensor->type);
  15425. GGML_ASSERT(nelements % block_size == 0);
  15426. size_t nblocks = nelements / block_size;
  15427. size_t blocks_per_thread = nblocks / nthread;
  15428. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  15429. size_t in_buff_offs = 0;
  15430. size_t out_buff_offs = 0;
  15431. for (int tnum = 0; tnum < nthread; tnum++) {
  15432. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  15433. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  15434. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  15435. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  15436. if (typ == GGML_TYPE_F16) {
  15437. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  15438. } else if (typ == GGML_TYPE_BF16) {
  15439. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  15440. } else {
  15441. qtype.to_float(inbuf, outbuf, nels);
  15442. }
  15443. };
  15444. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  15445. in_buff_offs += thr_block_bytes;
  15446. out_buff_offs += thr_elems;
  15447. }
  15448. for (auto & w : workers) { w.join(); }
  15449. workers.clear();
  15450. }
  15451. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  15452. const std::string name = ggml_get_name(tensor);
  15453. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15454. const llm_arch arch = qs.model.arch;
  15455. const auto tn = LLM_TN(arch);
  15456. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  15457. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  15458. };
  15459. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  15460. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  15461. if (n_expert > 1) {
  15462. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  15463. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  15464. // for getting the current layer as I initially thought, and we need to resort to parsing the
  15465. // tensor name.
  15466. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  15467. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  15468. }
  15469. if (i_layer < 0 || i_layer >= n_layer) {
  15470. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  15471. }
  15472. }
  15473. return std::make_pair(i_layer, n_layer);
  15474. };
  15475. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  15476. // with the quantization of the output tensor
  15477. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  15478. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  15479. new_type = qs.params->output_tensor_type;
  15480. } else {
  15481. int nx = tensor->ne[0];
  15482. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  15483. new_type = GGML_TYPE_Q8_0;
  15484. }
  15485. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15486. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  15487. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15488. new_type = GGML_TYPE_Q5_K;
  15489. }
  15490. else if (new_type != GGML_TYPE_Q8_0) {
  15491. new_type = GGML_TYPE_Q6_K;
  15492. }
  15493. }
  15494. } else if (name == "token_embd.weight") {
  15495. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  15496. new_type = qs.params->token_embedding_type;
  15497. } else {
  15498. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  15499. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15500. new_type = GGML_TYPE_Q2_K;
  15501. }
  15502. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  15503. new_type = GGML_TYPE_IQ3_S;
  15504. }
  15505. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15506. new_type = GGML_TYPE_IQ3_S;
  15507. }
  15508. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  15509. new_type == GGML_TYPE_Q4_0_8_8) {
  15510. new_type = GGML_TYPE_Q4_0;
  15511. }
  15512. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  15513. new_type = GGML_TYPE_Q4_K;
  15514. }
  15515. }
  15516. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  15517. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  15518. if (name.find("attn_v.weight") != std::string::npos) {
  15519. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  15520. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  15521. ++qs.i_attention_wv;
  15522. }
  15523. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  15524. new_type = GGML_TYPE_Q4_K;
  15525. }
  15526. else if (name.find("ffn_down") != std::string::npos) {
  15527. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  15528. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  15529. }
  15530. ++qs.i_ffn_down;
  15531. }
  15532. else if (name.find("attn_output.weight") != std::string::npos) {
  15533. if (qs.model.hparams.n_expert == 8) {
  15534. new_type = GGML_TYPE_Q5_K;
  15535. } else {
  15536. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  15537. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  15538. }
  15539. }
  15540. } else if (name.find("attn_v.weight") != std::string::npos) {
  15541. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  15542. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15543. }
  15544. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  15545. new_type = GGML_TYPE_Q4_K;
  15546. }
  15547. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15548. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  15549. }
  15550. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  15551. new_type = GGML_TYPE_Q4_K;
  15552. }
  15553. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15554. new_type = GGML_TYPE_Q4_K;
  15555. }
  15556. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15557. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15558. }
  15559. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  15560. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  15561. new_type = GGML_TYPE_Q5_K;
  15562. }
  15563. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  15564. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  15565. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  15566. if (qs.model.type == MODEL_70B) {
  15567. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  15568. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  15569. // nearly negligible increase in model size by quantizing this tensor with more bits:
  15570. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  15571. }
  15572. if (qs.model.hparams.n_expert == 8) {
  15573. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15574. // TODO: explore better strategies
  15575. new_type = GGML_TYPE_Q8_0;
  15576. }
  15577. ++qs.i_attention_wv;
  15578. } else if (name.find("attn_k.weight") != std::string::npos) {
  15579. if (qs.model.hparams.n_expert == 8) {
  15580. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15581. // TODO: explore better strategies
  15582. new_type = GGML_TYPE_Q8_0;
  15583. }
  15584. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15585. new_type = GGML_TYPE_IQ3_XXS;
  15586. }
  15587. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15588. new_type = GGML_TYPE_IQ2_S;
  15589. }
  15590. } else if (name.find("attn_q.weight") != std::string::npos) {
  15591. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15592. new_type = GGML_TYPE_IQ3_XXS;
  15593. }
  15594. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15595. new_type = GGML_TYPE_IQ2_S;
  15596. }
  15597. } else if (name.find("ffn_down") != std::string::npos) {
  15598. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  15599. int i_layer = info.first, n_layer = info.second;
  15600. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15601. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  15602. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  15603. }
  15604. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  15605. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15606. }
  15607. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15608. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  15609. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  15610. : GGML_TYPE_Q3_K;
  15611. }
  15612. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  15613. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  15614. new_type = GGML_TYPE_Q4_K;
  15615. }
  15616. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  15617. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  15618. }
  15619. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  15620. if (arch == LLM_ARCH_FALCON) {
  15621. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  15622. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15623. } else {
  15624. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15625. }
  15626. }
  15627. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  15628. new_type = GGML_TYPE_Q5_K;
  15629. }
  15630. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15631. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  15632. new_type = GGML_TYPE_Q5_K;
  15633. }
  15634. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  15635. && qs.has_imatrix && i_layer < n_layer/8) {
  15636. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  15637. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  15638. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  15639. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  15640. }
  15641. ++qs.i_ffn_down;
  15642. } else if (name.find("attn_output.weight") != std::string::npos) {
  15643. if (arch != LLM_ARCH_FALCON) {
  15644. if (qs.model.hparams.n_expert == 8) {
  15645. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15646. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  15647. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  15648. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  15649. new_type = GGML_TYPE_Q5_K;
  15650. }
  15651. } else {
  15652. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  15653. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  15654. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  15655. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  15656. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  15657. }
  15658. } else {
  15659. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  15660. }
  15661. }
  15662. else if (name.find("attn_qkv.weight") != std::string::npos) {
  15663. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15664. new_type = GGML_TYPE_Q4_K;
  15665. }
  15666. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  15667. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  15668. }
  15669. else if (name.find("ffn_gate") != std::string::npos) {
  15670. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  15671. int i_layer = info.first, n_layer = info.second;
  15672. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15673. new_type = GGML_TYPE_IQ3_XXS;
  15674. }
  15675. ++qs.i_ffn_gate;
  15676. }
  15677. else if (name.find("ffn_up") != std::string::npos) {
  15678. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  15679. int i_layer = info.first, n_layer = info.second;
  15680. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15681. new_type = GGML_TYPE_IQ3_XXS;
  15682. }
  15683. ++qs.i_ffn_up;
  15684. }
  15685. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15686. //}
  15687. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  15688. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  15689. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15690. //}
  15691. // This can be used to reduce the size of the Q5_K_S model.
  15692. // The associated PPL increase is fully in line with the size reduction
  15693. //else {
  15694. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  15695. //}
  15696. bool convert_incompatible_tensor = false;
  15697. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  15698. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  15699. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  15700. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  15701. new_type == GGML_TYPE_IQ1_M) {
  15702. int nx = tensor->ne[0];
  15703. int ny = tensor->ne[1];
  15704. if (nx % QK_K != 0) {
  15705. 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));
  15706. convert_incompatible_tensor = true;
  15707. } else {
  15708. ++qs.n_k_quantized;
  15709. }
  15710. }
  15711. if (convert_incompatible_tensor) {
  15712. switch (new_type) {
  15713. case GGML_TYPE_TQ1_0:
  15714. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  15715. case GGML_TYPE_IQ2_XXS:
  15716. case GGML_TYPE_IQ2_XS:
  15717. case GGML_TYPE_IQ2_S:
  15718. case GGML_TYPE_IQ3_XXS:
  15719. case GGML_TYPE_IQ3_S:
  15720. case GGML_TYPE_IQ1_S:
  15721. case GGML_TYPE_IQ1_M:
  15722. case GGML_TYPE_Q2_K:
  15723. case GGML_TYPE_Q3_K:
  15724. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  15725. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  15726. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  15727. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  15728. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  15729. }
  15730. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  15731. new_type = GGML_TYPE_F16;
  15732. }
  15733. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  15734. ++qs.n_fallback;
  15735. }
  15736. return new_type;
  15737. }
  15738. 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) {
  15739. if (nthread < 2) {
  15740. // single-thread
  15741. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  15742. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  15743. throw std::runtime_error("quantized data validation failed");
  15744. }
  15745. return new_size;
  15746. }
  15747. std::mutex mutex;
  15748. int64_t counter = 0;
  15749. size_t new_size = 0;
  15750. bool valid = true;
  15751. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  15752. nrows, n_per_row, imatrix]() {
  15753. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  15754. size_t local_size = 0;
  15755. while (true) {
  15756. std::unique_lock<std::mutex> lock(mutex);
  15757. int64_t first_row = counter; counter += nrows_per_chunk;
  15758. if (first_row >= nrows) {
  15759. if (local_size > 0) {
  15760. new_size += local_size;
  15761. }
  15762. break;
  15763. }
  15764. lock.unlock();
  15765. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  15766. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  15767. local_size += this_size;
  15768. // validate the quantized data
  15769. const size_t row_size = ggml_row_size(new_type, n_per_row);
  15770. void * this_data = (char *) new_data + first_row * row_size;
  15771. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  15772. std::unique_lock<std::mutex> lock(mutex);
  15773. valid = false;
  15774. break;
  15775. }
  15776. }
  15777. };
  15778. for (int it = 0; it < nthread - 1; ++it) {
  15779. workers.emplace_back(compute);
  15780. }
  15781. compute();
  15782. for (auto & w : workers) { w.join(); }
  15783. workers.clear();
  15784. if (!valid) {
  15785. throw std::runtime_error("quantized data validation failed");
  15786. }
  15787. return new_size;
  15788. }
  15789. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  15790. ggml_type default_type;
  15791. llama_ftype ftype = params->ftype;
  15792. switch (params->ftype) {
  15793. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  15794. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  15795. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  15796. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  15797. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  15798. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  15799. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  15800. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  15801. // K-quants
  15802. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  15803. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  15804. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  15805. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  15806. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  15807. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  15808. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  15809. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  15810. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  15811. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  15812. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  15813. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  15814. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  15815. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  15816. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  15817. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  15818. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  15819. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  15820. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  15821. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  15822. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  15823. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  15824. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  15825. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  15826. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  15827. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  15828. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  15829. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  15830. }
  15831. int nthread = params->nthread;
  15832. if (nthread <= 0) {
  15833. nthread = std::thread::hardware_concurrency();
  15834. }
  15835. // mmap consistently increases speed Linux, and also increases speed on Windows with
  15836. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  15837. #if defined(__linux__) || defined(_WIN32)
  15838. constexpr bool use_mmap = true;
  15839. #else
  15840. constexpr bool use_mmap = false;
  15841. #endif
  15842. llama_model_kv_override * kv_overrides = nullptr;
  15843. if (params->kv_overrides) {
  15844. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  15845. kv_overrides = v->data();
  15846. }
  15847. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  15848. ml.init_mappings(false); // no prefetching
  15849. llama_model model;
  15850. llm_load_arch(ml, model);
  15851. llm_load_hparams(ml, model);
  15852. struct quantize_state_internal qs(model, params);
  15853. if (params->only_copy) {
  15854. ftype = model.ftype;
  15855. }
  15856. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  15857. if (params->imatrix) {
  15858. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  15859. if (imatrix_data) {
  15860. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  15861. qs.has_imatrix = true;
  15862. // check imatrix for nans or infs
  15863. for (const auto & kv : *imatrix_data) {
  15864. for (float f : kv.second) {
  15865. if (!std::isfinite(f)) {
  15866. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  15867. }
  15868. }
  15869. }
  15870. }
  15871. }
  15872. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  15873. struct gguf_context * ctx_out = gguf_init_empty();
  15874. // copy the KV pairs from the input file
  15875. gguf_set_kv (ctx_out, ml.meta);
  15876. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  15877. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  15878. // Remove split metadata
  15879. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  15880. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  15881. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  15882. if (params->kv_overrides) {
  15883. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  15884. for (auto & o : overrides) {
  15885. if (o.key[0] == 0) break;
  15886. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  15887. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  15888. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  15889. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  15890. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  15891. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  15892. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  15893. gguf_set_val_str(ctx_out, o.key, o.val_str);
  15894. } else {
  15895. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  15896. }
  15897. }
  15898. }
  15899. for (int i = 0; i < ml.n_tensors; ++i) {
  15900. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  15901. const std::string name = ggml_get_name(meta);
  15902. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15903. if (name.find("attn_v.weight") != std::string::npos ||
  15904. name.find("attn_qkv.weight") != std::string::npos ||
  15905. name.find("attn_kv_b.weight")!= std::string::npos) {
  15906. ++qs.n_attention_wv;
  15907. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  15908. qs.has_output = true;
  15909. }
  15910. }
  15911. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  15912. // sanity checks
  15913. {
  15914. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  15915. // attention layers have a non-zero number of kv heads
  15916. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  15917. if (llama_model_has_encoder(&model)) {
  15918. n_attn_layer *= 3;
  15919. }
  15920. if (qs.n_attention_wv != n_attn_layer) {
  15921. LLAMA_LOG_WARN("%s: n_attention_wv is unexpected, expected: %d, found: %d\n", __func__, n_attn_layer, qs.n_attention_wv);
  15922. }
  15923. }
  15924. size_t total_size_org = 0;
  15925. size_t total_size_new = 0;
  15926. std::vector<std::thread> workers;
  15927. workers.reserve(nthread);
  15928. int idx = 0;
  15929. std::vector<no_init<uint8_t>> read_data;
  15930. std::vector<no_init<uint8_t>> work;
  15931. std::vector<no_init<float>> f32_conv_buf;
  15932. uint16_t n_split = 1;
  15933. // Assume split index is continuous
  15934. if (params->keep_split) {
  15935. for (int i = 0; i < ml.n_tensors; ++i) {
  15936. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  15937. }
  15938. }
  15939. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  15940. ctx_outs[0] = ctx_out;
  15941. // populate the original tensors so we get an initial meta data
  15942. for (int i = 0; i < ml.n_tensors; ++i) {
  15943. auto weight = ml.get_weight(i);
  15944. uint16_t i_split = params->keep_split ? weight->idx : 0;
  15945. struct ggml_tensor * tensor = weight->tensor;
  15946. if (ctx_outs[i_split] == NULL) {
  15947. ctx_outs[i_split] = gguf_init_empty();
  15948. }
  15949. gguf_add_tensor(ctx_outs[i_split], tensor);
  15950. }
  15951. // Set split info if needed
  15952. if (n_split > 1) {
  15953. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  15954. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  15955. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  15956. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  15957. }
  15958. }
  15959. int cur_split = -1;
  15960. std::ofstream fout;
  15961. auto close_ofstream = [&]() {
  15962. // Write metadata and close file handler
  15963. if (fout.is_open()) {
  15964. fout.seekp(0);
  15965. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  15966. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  15967. fout.write((const char *) data.data(), data.size());
  15968. fout.close();
  15969. }
  15970. };
  15971. auto new_ofstream = [&](int index) {
  15972. cur_split = index;
  15973. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  15974. std::string fname = fname_out;
  15975. if (params->keep_split) {
  15976. char split_path[PATH_MAX] = {0};
  15977. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  15978. fname = std::string(split_path);
  15979. }
  15980. fout = std::ofstream(fname, std::ios::binary);
  15981. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  15982. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  15983. // placeholder for the meta data
  15984. ::zeros(fout, meta_size);
  15985. };
  15986. const auto tn = LLM_TN(model.arch);
  15987. new_ofstream(0);
  15988. for (int i = 0; i < ml.n_tensors; ++i) {
  15989. auto weight = ml.get_weight(i);
  15990. struct ggml_tensor * tensor = weight->tensor;
  15991. if (weight->idx != cur_split && params->keep_split) {
  15992. close_ofstream();
  15993. new_ofstream(weight->idx);
  15994. }
  15995. const std::string name = ggml_get_name(tensor);
  15996. if (!ml.use_mmap) {
  15997. if (read_data.size() < ggml_nbytes(tensor)) {
  15998. read_data.resize(ggml_nbytes(tensor));
  15999. }
  16000. tensor->data = read_data.data();
  16001. }
  16002. ml.load_data_for(tensor);
  16003. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  16004. ++idx, ml.n_tensors,
  16005. ggml_get_name(tensor),
  16006. llama_format_tensor_shape(tensor).c_str(),
  16007. ggml_type_name(tensor->type));
  16008. // This used to be a regex, but <regex> has an extreme cost to compile times.
  16009. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  16010. // quantize only 2D and 3D tensors (experts)
  16011. quantize &= (ggml_n_dims(tensor) >= 2);
  16012. // do not quantize norm tensors
  16013. quantize &= name.find("_norm.weight") == std::string::npos;
  16014. quantize &= params->quantize_output_tensor || name != "output.weight";
  16015. quantize &= !params->only_copy;
  16016. // do not quantize expert gating tensors
  16017. // NOTE: can't use LLM_TN here because the layer number is not known
  16018. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  16019. // do not quantize positional embeddings and token types (BERT)
  16020. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  16021. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  16022. // do not quantize Mamba's small yet 2D weights
  16023. // NOTE: can't use LLM_TN here because the layer number is not known
  16024. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  16025. // do not quantize RWKV's time_mix_first tensors
  16026. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  16027. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  16028. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  16029. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  16030. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  16031. // do not quantize relative position bias (T5)
  16032. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  16033. enum ggml_type new_type;
  16034. void * new_data;
  16035. size_t new_size;
  16036. if (quantize) {
  16037. new_type = default_type;
  16038. // get more optimal quantization type based on the tensor shape, layer, etc.
  16039. if (!params->pure && ggml_is_quantized(default_type)) {
  16040. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  16041. }
  16042. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  16043. new_type = params->token_embedding_type;
  16044. }
  16045. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  16046. new_type = params->output_tensor_type;
  16047. }
  16048. // If we've decided to quantize to the same type the tensor is already
  16049. // in then there's nothing to do.
  16050. quantize = tensor->type != new_type;
  16051. }
  16052. if (!quantize) {
  16053. new_type = tensor->type;
  16054. new_data = tensor->data;
  16055. new_size = ggml_nbytes(tensor);
  16056. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  16057. } else {
  16058. const int64_t nelements = ggml_nelements(tensor);
  16059. const float * imatrix = nullptr;
  16060. if (imatrix_data) {
  16061. auto it = imatrix_data->find(tensor->name);
  16062. if (it == imatrix_data->end()) {
  16063. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  16064. } else {
  16065. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  16066. imatrix = it->second.data();
  16067. } else {
  16068. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  16069. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  16070. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  16071. // this is a significant error and it may be good idea to abort the process if this happens,
  16072. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  16073. // tok_embd should be ignored in this case, since it always causes this warning
  16074. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  16075. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  16076. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  16077. }
  16078. }
  16079. }
  16080. }
  16081. if ((new_type == GGML_TYPE_IQ2_XXS ||
  16082. new_type == GGML_TYPE_IQ2_XS ||
  16083. new_type == GGML_TYPE_IQ2_S ||
  16084. new_type == GGML_TYPE_IQ1_S ||
  16085. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  16086. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  16087. LLAMA_LOG_ERROR("\n\n============================================================\n");
  16088. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  16089. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  16090. LLAMA_LOG_ERROR("============================================================\n\n");
  16091. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  16092. }
  16093. float * f32_data;
  16094. if (tensor->type == GGML_TYPE_F32) {
  16095. f32_data = (float *) tensor->data;
  16096. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  16097. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  16098. } else {
  16099. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  16100. f32_data = (float *) f32_conv_buf.data();
  16101. }
  16102. int chunk_size_multiplier = 1;
  16103. 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) {
  16104. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  16105. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  16106. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  16107. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  16108. }
  16109. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  16110. fflush(stdout);
  16111. if (work.size() < (size_t)nelements * 4) {
  16112. work.resize(nelements * 4); // upper bound on size
  16113. }
  16114. new_data = work.data();
  16115. const int64_t n_per_row = tensor->ne[0];
  16116. const int64_t nrows = tensor->ne[1];
  16117. static const int64_t min_chunk_size = 32 * 512;
  16118. 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)) *
  16119. chunk_size_multiplier;
  16120. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  16121. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  16122. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  16123. // quantize each expert separately since they have different importance matrices
  16124. new_size = 0;
  16125. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  16126. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  16127. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  16128. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  16129. 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);
  16130. }
  16131. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  16132. }
  16133. total_size_org += ggml_nbytes(tensor);
  16134. total_size_new += new_size;
  16135. // update the gguf meta data as we go
  16136. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  16137. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  16138. // write tensor data + padding
  16139. fout.write((const char *) new_data, new_size);
  16140. zeros(fout, GGML_PAD(new_size, align) - new_size);
  16141. }
  16142. close_ofstream();
  16143. for (auto & c:ctx_outs) {
  16144. gguf_free(c);
  16145. }
  16146. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  16147. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  16148. if (qs.n_fallback > 0) {
  16149. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  16150. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  16151. }
  16152. }
  16153. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  16154. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  16155. ggml_context * ctx = nullptr;
  16156. struct gguf_init_params meta_gguf_params = {
  16157. /* .no_alloc = */ true,
  16158. /* .ctx = */ &ctx,
  16159. };
  16160. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  16161. if (!ctx_gguf) {
  16162. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  16163. }
  16164. // check metadata
  16165. {
  16166. auto get_kv_str = [&](const std::string & key) -> std::string {
  16167. int id = gguf_find_key(ctx_gguf, key.c_str());
  16168. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  16169. };
  16170. auto get_kv_f32 = [&](const std::string & key) -> float {
  16171. int id = gguf_find_key(ctx_gguf, key.c_str());
  16172. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  16173. };
  16174. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  16175. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  16176. if (general_type != "adapter") {
  16177. gguf_free(ctx_gguf);
  16178. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  16179. }
  16180. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  16181. auto general_arch = llm_arch_from_string(general_arch_str);
  16182. if (general_arch != model->arch) {
  16183. gguf_free(ctx_gguf);
  16184. throw std::runtime_error("model arch and LoRA arch mismatch");
  16185. }
  16186. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  16187. if (adapter_type != "lora") {
  16188. gguf_free(ctx_gguf);
  16189. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  16190. }
  16191. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  16192. }
  16193. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  16194. // contexts for each buffer type
  16195. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  16196. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  16197. auto it = ctx_map.find(buft);
  16198. if (it == ctx_map.end()) {
  16199. // add a new context
  16200. struct ggml_init_params params = {
  16201. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  16202. /*.mem_buffer =*/ NULL,
  16203. /*.no_alloc =*/ true,
  16204. };
  16205. ggml_context * buft_ctx = ggml_init(params);
  16206. ctx_map[buft] = buft_ctx;
  16207. return buft_ctx;
  16208. };
  16209. return it->second;
  16210. };
  16211. // bundle lora_a and lora_b into pairs
  16212. std::map<std::string, llama_lora_weight> ab_map;
  16213. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  16214. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  16215. };
  16216. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  16217. std::string name(cur->name);
  16218. if (str_endswith(name, ".lora_a")) {
  16219. replace_all(name, ".lora_a", "");
  16220. if (ab_map.find(name) == ab_map.end()) {
  16221. ab_map[name] = llama_lora_weight(cur, nullptr);
  16222. } else {
  16223. ab_map[name].a = cur;
  16224. }
  16225. } else if (str_endswith(name, ".lora_b")) {
  16226. replace_all(name, ".lora_b", "");
  16227. if (ab_map.find(name) == ab_map.end()) {
  16228. ab_map[name] = llama_lora_weight(nullptr, cur);
  16229. } else {
  16230. ab_map[name].b = cur;
  16231. }
  16232. } else {
  16233. gguf_free(ctx_gguf);
  16234. ggml_free(ctx);
  16235. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  16236. }
  16237. }
  16238. // add tensors
  16239. for (auto & it : ab_map) {
  16240. const std::string & name = it.first;
  16241. llama_lora_weight & w = it.second;
  16242. if (!w.a || !w.b) {
  16243. gguf_free(ctx_gguf);
  16244. ggml_free(ctx);
  16245. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  16246. }
  16247. // device buft and device ctx
  16248. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  16249. if (!model_tensor) {
  16250. gguf_free(ctx_gguf);
  16251. ggml_free(ctx);
  16252. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  16253. }
  16254. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  16255. // validate tensor shape
  16256. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  16257. gguf_free(ctx_gguf);
  16258. ggml_free(ctx);
  16259. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  16260. }
  16261. if (w.a->ne[1] != w.b->ne[0]) {
  16262. gguf_free(ctx_gguf);
  16263. ggml_free(ctx);
  16264. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  16265. }
  16266. // save tensor to adapter
  16267. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  16268. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  16269. ggml_set_name(tensor_a, w.a->name);
  16270. ggml_set_name(tensor_b, w.b->name);
  16271. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  16272. }
  16273. // allocate tensors / buffers and zero
  16274. {
  16275. adapter.ctxs.reserve(ctx_map.size());
  16276. adapter.bufs.reserve(ctx_map.size());
  16277. for (auto it : ctx_map) {
  16278. ggml_backend_buffer_type_t buft = it.first;
  16279. ggml_context * ctx_dev = it.second;
  16280. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  16281. if (!buf) {
  16282. gguf_free(ctx_gguf);
  16283. ggml_free(ctx);
  16284. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  16285. }
  16286. 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);
  16287. adapter.ctxs.push_back(ctx_dev);
  16288. adapter.bufs.push_back(buf);
  16289. }
  16290. }
  16291. // set tensor data
  16292. {
  16293. llama_file gguf_file(path_lora, "rb");
  16294. std::vector<uint8_t> read_buf;
  16295. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  16296. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  16297. size_t size = ggml_nbytes(orig);
  16298. read_buf.resize(size);
  16299. gguf_file.seek(offs, SEEK_SET);
  16300. gguf_file.read_raw(read_buf.data(), size);
  16301. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  16302. };
  16303. for (auto & it : adapter.ab_map) {
  16304. auto orig = ab_map[it.first];
  16305. auto dev = it.second;
  16306. set_tensor(orig.a, dev.a);
  16307. set_tensor(orig.b, dev.b);
  16308. }
  16309. }
  16310. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  16311. // free ctx for reading gguf
  16312. gguf_free(ctx_gguf);
  16313. ggml_free(ctx);
  16314. }
  16315. int32_t llama_lora_adapter_set(
  16316. struct llama_context * ctx,
  16317. struct llama_lora_adapter * adapter,
  16318. float scale) {
  16319. if (ctx->cparams.flash_attn) {
  16320. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  16321. return -1;
  16322. }
  16323. ctx->lora_adapters[adapter] = scale;
  16324. return 0;
  16325. }
  16326. int32_t llama_lora_adapter_remove(
  16327. struct llama_context * ctx,
  16328. struct llama_lora_adapter * adapter) {
  16329. auto pos = ctx->lora_adapters.find(adapter);
  16330. if (pos != ctx->lora_adapters.end()) {
  16331. ctx->lora_adapters.erase(pos);
  16332. return 0;
  16333. }
  16334. return -1;
  16335. }
  16336. void llama_lora_adapter_clear(struct llama_context * ctx) {
  16337. ctx->lora_adapters.clear();
  16338. }
  16339. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  16340. delete adapter;
  16341. }
  16342. //
  16343. // interface implementation
  16344. //
  16345. struct llama_model_params llama_model_default_params() {
  16346. struct llama_model_params result = {
  16347. /*.n_gpu_layers =*/ 0,
  16348. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  16349. /*.main_gpu =*/ 0,
  16350. /*.tensor_split =*/ nullptr,
  16351. /*.rpc_servers =*/ nullptr,
  16352. /*.progress_callback =*/ nullptr,
  16353. /*.progress_callback_user_data =*/ nullptr,
  16354. /*.kv_overrides =*/ nullptr,
  16355. /*.vocab_only =*/ false,
  16356. /*.use_mmap =*/ true,
  16357. /*.use_mlock =*/ false,
  16358. /*.check_tensors =*/ false,
  16359. };
  16360. #ifdef GGML_USE_METAL
  16361. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  16362. result.n_gpu_layers = 999;
  16363. #endif
  16364. return result;
  16365. }
  16366. struct llama_context_params llama_context_default_params() {
  16367. struct llama_context_params result = {
  16368. /*.n_ctx =*/ 512,
  16369. /*.n_batch =*/ 2048,
  16370. /*.n_ubatch =*/ 512,
  16371. /*.n_seq_max =*/ 1,
  16372. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  16373. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  16374. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  16375. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  16376. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  16377. /*.rope_freq_base =*/ 0.0f,
  16378. /*.rope_freq_scale =*/ 0.0f,
  16379. /*.yarn_ext_factor =*/ -1.0f,
  16380. /*.yarn_attn_factor =*/ 1.0f,
  16381. /*.yarn_beta_fast =*/ 32.0f,
  16382. /*.yarn_beta_slow =*/ 1.0f,
  16383. /*.yarn_orig_ctx =*/ 0,
  16384. /*.defrag_thold =*/ -1.0f,
  16385. /*.cb_eval =*/ nullptr,
  16386. /*.cb_eval_user_data =*/ nullptr,
  16387. /*.type_k =*/ GGML_TYPE_F16,
  16388. /*.type_v =*/ GGML_TYPE_F16,
  16389. /*.logits_all =*/ false,
  16390. /*.embeddings =*/ false,
  16391. /*.offload_kqv =*/ true,
  16392. /*.flash_attn =*/ false,
  16393. /*.no_perf =*/ true,
  16394. /*.abort_callback =*/ nullptr,
  16395. /*.abort_callback_data =*/ nullptr,
  16396. };
  16397. return result;
  16398. }
  16399. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  16400. struct llama_sampler_chain_params result = {
  16401. /*.no_perf =*/ true,
  16402. };
  16403. return result;
  16404. }
  16405. struct llama_model_quantize_params llama_model_quantize_default_params() {
  16406. struct llama_model_quantize_params result = {
  16407. /*.nthread =*/ 0,
  16408. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  16409. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  16410. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  16411. /*.allow_requantize =*/ false,
  16412. /*.quantize_output_tensor =*/ true,
  16413. /*.only_copy =*/ false,
  16414. /*.pure =*/ false,
  16415. /*.keep_split =*/ false,
  16416. /*.imatrix =*/ nullptr,
  16417. /*.kv_overrides =*/ nullptr,
  16418. };
  16419. return result;
  16420. }
  16421. size_t llama_max_devices(void) {
  16422. #if defined(GGML_USE_RPC)
  16423. return GGML_RPC_MAX_SERVERS;
  16424. #elif defined(GGML_USE_METAL)
  16425. return 1;
  16426. #elif defined(GGML_USE_CUDA)
  16427. return GGML_CUDA_MAX_DEVICES;
  16428. #elif defined(GGML_USE_SYCL)
  16429. return GGML_SYCL_MAX_DEVICES;
  16430. #elif defined(GGML_USE_VULKAN)
  16431. return GGML_VK_MAX_DEVICES;
  16432. #elif defined(GGML_USE_CANN)
  16433. return GGML_CANN_MAX_DEVICES;
  16434. #else
  16435. return 1;
  16436. #endif
  16437. }
  16438. bool llama_supports_mmap(void) {
  16439. return llama_mmap::SUPPORTED;
  16440. }
  16441. bool llama_supports_mlock(void) {
  16442. return llama_mlock::SUPPORTED;
  16443. }
  16444. bool llama_supports_gpu_offload(void) {
  16445. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  16446. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  16447. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  16448. return true;
  16449. #else
  16450. return false;
  16451. #endif
  16452. }
  16453. void llama_backend_init(void) {
  16454. ggml_time_init();
  16455. // needed to initialize f16 tables
  16456. {
  16457. struct ggml_init_params params = { 0, NULL, false };
  16458. struct ggml_context * ctx = ggml_init(params);
  16459. ggml_free(ctx);
  16460. }
  16461. }
  16462. void llama_numa_init(enum ggml_numa_strategy numa) {
  16463. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  16464. ggml_numa_init(numa);
  16465. }
  16466. }
  16467. void llama_attach_threadpool(
  16468. struct llama_context * ctx,
  16469. ggml_threadpool_t threadpool,
  16470. ggml_threadpool_t threadpool_batch) {
  16471. ctx->threadpool = threadpool;
  16472. ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  16473. }
  16474. void llama_detach_threadpool(struct llama_context * ctx) {
  16475. ctx->threadpool = nullptr;
  16476. ctx->threadpool_batch = nullptr;
  16477. }
  16478. void llama_backend_free(void) {
  16479. ggml_quantize_free();
  16480. }
  16481. int64_t llama_time_us(void) {
  16482. return ggml_time_us();
  16483. }
  16484. struct llama_model * llama_load_model_from_file(
  16485. const char * path_model,
  16486. struct llama_model_params params) {
  16487. ggml_time_init();
  16488. llama_model * model = new llama_model;
  16489. unsigned cur_percentage = 0;
  16490. if (params.progress_callback == NULL) {
  16491. params.progress_callback_user_data = &cur_percentage;
  16492. params.progress_callback = [](float progress, void * ctx) {
  16493. unsigned * cur_percentage_p = (unsigned *) ctx;
  16494. unsigned percentage = (unsigned) (100 * progress);
  16495. while (percentage > *cur_percentage_p) {
  16496. *cur_percentage_p = percentage;
  16497. LLAMA_LOG_CONT(".");
  16498. if (percentage >= 100) {
  16499. LLAMA_LOG_CONT("\n");
  16500. }
  16501. }
  16502. return true;
  16503. };
  16504. }
  16505. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  16506. // split the servers set them into model->rpc_servers
  16507. std::string servers(params.rpc_servers);
  16508. size_t pos = 0;
  16509. while ((pos = servers.find(",")) != std::string::npos) {
  16510. std::string server = servers.substr(0, pos);
  16511. model->rpc_servers.push_back(server);
  16512. servers.erase(0, pos + 1);
  16513. }
  16514. model->rpc_servers.push_back(servers);
  16515. }
  16516. int status = llama_model_load(path_model, *model, params);
  16517. GGML_ASSERT(status <= 0);
  16518. if (status < 0) {
  16519. if (status == -1) {
  16520. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  16521. } else if (status == -2) {
  16522. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  16523. }
  16524. delete model;
  16525. return nullptr;
  16526. }
  16527. return model;
  16528. }
  16529. void llama_free_model(struct llama_model * model) {
  16530. delete model;
  16531. }
  16532. struct llama_context * llama_new_context_with_model(
  16533. struct llama_model * model,
  16534. struct llama_context_params params) {
  16535. if (!model) {
  16536. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  16537. return nullptr;
  16538. }
  16539. if (params.n_batch == 0 && params.n_ubatch == 0) {
  16540. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  16541. return nullptr;
  16542. }
  16543. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  16544. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  16545. return nullptr;
  16546. }
  16547. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  16548. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  16549. params.flash_attn = false;
  16550. }
  16551. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  16552. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  16553. params.flash_attn = false;
  16554. }
  16555. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  16556. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  16557. return nullptr;
  16558. }
  16559. llama_context * ctx = new llama_context(*model);
  16560. const auto & hparams = model->hparams;
  16561. auto & cparams = ctx->cparams;
  16562. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  16563. cparams.n_threads = params.n_threads;
  16564. cparams.n_threads_batch = params.n_threads_batch;
  16565. cparams.yarn_ext_factor = params.yarn_ext_factor;
  16566. cparams.yarn_attn_factor = params.yarn_attn_factor;
  16567. cparams.yarn_beta_fast = params.yarn_beta_fast;
  16568. cparams.yarn_beta_slow = params.yarn_beta_slow;
  16569. cparams.defrag_thold = params.defrag_thold;
  16570. cparams.embeddings = params.embeddings;
  16571. cparams.offload_kqv = params.offload_kqv;
  16572. cparams.flash_attn = params.flash_attn;
  16573. cparams.no_perf = params.no_perf;
  16574. cparams.pooling_type = params.pooling_type;
  16575. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  16576. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  16577. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  16578. // this is necessary due to kv_self.n being padded later during inference
  16579. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  16580. // with causal attention, the batch size is limited by the context size
  16581. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  16582. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  16583. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  16584. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  16585. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  16586. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  16587. cparams.n_batch = GGML_KQ_MASK_PAD;
  16588. }
  16589. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  16590. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  16591. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  16592. hparams.n_ctx_train;
  16593. cparams.cb_eval = params.cb_eval;
  16594. cparams.cb_eval_user_data = params.cb_eval_user_data;
  16595. auto rope_scaling_type = params.rope_scaling_type;
  16596. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  16597. rope_scaling_type = hparams.rope_scaling_type_train;
  16598. }
  16599. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  16600. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  16601. }
  16602. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  16603. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  16604. }
  16605. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  16606. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16607. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16608. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  16609. } else {
  16610. cparams.pooling_type = hparams.pooling_type;
  16611. }
  16612. }
  16613. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  16614. cparams.causal_attn = hparams.causal_attn;
  16615. } else {
  16616. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  16617. }
  16618. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  16619. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  16620. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  16621. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  16622. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  16623. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  16624. ctx->abort_callback = params.abort_callback;
  16625. ctx->abort_callback_data = params.abort_callback_data;
  16626. ctx->logits_all = params.logits_all;
  16627. // build worst-case graph for encoder if a model contains encoder
  16628. ctx->is_encoding = llama_model_has_encoder(model);
  16629. uint32_t kv_size = cparams.n_ctx;
  16630. ggml_type type_k = params.type_k;
  16631. ggml_type type_v = params.type_v;
  16632. // Mamba only needs a constant number of KV cache cells per sequence
  16633. if (llama_model_is_recurrent(model)) {
  16634. // Mamba needs at least as many KV cells as there are sequences kept at any time
  16635. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  16636. // it's probably best to keep as much precision as possible for the states
  16637. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  16638. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  16639. }
  16640. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  16641. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  16642. if (!hparams.vocab_only) {
  16643. // initialize backends
  16644. #if defined(GGML_USE_RPC)
  16645. if (model->n_gpu_layers > 0) {
  16646. for (const auto & endpoint : model->rpc_servers) {
  16647. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  16648. if (backend == nullptr) {
  16649. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  16650. llama_free(ctx);
  16651. return nullptr;
  16652. }
  16653. ctx->backends.push_back(backend);
  16654. }
  16655. }
  16656. #endif
  16657. #if defined(GGML_USE_METAL)
  16658. if (model->n_gpu_layers > 0) {
  16659. ctx->backend_metal = ggml_backend_metal_init();
  16660. if (ctx->backend_metal == nullptr) {
  16661. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  16662. llama_free(ctx);
  16663. return nullptr;
  16664. }
  16665. ctx->backends.push_back(ctx->backend_metal);
  16666. }
  16667. #elif defined(GGML_USE_CUDA)
  16668. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16669. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16670. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  16671. if (backend == nullptr) {
  16672. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  16673. llama_free(ctx);
  16674. return nullptr;
  16675. }
  16676. ctx->backends.push_back(backend);
  16677. } else {
  16678. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16679. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  16680. ggml_backend_t backend = ggml_backend_cuda_init(device);
  16681. if (backend == nullptr) {
  16682. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  16683. llama_free(ctx);
  16684. return nullptr;
  16685. }
  16686. ctx->backends.push_back(backend);
  16687. }
  16688. }
  16689. #elif defined(GGML_USE_VULKAN)
  16690. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16691. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  16692. llama_free(ctx);
  16693. return nullptr;
  16694. }
  16695. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  16696. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  16697. if (backend == nullptr) {
  16698. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  16699. llama_free(ctx);
  16700. return nullptr;
  16701. }
  16702. ctx->backends.push_back(backend);
  16703. } else {
  16704. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  16705. ggml_backend_t backend = ggml_backend_vk_init(device);
  16706. if (backend == nullptr) {
  16707. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  16708. llama_free(ctx);
  16709. return nullptr;
  16710. }
  16711. ctx->backends.push_back(backend);
  16712. }
  16713. }
  16714. #elif defined(GGML_USE_SYCL)
  16715. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16716. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16717. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  16718. if (backend == nullptr) {
  16719. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  16720. llama_free(ctx);
  16721. return nullptr;
  16722. }
  16723. ctx->backends.push_back(backend);
  16724. } else {
  16725. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  16726. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  16727. ggml_backend_t backend = ggml_backend_sycl_init(i);
  16728. if (backend == nullptr) {
  16729. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  16730. llama_free(ctx);
  16731. return nullptr;
  16732. }
  16733. ctx->backends.push_back(backend);
  16734. }
  16735. }
  16736. #elif defined(GGML_USE_KOMPUTE)
  16737. if (model->n_gpu_layers > 0) {
  16738. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  16739. if (backend == nullptr) {
  16740. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  16741. llama_free(ctx);
  16742. return nullptr;
  16743. }
  16744. ctx->backends.push_back(backend);
  16745. }
  16746. #elif defined(GGML_USE_CANN)
  16747. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16748. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  16749. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16750. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  16751. if (backend == nullptr) {
  16752. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  16753. llama_free(ctx);
  16754. return nullptr;
  16755. }
  16756. ctx->backends.push_back(backend);
  16757. } else {
  16758. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16759. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  16760. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  16761. ggml_backend_t backend = ggml_backend_cann_init(device);
  16762. if (backend == nullptr) {
  16763. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  16764. llama_free(ctx);
  16765. return nullptr;
  16766. }
  16767. ctx->backends.push_back(backend);
  16768. }
  16769. }
  16770. #endif
  16771. #ifdef GGML_USE_BLAS
  16772. ctx->backend_blas = ggml_backend_blas_init();
  16773. if (ctx->backend_blas == nullptr) {
  16774. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  16775. } else {
  16776. ctx->backends.push_back(ctx->backend_blas);
  16777. }
  16778. #endif
  16779. ctx->backend_cpu = ggml_backend_cpu_init();
  16780. if (ctx->backend_cpu == nullptr) {
  16781. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  16782. llama_free(ctx);
  16783. return nullptr;
  16784. }
  16785. ctx->backends.push_back(ctx->backend_cpu);
  16786. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  16787. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  16788. llama_free(ctx);
  16789. return nullptr;
  16790. }
  16791. {
  16792. size_t memory_size_k = 0;
  16793. size_t memory_size_v = 0;
  16794. for (auto & k : ctx->kv_self.k_l) {
  16795. memory_size_k += ggml_nbytes(k);
  16796. }
  16797. for (auto & v : ctx->kv_self.v_l) {
  16798. memory_size_v += ggml_nbytes(v);
  16799. }
  16800. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  16801. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  16802. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  16803. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  16804. }
  16805. // graph outputs buffer
  16806. {
  16807. // resized during inference when a batch uses more outputs
  16808. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  16809. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  16810. llama_free(ctx);
  16811. return nullptr;
  16812. }
  16813. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  16814. ggml_backend_buffer_name(ctx->buf_output),
  16815. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  16816. }
  16817. // scheduler and compute buffers
  16818. {
  16819. // buffer types used for the compute buffer of each backend
  16820. std::vector<ggml_backend_buffer_type_t> backend_buft;
  16821. for (auto * backend : ctx->backends) {
  16822. if (ggml_backend_is_cpu(backend)) {
  16823. // use host buffers for the CPU backend compute buffer
  16824. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  16825. } else {
  16826. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  16827. }
  16828. }
  16829. const size_t max_nodes = llama_model_max_nodes(*model);
  16830. // buffer used to store the computation graph and the tensor meta data
  16831. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  16832. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  16833. bool pipeline_parallel =
  16834. llama_get_device_count(*model) > 1 &&
  16835. model->n_gpu_layers > (int)model->hparams.n_layer &&
  16836. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  16837. params.offload_kqv;
  16838. #ifndef GGML_USE_CUDA
  16839. // pipeline parallelism requires support for async compute and events
  16840. // currently this is only implemented in the CUDA backend
  16841. pipeline_parallel = false;
  16842. #endif
  16843. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  16844. if (pipeline_parallel) {
  16845. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  16846. }
  16847. // build worst-case graph
  16848. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  16849. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  16850. 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
  16851. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  16852. ggml_cgraph * gf = llama_build_graph(*ctx, ubatch, true);
  16853. // initialize scheduler with the worst-case graph
  16854. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  16855. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  16856. llama_free(ctx);
  16857. return nullptr;
  16858. }
  16859. for (size_t i = 0; i < ctx->backends.size(); i++) {
  16860. ggml_backend_t backend = ctx->backends[i];
  16861. ggml_backend_buffer_type_t buft = backend_buft[i];
  16862. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  16863. if (size > 1) {
  16864. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  16865. ggml_backend_buft_name(buft),
  16866. size / 1024.0 / 1024.0);
  16867. }
  16868. }
  16869. // note: the number of splits during measure is higher than during inference due to the kv shift
  16870. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  16871. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, ggml_graph_n_nodes(gf));
  16872. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  16873. }
  16874. }
  16875. return ctx;
  16876. }
  16877. void llama_free(struct llama_context * ctx) {
  16878. delete ctx;
  16879. }
  16880. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  16881. return ctx->cparams.n_ctx;
  16882. }
  16883. uint32_t llama_n_batch(const struct llama_context * ctx) {
  16884. return ctx->cparams.n_batch;
  16885. }
  16886. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  16887. return ctx->cparams.n_ubatch;
  16888. }
  16889. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  16890. return ctx->kv_self.size;
  16891. }
  16892. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  16893. return model->vocab.type;
  16894. }
  16895. int32_t llama_n_vocab(const struct llama_model * model) {
  16896. return model->hparams.n_vocab;
  16897. }
  16898. int32_t llama_n_ctx_train(const struct llama_model * model) {
  16899. return model->hparams.n_ctx_train;
  16900. }
  16901. int32_t llama_n_embd(const struct llama_model * model) {
  16902. return model->hparams.n_embd;
  16903. }
  16904. int32_t llama_n_layer(const struct llama_model * model) {
  16905. return model->hparams.n_layer;
  16906. }
  16907. int32_t llama_n_head(const struct llama_model * model) {
  16908. return model->hparams.n_head();
  16909. }
  16910. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  16911. return &ctx->model;
  16912. }
  16913. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  16914. return ctx->cparams.pooling_type;
  16915. }
  16916. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  16917. switch (model->arch) {
  16918. // these models do not use RoPE
  16919. case LLM_ARCH_GPT2:
  16920. case LLM_ARCH_GPTJ:
  16921. case LLM_ARCH_MPT:
  16922. case LLM_ARCH_REFACT:
  16923. case LLM_ARCH_BLOOM:
  16924. case LLM_ARCH_MAMBA:
  16925. case LLM_ARCH_JINA_BERT_V2:
  16926. case LLM_ARCH_T5:
  16927. case LLM_ARCH_T5ENCODER:
  16928. case LLM_ARCH_JAIS:
  16929. case LLM_ARCH_RWKV6:
  16930. return LLAMA_ROPE_TYPE_NONE;
  16931. // use what we call a normal RoPE, operating on pairs of consecutive head values
  16932. case LLM_ARCH_LLAMA:
  16933. case LLM_ARCH_MLLAMA:
  16934. case LLM_ARCH_BAICHUAN:
  16935. case LLM_ARCH_STARCODER:
  16936. case LLM_ARCH_PLAMO:
  16937. case LLM_ARCH_ORION:
  16938. case LLM_ARCH_INTERNLM2:
  16939. case LLM_ARCH_MINICPM:
  16940. case LLM_ARCH_XVERSE:
  16941. case LLM_ARCH_COMMAND_R:
  16942. case LLM_ARCH_OLMO:
  16943. case LLM_ARCH_ARCTIC:
  16944. case LLM_ARCH_DEEPSEEK2:
  16945. case LLM_ARCH_CHATGLM:
  16946. case LLM_ARCH_GRANITE:
  16947. case LLM_ARCH_GRANITE_MOE:
  16948. case LLM_ARCH_CHAMELEON:
  16949. case LLM_ARCH_SOLAR:
  16950. return LLAMA_ROPE_TYPE_NORM;
  16951. // the pairs of head values are offset by n_rot/2
  16952. case LLM_ARCH_FALCON:
  16953. case LLM_ARCH_GROK:
  16954. case LLM_ARCH_DBRX:
  16955. case LLM_ARCH_BERT:
  16956. case LLM_ARCH_NOMIC_BERT:
  16957. case LLM_ARCH_STABLELM:
  16958. case LLM_ARCH_BITNET:
  16959. case LLM_ARCH_QWEN:
  16960. case LLM_ARCH_QWEN2:
  16961. case LLM_ARCH_QWEN2MOE:
  16962. case LLM_ARCH_OLMOE:
  16963. case LLM_ARCH_PHI2:
  16964. case LLM_ARCH_PHI3:
  16965. case LLM_ARCH_GEMMA:
  16966. case LLM_ARCH_GEMMA2:
  16967. case LLM_ARCH_STARCODER2:
  16968. case LLM_ARCH_OPENELM:
  16969. case LLM_ARCH_GPTNEOX:
  16970. case LLM_ARCH_CODESHELL:
  16971. case LLM_ARCH_NEMOTRON:
  16972. case LLM_ARCH_EXAONE:
  16973. case LLM_ARCH_MINICPM3:
  16974. return LLAMA_ROPE_TYPE_NEOX;
  16975. // all model arches should be listed explicitly here
  16976. case LLM_ARCH_UNKNOWN:
  16977. GGML_ABORT("unknown architecture");
  16978. }
  16979. return LLAMA_ROPE_TYPE_NONE;
  16980. }
  16981. float llama_rope_freq_scale_train(const struct llama_model * model) {
  16982. return model->hparams.rope_freq_scale_train;
  16983. }
  16984. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  16985. const auto & it = model->gguf_kv.find(key);
  16986. if (it == model->gguf_kv.end()) {
  16987. if (buf_size > 0) {
  16988. buf[0] = '\0';
  16989. }
  16990. return -1;
  16991. }
  16992. return snprintf(buf, buf_size, "%s", it->second.c_str());
  16993. }
  16994. int32_t llama_model_meta_count(const struct llama_model * model) {
  16995. return (int)model->gguf_kv.size();
  16996. }
  16997. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  16998. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  16999. if (buf_size > 0) {
  17000. buf[0] = '\0';
  17001. }
  17002. return -1;
  17003. }
  17004. auto it = model->gguf_kv.begin();
  17005. std::advance(it, i);
  17006. return snprintf(buf, buf_size, "%s", it->first.c_str());
  17007. }
  17008. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  17009. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  17010. if (buf_size > 0) {
  17011. buf[0] = '\0';
  17012. }
  17013. return -1;
  17014. }
  17015. auto it = model->gguf_kv.begin();
  17016. std::advance(it, i);
  17017. return snprintf(buf, buf_size, "%s", it->second.c_str());
  17018. }
  17019. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  17020. return snprintf(buf, buf_size, "%s %s %s",
  17021. llama_model_arch_name(model->arch),
  17022. llama_model_type_name(model->type),
  17023. llama_model_ftype_name(model->ftype).c_str());
  17024. }
  17025. uint64_t llama_model_size(const struct llama_model * model) {
  17026. uint64_t size = 0;
  17027. for (const auto & it : model->tensors_by_name) {
  17028. size += ggml_nbytes(it.second);
  17029. }
  17030. return size;
  17031. }
  17032. uint64_t llama_model_n_params(const struct llama_model * model) {
  17033. uint64_t nparams = 0;
  17034. for (const auto & it : model->tensors_by_name) {
  17035. nparams += ggml_nelements(it.second);
  17036. }
  17037. return nparams;
  17038. }
  17039. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  17040. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  17041. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  17042. return it.first == name;
  17043. });
  17044. if (it == model->tensors_by_name.end()) {
  17045. return nullptr;
  17046. }
  17047. return it->second;
  17048. }
  17049. bool llama_model_has_encoder(const struct llama_model * model) {
  17050. switch (model->arch) {
  17051. case LLM_ARCH_T5: return true;
  17052. case LLM_ARCH_T5ENCODER: return true;
  17053. default: return false;
  17054. }
  17055. }
  17056. bool llama_model_has_decoder(const struct llama_model * model) {
  17057. switch (model->arch) {
  17058. case LLM_ARCH_T5ENCODER: return false;
  17059. default: return true;
  17060. }
  17061. }
  17062. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  17063. return model->hparams.dec_start_token_id;
  17064. }
  17065. bool llama_model_is_recurrent(const struct llama_model * model) {
  17066. switch (model->arch) {
  17067. case LLM_ARCH_MAMBA: return true;
  17068. case LLM_ARCH_RWKV6: return true;
  17069. default: return false;
  17070. }
  17071. }
  17072. uint32_t llama_model_quantize(
  17073. const char * fname_inp,
  17074. const char * fname_out,
  17075. const llama_model_quantize_params * params) {
  17076. try {
  17077. llama_model_quantize_internal(fname_inp, fname_out, params);
  17078. return 0;
  17079. } catch (const std::exception & err) {
  17080. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  17081. return 1;
  17082. }
  17083. }
  17084. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  17085. try {
  17086. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  17087. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  17088. return adapter;
  17089. } catch (const std::exception & err) {
  17090. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  17091. return nullptr;
  17092. }
  17093. }
  17094. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  17095. GGML_ASSERT(cvec.tensors.empty());
  17096. GGML_ASSERT(cvec.ctxs.empty());
  17097. GGML_ASSERT(cvec.bufs.empty());
  17098. // count layer buffer types
  17099. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  17100. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  17101. buft_layer_count[model.buft_layer[i].buft]++;
  17102. }
  17103. // allocate contexts
  17104. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  17105. for (auto & it : buft_layer_count) {
  17106. int n_layers = it.second;
  17107. struct ggml_init_params params = {
  17108. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  17109. /*.mem_buffer =*/ NULL,
  17110. /*.no_alloc =*/ true,
  17111. };
  17112. ggml_context * ctx = ggml_init(params);
  17113. if (!ctx) {
  17114. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  17115. return 1;
  17116. }
  17117. ctx_map[it.first] = ctx;
  17118. }
  17119. // make tensors
  17120. cvec.tensors.reserve(model.hparams.n_layer);
  17121. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  17122. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17123. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  17124. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  17125. cvec.tensors.push_back(tensor);
  17126. }
  17127. // allocate tensors / buffers and zero
  17128. cvec.ctxs.reserve(ctx_map.size());
  17129. cvec.bufs.reserve(ctx_map.size());
  17130. for (auto it : ctx_map) {
  17131. ggml_backend_buffer_type_t buft = it.first;
  17132. ggml_context * ctx = it.second;
  17133. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  17134. if (!buf) {
  17135. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  17136. return false;
  17137. }
  17138. ggml_backend_buffer_clear(buf, 0);
  17139. cvec.ctxs.push_back(ctx);
  17140. cvec.bufs.push_back(buf);
  17141. }
  17142. return true;
  17143. }
  17144. 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) {
  17145. const llama_model & model = lctx->model;
  17146. llama_control_vector & cvec = lctx->cvec;
  17147. if (data == nullptr) {
  17148. // disable the current control vector (but leave allocated for later)
  17149. cvec.layer_start = -1;
  17150. cvec.layer_end = -1;
  17151. return 0;
  17152. }
  17153. if (n_embd != (int) model.hparams.n_embd) {
  17154. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  17155. return 1;
  17156. }
  17157. if (cvec.tensors.empty()) {
  17158. if (!llama_control_vector_init(cvec, model)) {
  17159. return 1;
  17160. }
  17161. }
  17162. cvec.layer_start = il_start;
  17163. cvec.layer_end = il_end;
  17164. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  17165. assert(cvec.tensors[il] != nullptr);
  17166. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  17167. if (off + n_embd <= len) {
  17168. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  17169. }
  17170. }
  17171. return 0;
  17172. }
  17173. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  17174. struct llama_kv_cache_view result = {
  17175. /*.n_cells = */ 0,
  17176. /*.n_seq_max = */ n_seq_max,
  17177. /*.token_count = */ 0,
  17178. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  17179. /*.max_contiguous = */ 0,
  17180. /*.max_contiguous_idx = */ -1,
  17181. /*.cells = */ nullptr,
  17182. /*.cells_sequences = */ nullptr,
  17183. };
  17184. return result;
  17185. }
  17186. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  17187. if (view->cells != nullptr) {
  17188. free(view->cells);
  17189. view->cells = nullptr;
  17190. }
  17191. if (view->cells_sequences != nullptr) {
  17192. free(view->cells_sequences);
  17193. view->cells_sequences = nullptr;
  17194. }
  17195. }
  17196. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  17197. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  17198. view->n_cells = int32_t(ctx->kv_self.size);
  17199. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  17200. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  17201. view->cells = (struct llama_kv_cache_view_cell *)p;
  17202. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  17203. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  17204. view->cells_sequences = (llama_seq_id *)p;
  17205. }
  17206. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  17207. llama_kv_cache_view_cell * c_curr = view->cells;
  17208. llama_seq_id * cs_curr = view->cells_sequences;
  17209. int32_t used_cells = 0;
  17210. int32_t token_count = 0;
  17211. int32_t curr_contig_idx = -1;
  17212. uint32_t max_contig = 0;
  17213. int32_t max_contig_idx = -1;
  17214. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  17215. const size_t curr_size = kv_cells[i].seq_id.size();
  17216. token_count += curr_size;
  17217. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  17218. if (curr_size > 0) {
  17219. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  17220. max_contig = i - curr_contig_idx;
  17221. max_contig_idx = curr_contig_idx;
  17222. }
  17223. curr_contig_idx = -1;
  17224. } else if (curr_contig_idx < 0) {
  17225. curr_contig_idx = i;
  17226. }
  17227. int seq_idx = 0;
  17228. for (const llama_seq_id it : kv_cells[i].seq_id) {
  17229. if (seq_idx >= view->n_seq_max) {
  17230. break;
  17231. }
  17232. cs_curr[seq_idx] = it;
  17233. seq_idx++;
  17234. }
  17235. if (seq_idx != 0) {
  17236. used_cells++;
  17237. }
  17238. for (; seq_idx < view->n_seq_max; seq_idx++) {
  17239. cs_curr[seq_idx] = -1;
  17240. }
  17241. }
  17242. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  17243. max_contig_idx = curr_contig_idx;
  17244. max_contig = kv_cells.size() - curr_contig_idx;
  17245. }
  17246. view->max_contiguous = max_contig;
  17247. view->max_contiguous_idx = max_contig_idx;
  17248. view->token_count = token_count;
  17249. view->used_cells = used_cells;
  17250. if (uint32_t(used_cells) != ctx->kv_self.used) {
  17251. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  17252. __func__, ctx->kv_self.used, used_cells);
  17253. }
  17254. }
  17255. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  17256. int result = 0;
  17257. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  17258. result += ctx->kv_self.cells[i].seq_id.size();
  17259. }
  17260. return result;
  17261. }
  17262. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  17263. return ctx->kv_self.used;
  17264. }
  17265. void llama_kv_cache_clear(struct llama_context * ctx) {
  17266. llama_kv_cache_clear(ctx->kv_self);
  17267. }
  17268. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  17269. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  17270. }
  17271. 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) {
  17272. if (seq_id_src == seq_id_dst) {
  17273. return;
  17274. }
  17275. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  17276. }
  17277. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  17278. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  17279. }
  17280. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  17281. if (delta == 0) {
  17282. return;
  17283. }
  17284. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  17285. }
  17286. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  17287. if (d == 1) {
  17288. return;
  17289. }
  17290. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  17291. }
  17292. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  17293. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  17294. }
  17295. void llama_kv_cache_defrag(struct llama_context * ctx) {
  17296. llama_kv_cache_defrag(ctx->kv_self);
  17297. }
  17298. void llama_kv_cache_update(struct llama_context * ctx) {
  17299. llama_kv_cache_update_internal(*ctx);
  17300. }
  17301. // deprecated
  17302. size_t llama_get_state_size(struct llama_context * ctx) {
  17303. return llama_state_get_size(ctx);
  17304. }
  17305. // deprecated
  17306. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  17307. return llama_state_get_data(ctx, dst, -1);
  17308. }
  17309. // deprecated
  17310. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  17311. return llama_state_set_data(ctx, src, -1);
  17312. }
  17313. // deprecated
  17314. 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) {
  17315. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17316. }
  17317. // deprecated
  17318. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17319. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  17320. }
  17321. // TODO: replace all non-fatal assertions with returned errors or exceptions
  17322. struct llama_data_write {
  17323. virtual void write(const void * src, size_t size) = 0;
  17324. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  17325. virtual size_t get_size_written() = 0;
  17326. virtual ~llama_data_write() = default;
  17327. void write_string(const std::string & str) {
  17328. uint32_t str_size = str.size();
  17329. write(&str_size, sizeof(str_size));
  17330. write(str.data(), str_size);
  17331. }
  17332. void write_model_info(const struct llama_context * ctx) {
  17333. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17334. write_string(arch_str);
  17335. // TODO: add more model-specific info which should prevent loading the session file if not identical
  17336. }
  17337. //void write_rng(const std::mt19937 & rng) {
  17338. // std::ostringstream rng_ss;
  17339. // rng_ss << rng;
  17340. // const std::string & rng_str = rng_ss.str();
  17341. // write_string(rng_str);
  17342. //}
  17343. void write_output_ids(struct llama_context * ctx) {
  17344. llama_output_reorder(ctx);
  17345. const uint32_t n_outputs = ctx->n_outputs;
  17346. std::vector<int32_t> output_pos;
  17347. const size_t n_batch = ctx->cparams.n_batch;
  17348. const auto & output_ids = ctx->output_ids;
  17349. GGML_ASSERT(n_outputs <= ctx->output_size);
  17350. output_pos.resize(n_outputs);
  17351. // build a more compact representation of the output ids
  17352. for (size_t i = 0; i < n_batch; ++i) {
  17353. // map an output id to a position in the batch
  17354. int32_t pos = output_ids[i];
  17355. if (pos >= 0) {
  17356. GGML_ASSERT((uint32_t) pos < n_outputs);
  17357. output_pos[pos] = i;
  17358. }
  17359. }
  17360. write(&n_outputs, sizeof(n_outputs));
  17361. if (n_outputs) {
  17362. write(output_pos.data(), n_outputs * sizeof(int32_t));
  17363. }
  17364. }
  17365. void write_logits(const struct llama_context * ctx) {
  17366. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  17367. write(&logits_size, sizeof(logits_size));
  17368. if (logits_size) {
  17369. write(ctx->logits, logits_size * sizeof(float));
  17370. }
  17371. }
  17372. void write_embeddings(const struct llama_context * ctx) {
  17373. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  17374. write(&embeddings_size, sizeof(embeddings_size));
  17375. if (embeddings_size) {
  17376. write(ctx->embd, embeddings_size * sizeof(float));
  17377. }
  17378. }
  17379. 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) {
  17380. for (const auto & range : cell_ranges) {
  17381. for (uint32_t i = range.first; i < range.second; ++i) {
  17382. const auto & cell = kv_self.cells[i];
  17383. const llama_pos pos = cell.pos;
  17384. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  17385. write(&pos, sizeof(pos));
  17386. write(&n_seq_id, sizeof(n_seq_id));
  17387. if (n_seq_id) {
  17388. for (auto seq_id : cell.seq_id) {
  17389. write(&seq_id, sizeof(seq_id));
  17390. }
  17391. }
  17392. }
  17393. }
  17394. }
  17395. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  17396. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17397. const struct llama_hparams & hparams = ctx->model.hparams;
  17398. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  17399. const uint32_t n_layer = hparams.n_layer;
  17400. write(&v_trans, sizeof(v_trans));
  17401. write(&n_layer, sizeof(n_layer));
  17402. std::vector<uint8_t> tmp_buf;
  17403. // Iterate and write all the keys first, each row is a cell
  17404. // Get whole range at a time
  17405. for (uint32_t il = 0; il < n_layer; ++il) {
  17406. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17407. // Write key type
  17408. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17409. write(&k_type_i, sizeof(k_type_i));
  17410. // Write row size of key
  17411. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17412. write(&k_size_row, sizeof(k_size_row));
  17413. // Read each range of cells of k_size length each into tmp_buf and write out
  17414. for (const auto & range : cell_ranges) {
  17415. const size_t range_size = range.second - range.first;
  17416. const size_t buf_size = range_size * k_size_row;
  17417. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  17418. }
  17419. }
  17420. if (!kv_self.v_trans) {
  17421. for (uint32_t il = 0; il < n_layer; ++il) {
  17422. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17423. // Write value type
  17424. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17425. write(&v_type_i, sizeof(v_type_i));
  17426. // Write row size of value
  17427. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17428. write(&v_size_row, sizeof(v_size_row));
  17429. // Read each range of cells of v_size length each into tmp_buf and write out
  17430. for (const auto & range : cell_ranges) {
  17431. const size_t range_size = range.second - range.first;
  17432. const size_t buf_size = range_size * v_size_row;
  17433. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  17434. }
  17435. }
  17436. } else {
  17437. // When v is transposed, we also need the element size and get the element ranges from each row
  17438. const uint32_t kv_size = kv_self.size;
  17439. for (uint32_t il = 0; il < n_layer; ++il) {
  17440. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17441. // Write value type
  17442. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17443. write(&v_type_i, sizeof(v_type_i));
  17444. // Write element size
  17445. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17446. write(&v_size_el, sizeof(v_size_el));
  17447. // Write GQA embedding size
  17448. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  17449. // For each row, we get the element values of each cell
  17450. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17451. // Read each range of cells of v_size_el length each into tmp_buf and write out
  17452. for (const auto & range : cell_ranges) {
  17453. const size_t range_size = range.second - range.first;
  17454. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  17455. const size_t buf_size = range_size * v_size_el;
  17456. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  17457. }
  17458. }
  17459. }
  17460. }
  17461. }
  17462. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17463. const struct llama_kv_cache & kv_self = ctx->kv_self;
  17464. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  17465. uint32_t cell_count = 0;
  17466. // Count the number of cells with the specified seq_id
  17467. // Find all the ranges of cells with this seq id (or all, when -1)
  17468. uint32_t cell_range_begin = kv_self.size;
  17469. for (uint32_t i = 0; i < kv_self.size; ++i) {
  17470. const auto & cell = kv_self.cells[i];
  17471. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  17472. ++cell_count;
  17473. if (cell_range_begin == kv_self.size) {
  17474. cell_range_begin = i;
  17475. }
  17476. } else {
  17477. if (cell_range_begin != kv_self.size) {
  17478. cell_ranges.emplace_back(cell_range_begin, i);
  17479. cell_range_begin = kv_self.size;
  17480. }
  17481. }
  17482. }
  17483. if (cell_range_begin != kv_self.size) {
  17484. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  17485. }
  17486. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  17487. uint32_t cell_count_check = 0;
  17488. for (const auto & range : cell_ranges) {
  17489. cell_count_check += range.second - range.first;
  17490. }
  17491. GGML_ASSERT(cell_count == cell_count_check);
  17492. write(&cell_count, sizeof(cell_count));
  17493. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  17494. write_kv_cache_data(ctx, cell_ranges);
  17495. }
  17496. };
  17497. struct llama_data_read {
  17498. virtual const uint8_t * read(size_t size) = 0;
  17499. virtual void read_to(void * dst, size_t size) = 0;
  17500. virtual size_t get_size_read() = 0;
  17501. virtual ~llama_data_read() = default;
  17502. void read_string(std::string & str) {
  17503. uint32_t str_size;
  17504. read_to(&str_size, sizeof(str_size));
  17505. str.assign((const char *) read(str_size), str_size);
  17506. }
  17507. // validate model information
  17508. void read_model_info(const struct llama_context * ctx) {
  17509. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  17510. std::string arch_str;
  17511. read_string(arch_str);
  17512. if (cur_arch_str != arch_str) {
  17513. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  17514. }
  17515. // TODO: add more info which needs to be identical but which is not verified otherwise
  17516. }
  17517. //void read_rng(std::mt19937 & rng) {
  17518. // std::string rng_str;
  17519. // read_string(rng_str);
  17520. // std::istringstream rng_ss(rng_str);
  17521. // rng_ss >> rng;
  17522. // if (rng_ss.fail()) {
  17523. // throw std::runtime_error("failed to load RNG state");
  17524. // }
  17525. //}
  17526. void read_output_ids(struct llama_context * ctx) {
  17527. std::vector<int32_t> output_pos;
  17528. uint32_t n_outputs;
  17529. read_to(&n_outputs, sizeof(n_outputs));
  17530. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  17531. throw std::runtime_error("could not reserve outputs");
  17532. }
  17533. if (n_outputs) {
  17534. output_pos.resize(n_outputs);
  17535. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  17536. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  17537. int32_t id = output_pos[i];
  17538. if ((uint32_t) id >= ctx->cparams.n_batch) {
  17539. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  17540. }
  17541. ctx->output_ids[id] = i;
  17542. }
  17543. ctx->n_outputs = n_outputs;
  17544. }
  17545. }
  17546. void read_logits(struct llama_context * ctx) {
  17547. uint64_t logits_size;
  17548. read_to(&logits_size, sizeof(logits_size));
  17549. if (ctx->logits_size < logits_size) {
  17550. throw std::runtime_error("logits buffer too small");
  17551. }
  17552. if (logits_size) {
  17553. read_to(ctx->logits, logits_size * sizeof(float));
  17554. }
  17555. }
  17556. void read_embeddings(struct llama_context * ctx) {
  17557. uint64_t embeddings_size;
  17558. read_to(&embeddings_size, sizeof(embeddings_size));
  17559. if (ctx->embd_size < embeddings_size) {
  17560. throw std::runtime_error("embeddings buffer too small");
  17561. }
  17562. if (embeddings_size) {
  17563. read_to(ctx->embd, embeddings_size * sizeof(float));
  17564. }
  17565. }
  17566. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  17567. struct llama_kv_cache & kv_self = ctx->kv_self;
  17568. if (dest_seq_id != -1) {
  17569. // single sequence
  17570. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  17571. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  17572. batch.n_tokens = cell_count;
  17573. batch.n_seq_tokens = cell_count;
  17574. batch.n_seqs = 1;
  17575. for (uint32_t i = 0; i < cell_count; ++i) {
  17576. llama_pos pos;
  17577. uint32_t n_seq_id;
  17578. read_to(&pos, sizeof(pos));
  17579. read_to(&n_seq_id, sizeof(n_seq_id));
  17580. if (n_seq_id != 0) {
  17581. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  17582. return false;
  17583. }
  17584. batch.pos[i] = pos;
  17585. }
  17586. batch.n_seq_id[0] = 1;
  17587. batch.seq_id[0] = &dest_seq_id;
  17588. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  17589. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  17590. return false;
  17591. }
  17592. // 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)
  17593. // Assume that this is one contiguous block of cells
  17594. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  17595. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  17596. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  17597. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  17598. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  17599. } else {
  17600. // whole KV cache restore
  17601. if (cell_count > kv_self.size) {
  17602. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  17603. return false;
  17604. }
  17605. llama_kv_cache_clear(kv_self);
  17606. for (uint32_t i = 0; i < cell_count; ++i) {
  17607. llama_kv_cell & cell = kv_self.cells[i];
  17608. llama_pos pos;
  17609. uint32_t n_seq_id;
  17610. read_to(&pos, sizeof(pos));
  17611. read_to(&n_seq_id, sizeof(n_seq_id));
  17612. cell.pos = pos;
  17613. for (uint32_t j = 0; j < n_seq_id; ++j) {
  17614. llama_seq_id seq_id;
  17615. read_to(&seq_id, sizeof(seq_id));
  17616. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  17617. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  17618. return false;
  17619. }
  17620. cell.seq_id.insert(seq_id);
  17621. if (kv_self.recurrent) {
  17622. int32_t & tail = kv_self.cells[seq_id].tail;
  17623. if (tail != -1) {
  17624. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  17625. return false;
  17626. }
  17627. tail = i;
  17628. }
  17629. }
  17630. }
  17631. kv_self.head = 0;
  17632. kv_self.used = cell_count;
  17633. }
  17634. if (kv_self.recurrent) {
  17635. for (uint32_t i = 0; i < cell_count; ++i) {
  17636. uint32_t cell_id = kv_self.head + i;
  17637. // make sure the recurrent states will keep their restored state
  17638. kv_self.cells[cell_id].src = cell_id;
  17639. }
  17640. }
  17641. return true;
  17642. }
  17643. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  17644. const struct llama_hparams & hparams = ctx->model.hparams;
  17645. struct llama_kv_cache & kv_self = ctx->kv_self;
  17646. uint32_t v_trans;
  17647. uint32_t n_layer;
  17648. read_to(&v_trans, sizeof(v_trans));
  17649. read_to(&n_layer, sizeof(n_layer));
  17650. if (n_layer != hparams.n_layer) {
  17651. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  17652. return false;
  17653. }
  17654. if (cell_count > kv_self.size) {
  17655. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  17656. return false;
  17657. }
  17658. if (kv_self.v_trans != (bool) v_trans) {
  17659. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  17660. return false;
  17661. }
  17662. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  17663. for (uint32_t il = 0; il < n_layer; ++il) {
  17664. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17665. // Read type of key
  17666. int32_t k_type_i_ref;
  17667. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  17668. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17669. if (k_type_i != k_type_i_ref) {
  17670. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  17671. return false;
  17672. }
  17673. // Read row size of key
  17674. uint64_t k_size_row_ref;
  17675. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  17676. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17677. if (k_size_row != k_size_row_ref) {
  17678. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  17679. return false;
  17680. }
  17681. if (cell_count) {
  17682. // Read and set the keys for the whole cell range
  17683. 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);
  17684. }
  17685. }
  17686. if (!kv_self.v_trans) {
  17687. for (uint32_t il = 0; il < n_layer; ++il) {
  17688. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17689. // Read type of value
  17690. int32_t v_type_i_ref;
  17691. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17692. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17693. if (v_type_i != v_type_i_ref) {
  17694. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17695. return false;
  17696. }
  17697. // Read row size of value
  17698. uint64_t v_size_row_ref;
  17699. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  17700. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17701. if (v_size_row != v_size_row_ref) {
  17702. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  17703. return false;
  17704. }
  17705. if (cell_count) {
  17706. // Read and set the values for the whole cell range
  17707. 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);
  17708. }
  17709. }
  17710. } else {
  17711. // For each layer, read the values for each cell (transposed)
  17712. for (uint32_t il = 0; il < n_layer; ++il) {
  17713. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17714. // Read type of value
  17715. int32_t v_type_i_ref;
  17716. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17717. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17718. if (v_type_i != v_type_i_ref) {
  17719. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17720. return false;
  17721. }
  17722. // Read element size of value
  17723. uint32_t v_size_el_ref;
  17724. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  17725. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17726. if (v_size_el != v_size_el_ref) {
  17727. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  17728. return false;
  17729. }
  17730. // Read GQA embedding size
  17731. uint32_t n_embd_v_gqa_ref;
  17732. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  17733. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  17734. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  17735. return false;
  17736. }
  17737. if (cell_count) {
  17738. // For each row in the transposed matrix, read the values for the whole cell range
  17739. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17740. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  17741. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  17742. }
  17743. }
  17744. }
  17745. }
  17746. return true;
  17747. }
  17748. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17749. uint32_t cell_count;
  17750. read_to(&cell_count, sizeof(cell_count));
  17751. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  17752. if (!res) {
  17753. if (seq_id == -1) {
  17754. llama_kv_cache_clear(ctx);
  17755. } else {
  17756. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  17757. }
  17758. throw std::runtime_error("failed to restore kv cache");
  17759. }
  17760. }
  17761. };
  17762. struct llama_data_write_dummy : llama_data_write {
  17763. size_t size_written = 0;
  17764. llama_data_write_dummy() {}
  17765. void write(const void * /* src */, size_t size) override {
  17766. size_written += size;
  17767. }
  17768. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  17769. size_written += size;
  17770. }
  17771. size_t get_size_written() override {
  17772. return size_written;
  17773. }
  17774. };
  17775. struct llama_data_write_buffer : llama_data_write {
  17776. uint8_t * ptr;
  17777. size_t buf_size = 0;
  17778. size_t size_written = 0;
  17779. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17780. void write(const void * src, size_t size) override {
  17781. if (size > buf_size) {
  17782. throw std::runtime_error("unexpectedly reached end of buffer");
  17783. }
  17784. memcpy(ptr, src, size);
  17785. ptr += size;
  17786. size_written += size;
  17787. buf_size -= size;
  17788. }
  17789. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17790. if (size > buf_size) {
  17791. throw std::runtime_error("unexpectedly reached end of buffer");
  17792. }
  17793. ggml_backend_tensor_get(tensor, ptr, offset, size);
  17794. ptr += size;
  17795. size_written += size;
  17796. buf_size -= size;
  17797. }
  17798. size_t get_size_written() override {
  17799. return size_written;
  17800. }
  17801. };
  17802. struct llama_data_read_buffer : llama_data_read {
  17803. const uint8_t * ptr;
  17804. size_t buf_size = 0;
  17805. size_t size_read = 0;
  17806. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17807. const uint8_t * read(size_t size) override {
  17808. const uint8_t * base_ptr = ptr;
  17809. if (size > buf_size) {
  17810. throw std::runtime_error("unexpectedly reached end of buffer");
  17811. }
  17812. ptr += size;
  17813. size_read += size;
  17814. buf_size -= size;
  17815. return base_ptr;
  17816. }
  17817. void read_to(void * dst, size_t size) override {
  17818. memcpy(dst, read(size), size);
  17819. }
  17820. size_t get_size_read() override {
  17821. return size_read;
  17822. }
  17823. };
  17824. struct llama_data_write_file : llama_data_write {
  17825. llama_file * file;
  17826. size_t size_written = 0;
  17827. std::vector<uint8_t> temp_buffer;
  17828. llama_data_write_file(llama_file * f) : file(f) {}
  17829. void write(const void * src, size_t size) override {
  17830. file->write_raw(src, size);
  17831. size_written += size;
  17832. }
  17833. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17834. temp_buffer.resize(size);
  17835. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  17836. write(temp_buffer.data(), temp_buffer.size());
  17837. }
  17838. size_t get_size_written() override {
  17839. return size_written;
  17840. }
  17841. };
  17842. struct llama_data_read_file : llama_data_read {
  17843. llama_file * file;
  17844. size_t size_read = 0;
  17845. std::vector<uint8_t> temp_buffer;
  17846. llama_data_read_file(llama_file * f) : file(f) {}
  17847. void read_to(void * dst, size_t size) override {
  17848. file->read_raw(dst, size);
  17849. size_read += size;
  17850. }
  17851. const uint8_t * read(size_t size) override {
  17852. temp_buffer.resize(size);
  17853. read_to(temp_buffer.data(), size);
  17854. return temp_buffer.data();
  17855. }
  17856. size_t get_size_read() override {
  17857. return size_read;
  17858. }
  17859. };
  17860. /** copy state data into either a buffer or file depending on the passed in context
  17861. *
  17862. * file context:
  17863. * llama_file file("/path", "wb");
  17864. * llama_data_write_file data_ctx(&file);
  17865. * llama_state_get_data_internal(ctx, data_ctx);
  17866. *
  17867. * buffer context:
  17868. * std::vector<uint8_t> buf(max_size, 0);
  17869. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  17870. * llama_state_get_data_internal(ctx, data_ctx);
  17871. *
  17872. */
  17873. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  17874. llama_synchronize(ctx);
  17875. data_ctx.write_model_info(ctx);
  17876. // copy outputs
  17877. data_ctx.write_output_ids(ctx);
  17878. data_ctx.write_logits(ctx);
  17879. data_ctx.write_embeddings(ctx);
  17880. data_ctx.write_kv_cache(ctx);
  17881. return data_ctx.get_size_written();
  17882. }
  17883. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  17884. llama_data_write_buffer data_ctx(dst, size);
  17885. try {
  17886. return llama_state_get_data_internal(ctx, data_ctx);
  17887. } catch (const std::exception & err) {
  17888. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  17889. return 0;
  17890. }
  17891. }
  17892. // Returns the *actual* size of the state.
  17893. // Intended to be used when saving to state to a buffer.
  17894. size_t llama_state_get_size(struct llama_context * ctx) {
  17895. llama_data_write_dummy data_ctx;
  17896. try {
  17897. return llama_state_get_data_internal(ctx, data_ctx);
  17898. } catch (const std::exception & err) {
  17899. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  17900. return 0;
  17901. }
  17902. }
  17903. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  17904. llama_synchronize(ctx);
  17905. data_ctx.read_model_info(ctx);
  17906. // set outputs
  17907. data_ctx.read_output_ids(ctx);
  17908. data_ctx.read_logits(ctx);
  17909. data_ctx.read_embeddings(ctx);
  17910. data_ctx.read_kv_cache(ctx);
  17911. return data_ctx.get_size_read();
  17912. }
  17913. // Sets the state reading from the specified source address
  17914. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  17915. llama_data_read_buffer data_ctx(src, size);
  17916. try {
  17917. return llama_state_set_data_internal(ctx, data_ctx);
  17918. } catch (const std::exception & err) {
  17919. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  17920. return 0;
  17921. }
  17922. }
  17923. 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) {
  17924. llama_file file(path_session, "rb");
  17925. // sanity checks
  17926. {
  17927. const uint32_t magic = file.read_u32();
  17928. const uint32_t version = file.read_u32();
  17929. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  17930. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  17931. return false;
  17932. }
  17933. }
  17934. // load the prompt
  17935. {
  17936. const uint32_t n_token_count = file.read_u32();
  17937. if (n_token_count > n_token_capacity) {
  17938. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  17939. return false;
  17940. }
  17941. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  17942. *n_token_count_out = n_token_count;
  17943. }
  17944. // restore the context state
  17945. {
  17946. const size_t n_state_size_cur = file.size - file.tell();
  17947. llama_data_read_file data_ctx(&file);
  17948. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  17949. if (n_read != n_state_size_cur) {
  17950. 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);
  17951. return false;
  17952. }
  17953. }
  17954. return true;
  17955. }
  17956. 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) {
  17957. try {
  17958. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17959. } catch (const std::exception & err) {
  17960. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  17961. return false;
  17962. }
  17963. }
  17964. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17965. llama_file file(path_session, "wb");
  17966. file.write_u32(LLAMA_SESSION_MAGIC);
  17967. file.write_u32(LLAMA_SESSION_VERSION);
  17968. // save the prompt
  17969. file.write_u32((uint32_t) n_token_count);
  17970. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  17971. // save the context state using stream saving
  17972. llama_data_write_file data_ctx(&file);
  17973. llama_state_get_data_internal(ctx, data_ctx);
  17974. return true;
  17975. }
  17976. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17977. try {
  17978. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  17979. } catch (const std::exception & err) {
  17980. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  17981. return false;
  17982. }
  17983. }
  17984. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  17985. llama_synchronize(ctx);
  17986. data_ctx.write_kv_cache(ctx, seq_id);
  17987. return data_ctx.get_size_written();
  17988. }
  17989. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  17990. llama_data_write_dummy data_ctx;
  17991. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  17992. }
  17993. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  17994. llama_data_write_buffer data_ctx(dst, size);
  17995. try {
  17996. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  17997. } catch (const std::exception & err) {
  17998. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  17999. return 0;
  18000. }
  18001. }
  18002. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  18003. llama_synchronize(ctx);
  18004. data_ctx.read_kv_cache(ctx, dest_seq_id);
  18005. return data_ctx.get_size_read();
  18006. }
  18007. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  18008. llama_data_read_buffer data_ctx(src, size);
  18009. try {
  18010. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18011. } catch (const std::exception & err) {
  18012. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  18013. return 0;
  18014. }
  18015. }
  18016. 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) {
  18017. llama_file file(filepath, "wb");
  18018. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  18019. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  18020. // save the prompt
  18021. file.write_u32((uint32_t) n_token_count);
  18022. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  18023. // save the context state using stream saving
  18024. llama_data_write_file data_ctx(&file);
  18025. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  18026. const size_t res = file.tell();
  18027. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  18028. return res;
  18029. }
  18030. 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) {
  18031. llama_file file(filepath, "rb");
  18032. // version checks
  18033. {
  18034. const uint32_t magic = file.read_u32();
  18035. const uint32_t version = file.read_u32();
  18036. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  18037. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  18038. return 0;
  18039. }
  18040. }
  18041. // load the prompt
  18042. {
  18043. const uint32_t n_token_count = file.read_u32();
  18044. if (n_token_count > n_token_capacity) {
  18045. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  18046. return 0;
  18047. }
  18048. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  18049. *n_token_count_out = n_token_count;
  18050. }
  18051. // restore the context state
  18052. {
  18053. const size_t state_size = file.size - file.tell();
  18054. llama_data_read_file data_ctx(&file);
  18055. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  18056. if (!nread) {
  18057. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  18058. return 0;
  18059. }
  18060. GGML_ASSERT(nread <= state_size);
  18061. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  18062. }
  18063. return file.tell();
  18064. }
  18065. 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) {
  18066. try {
  18067. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  18068. } catch (const std::exception & err) {
  18069. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  18070. return 0;
  18071. }
  18072. }
  18073. 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) {
  18074. try {
  18075. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  18076. } catch (const std::exception & err) {
  18077. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  18078. return 0;
  18079. }
  18080. }
  18081. void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  18082. ctx->cparams.n_threads = n_threads;
  18083. ctx->cparams.n_threads_batch = n_threads_batch;
  18084. }
  18085. int32_t llama_n_threads(struct llama_context * ctx) {
  18086. return ctx->cparams.n_threads;
  18087. }
  18088. int32_t llama_n_threads_batch(struct llama_context * ctx) {
  18089. return ctx->cparams.n_threads_batch;
  18090. }
  18091. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  18092. ctx->abort_callback = abort_callback;
  18093. ctx->abort_callback_data = abort_callback_data;
  18094. }
  18095. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  18096. ctx->cparams.embeddings = embeddings;
  18097. }
  18098. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  18099. ctx->cparams.causal_attn = causal_attn;
  18100. }
  18101. void llama_set_cross_attention(struct llama_context * ctx, bool cross_attention) {
  18102. ctx->cparams.cross_attn = cross_attention;
  18103. }
  18104. struct llama_batch llama_batch_get_one(
  18105. llama_token * tokens,
  18106. int32_t n_tokens,
  18107. llama_pos pos_0,
  18108. llama_seq_id seq_id) {
  18109. return {
  18110. /*n_tokens =*/ n_tokens,
  18111. /*tokens =*/ tokens,
  18112. /*embd =*/ nullptr,
  18113. /*n_embd =*/ 0,
  18114. /*pos =*/ nullptr,
  18115. /*n_seq_id =*/ nullptr,
  18116. /*seq_id =*/ nullptr,
  18117. /*logits =*/ nullptr,
  18118. /*all_pos_0 =*/ pos_0,
  18119. /*all_pos_1 =*/ 1,
  18120. /*all_seq_id =*/ seq_id,
  18121. };
  18122. }
  18123. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  18124. llama_batch batch = {
  18125. /*n_tokens =*/ 0,
  18126. /*tokens =*/ nullptr,
  18127. /*embd =*/ nullptr,
  18128. /*n_embd =*/ 0,
  18129. /*pos =*/ nullptr,
  18130. /*n_seq_id =*/ nullptr,
  18131. /*seq_id =*/ nullptr,
  18132. /*logits =*/ nullptr,
  18133. /*all_pos_0 =*/ 0,
  18134. /*all_pos_1 =*/ 0,
  18135. /*all_seq_id =*/ 0,
  18136. };
  18137. if (embd) {
  18138. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  18139. batch.n_embd = embd;
  18140. } else {
  18141. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  18142. }
  18143. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  18144. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  18145. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  18146. for (int i = 0; i < n_tokens_alloc; ++i) {
  18147. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  18148. }
  18149. batch.seq_id[n_tokens_alloc] = nullptr;
  18150. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  18151. return batch;
  18152. }
  18153. void llama_batch_free(struct llama_batch batch) {
  18154. if (batch.token) free(batch.token);
  18155. if (batch.embd) free(batch.embd);
  18156. if (batch.pos) free(batch.pos);
  18157. if (batch.n_seq_id) free(batch.n_seq_id);
  18158. if (batch.seq_id) {
  18159. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  18160. free(batch.seq_id[i]);
  18161. }
  18162. free(batch.seq_id);
  18163. }
  18164. if (batch.logits) free(batch.logits);
  18165. }
  18166. int32_t llama_encode(
  18167. struct llama_context * ctx,
  18168. struct llama_batch batch) {
  18169. const int ret = llama_encode_internal(*ctx, batch);
  18170. if (ret < 0) {
  18171. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  18172. }
  18173. return ret;
  18174. }
  18175. int32_t llama_decode(
  18176. struct llama_context * ctx,
  18177. struct llama_batch batch) {
  18178. const int ret = llama_decode_internal(*ctx, batch);
  18179. if (ret < 0) {
  18180. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  18181. }
  18182. return ret;
  18183. }
  18184. void llama_synchronize(struct llama_context * ctx) {
  18185. ggml_backend_sched_synchronize(ctx->sched);
  18186. // FIXME: if multiple single tokens are evaluated without a synchronization,
  18187. // the stats will be added to the prompt evaluation stats
  18188. // this should only happen when using batch size 1 to evaluate a batch
  18189. // add the evaluation to the stats
  18190. if (ctx->n_queued_tokens == 1) {
  18191. if (!ctx->cparams.no_perf) {
  18192. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18193. }
  18194. ctx->n_eval++;
  18195. } else if (ctx->n_queued_tokens > 1) {
  18196. if (!ctx->cparams.no_perf) {
  18197. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  18198. }
  18199. ctx->n_p_eval += ctx->n_queued_tokens;
  18200. }
  18201. // get a more accurate load time, upon first eval
  18202. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  18203. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  18204. ctx->has_evaluated_once = true;
  18205. }
  18206. ctx->n_queued_tokens = 0;
  18207. ctx->t_compute_start_us = 0;
  18208. }
  18209. float * llama_get_logits(struct llama_context * ctx) {
  18210. llama_synchronize(ctx);
  18211. // reorder logits for backward compatibility
  18212. // TODO: maybe deprecate this
  18213. llama_output_reorder(ctx);
  18214. return ctx->logits;
  18215. }
  18216. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  18217. int32_t j = -1;
  18218. llama_synchronize(ctx);
  18219. try {
  18220. if (ctx->logits == nullptr) {
  18221. throw std::runtime_error("no logits");
  18222. }
  18223. if (i < 0) {
  18224. j = ctx->n_outputs + i;
  18225. if (j < 0) {
  18226. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18227. }
  18228. } else if ((size_t) i >= ctx->output_ids.size()) {
  18229. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  18230. } else {
  18231. j = ctx->output_ids[i];
  18232. }
  18233. if (j < 0) {
  18234. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18235. }
  18236. if (j >= ctx->n_outputs) {
  18237. // This should not happen
  18238. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18239. }
  18240. return ctx->logits + j*ctx->model.hparams.n_vocab;
  18241. } catch (const std::exception & err) {
  18242. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  18243. #ifndef NDEBUG
  18244. GGML_ABORT("fatal error");
  18245. #else
  18246. return nullptr;
  18247. #endif
  18248. }
  18249. }
  18250. float * llama_get_embeddings(struct llama_context * ctx) {
  18251. llama_synchronize(ctx);
  18252. // reorder embeddings for backward compatibility
  18253. // TODO: maybe deprecate this
  18254. llama_output_reorder(ctx);
  18255. return ctx->embd;
  18256. }
  18257. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  18258. int32_t j = -1;
  18259. llama_synchronize(ctx);
  18260. try {
  18261. if (ctx->embd == nullptr) {
  18262. throw std::runtime_error("no embeddings");
  18263. }
  18264. if (i < 0) {
  18265. j = ctx->n_outputs + i;
  18266. if (j < 0) {
  18267. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  18268. }
  18269. } else if ((size_t) i >= ctx->output_ids.size()) {
  18270. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  18271. } else {
  18272. j = ctx->output_ids[i];
  18273. }
  18274. if (j < 0) {
  18275. throw std::runtime_error(format("batch.logits[%d] != true", i));
  18276. }
  18277. if (j >= ctx->n_outputs) {
  18278. // This should not happen
  18279. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  18280. }
  18281. return ctx->embd + j*ctx->model.hparams.n_embd;
  18282. } catch (const std::exception & err) {
  18283. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  18284. #ifndef NDEBUG
  18285. GGML_ABORT("fatal error");
  18286. #else
  18287. return nullptr;
  18288. #endif
  18289. }
  18290. }
  18291. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  18292. llama_synchronize(ctx);
  18293. auto it = ctx->embd_seq.find(seq_id);
  18294. if (it == ctx->embd_seq.end()) {
  18295. return nullptr;
  18296. }
  18297. return it->second.data();
  18298. }
  18299. //
  18300. // vocab
  18301. //
  18302. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  18303. return llama_token_get_text_impl(model->vocab, token);
  18304. }
  18305. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  18306. return llama_token_get_score_impl(model->vocab, token);
  18307. }
  18308. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  18309. return llama_token_get_attr_impl(model->vocab, token);
  18310. }
  18311. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  18312. return llama_token_is_eog_impl(model->vocab, token);
  18313. }
  18314. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  18315. return llama_token_is_control_impl(model->vocab, token);
  18316. }
  18317. llama_token llama_token_bos(const struct llama_model * model) {
  18318. return llama_token_bos_impl(model->vocab);
  18319. }
  18320. llama_token llama_token_eos(const struct llama_model * model) {
  18321. return llama_token_eos_impl(model->vocab);
  18322. }
  18323. llama_token llama_token_cls(const struct llama_model * model) {
  18324. return llama_token_cls_impl(model->vocab);
  18325. }
  18326. llama_token llama_token_sep(const struct llama_model * model) {
  18327. return llama_token_sep_impl(model->vocab);
  18328. }
  18329. llama_token llama_token_nl (const struct llama_model * model) {
  18330. return llama_token_nl_impl(model->vocab);
  18331. }
  18332. llama_token llama_token_pad(const struct llama_model * model) {
  18333. return llama_token_pad_impl(model->vocab);
  18334. }
  18335. bool llama_add_bos_token(const struct llama_model * model) {
  18336. return llama_add_bos_token_impl(model->vocab);
  18337. }
  18338. bool llama_add_eos_token(const struct llama_model * model) {
  18339. return llama_add_eos_token_impl(model->vocab);
  18340. }
  18341. llama_token llama_token_prefix(const struct llama_model * model) {
  18342. return llama_token_prefix_impl(model->vocab);
  18343. }
  18344. llama_token llama_token_middle(const struct llama_model * model) {
  18345. return llama_token_middle_impl(model->vocab);
  18346. }
  18347. llama_token llama_token_suffix(const struct llama_model * model) {
  18348. return llama_token_suffix_impl(model->vocab);
  18349. }
  18350. llama_token llama_token_eot(const struct llama_model * model) {
  18351. return llama_token_eot_impl(model->vocab);
  18352. }
  18353. //
  18354. // tokenization
  18355. //
  18356. int32_t llama_tokenize(
  18357. const struct llama_model * model,
  18358. const char * text,
  18359. int32_t text_len,
  18360. llama_token * tokens,
  18361. int32_t n_tokens_max,
  18362. bool add_special,
  18363. bool parse_special) {
  18364. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  18365. }
  18366. int32_t llama_token_to_piece(
  18367. const struct llama_model * model,
  18368. llama_token token,
  18369. char * buf,
  18370. int32_t length,
  18371. int32_t lstrip,
  18372. bool special) {
  18373. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  18374. }
  18375. int32_t llama_detokenize(
  18376. const struct llama_model * model,
  18377. const llama_token * tokens,
  18378. int32_t n_tokens,
  18379. char * text,
  18380. int32_t text_len_max,
  18381. bool remove_special,
  18382. bool unparse_special) {
  18383. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  18384. }
  18385. //
  18386. // chat templates
  18387. //
  18388. // Simple version of "llama_apply_chat_template" that only works with strings
  18389. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  18390. static int32_t llama_chat_apply_template_internal(
  18391. const std::string & tmpl,
  18392. const std::vector<const llama_chat_message *> & chat,
  18393. std::string & dest, bool add_ass) {
  18394. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  18395. std::stringstream ss;
  18396. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  18397. return tmpl.find(haystack) != std::string::npos;
  18398. };
  18399. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  18400. // chatml template
  18401. for (auto message : chat) {
  18402. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  18403. }
  18404. if (add_ass) {
  18405. ss << "<|im_start|>assistant\n";
  18406. }
  18407. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  18408. // llama2 template and its variants
  18409. // [variant] support system message
  18410. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  18411. // [variant] space before + after response
  18412. bool space_around_response = tmpl_contains("' ' + eos_token");
  18413. // [variant] add BOS inside history
  18414. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  18415. // [variant] trim spaces from the input message
  18416. bool strip_message = tmpl_contains("content.strip()");
  18417. // construct the prompt
  18418. bool is_inside_turn = true; // skip BOS at the beginning
  18419. ss << "[INST] ";
  18420. for (auto message : chat) {
  18421. std::string content = strip_message ? trim(message->content) : message->content;
  18422. std::string role(message->role);
  18423. if (!is_inside_turn) {
  18424. is_inside_turn = true;
  18425. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  18426. }
  18427. if (role == "system") {
  18428. if (support_system_message) {
  18429. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  18430. } else {
  18431. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  18432. ss << content << "\n";
  18433. }
  18434. } else if (role == "user") {
  18435. ss << content << " [/INST]";
  18436. } else {
  18437. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  18438. is_inside_turn = false;
  18439. }
  18440. }
  18441. // llama2 templates seem to not care about "add_generation_prompt"
  18442. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  18443. // Phi 3
  18444. for (auto message : chat) {
  18445. std::string role(message->role);
  18446. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  18447. }
  18448. if (add_ass) {
  18449. ss << "<|assistant|>\n";
  18450. }
  18451. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  18452. // zephyr template
  18453. for (auto message : chat) {
  18454. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  18455. }
  18456. if (add_ass) {
  18457. ss << "<|assistant|>\n";
  18458. }
  18459. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  18460. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  18461. for (auto message : chat) {
  18462. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  18463. ss << bos << message->role << "\n" << message->content << "</s>\n";
  18464. }
  18465. if (add_ass) {
  18466. ss << "<s>assistant\n";
  18467. }
  18468. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  18469. // google/gemma-7b-it
  18470. std::string system_prompt = "";
  18471. for (auto message : chat) {
  18472. std::string role(message->role);
  18473. if (role == "system") {
  18474. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  18475. system_prompt = trim(message->content);
  18476. continue;
  18477. }
  18478. // in gemma, "assistant" is "model"
  18479. role = role == "assistant" ? "model" : message->role;
  18480. ss << "<start_of_turn>" << role << "\n";
  18481. if (!system_prompt.empty() && role != "model") {
  18482. ss << system_prompt << "\n\n";
  18483. system_prompt = "";
  18484. }
  18485. ss << trim(message->content) << "<end_of_turn>\n";
  18486. }
  18487. if (add_ass) {
  18488. ss << "<start_of_turn>model\n";
  18489. }
  18490. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  18491. // OrionStarAI/Orion-14B-Chat
  18492. std::string system_prompt = "";
  18493. for (auto message : chat) {
  18494. std::string role(message->role);
  18495. if (role == "system") {
  18496. // there is no system message support, we will merge it with user prompt
  18497. system_prompt = message->content;
  18498. continue;
  18499. } else if (role == "user") {
  18500. ss << "Human: ";
  18501. if (!system_prompt.empty()) {
  18502. ss << system_prompt << "\n\n";
  18503. system_prompt = "";
  18504. }
  18505. ss << message->content << "\n\nAssistant: </s>";
  18506. } else {
  18507. ss << message->content << "</s>";
  18508. }
  18509. }
  18510. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  18511. // openchat/openchat-3.5-0106,
  18512. for (auto message : chat) {
  18513. std::string role(message->role);
  18514. if (role == "system") {
  18515. ss << message->content << "<|end_of_turn|>";
  18516. } else {
  18517. role[0] = toupper(role[0]);
  18518. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  18519. }
  18520. }
  18521. if (add_ass) {
  18522. ss << "GPT4 Correct Assistant:";
  18523. }
  18524. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  18525. // eachadea/vicuna-13b-1.1 (and Orca variant)
  18526. for (auto message : chat) {
  18527. std::string role(message->role);
  18528. if (role == "system") {
  18529. // Orca-Vicuna variant uses a system prefix
  18530. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  18531. ss << "SYSTEM: " << message->content << "\n";
  18532. } else {
  18533. ss << message->content << "\n\n";
  18534. }
  18535. } else if (role == "user") {
  18536. ss << "USER: " << message->content << "\n";
  18537. } else if (role == "assistant") {
  18538. ss << "ASSISTANT: " << message->content << "</s>\n";
  18539. }
  18540. }
  18541. if (add_ass) {
  18542. ss << "ASSISTANT:";
  18543. }
  18544. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  18545. // deepseek-ai/deepseek-coder-33b-instruct
  18546. for (auto message : chat) {
  18547. std::string role(message->role);
  18548. if (role == "system") {
  18549. ss << message->content;
  18550. } else if (role == "user") {
  18551. ss << "### Instruction:\n" << message->content << "\n";
  18552. } else if (role == "assistant") {
  18553. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  18554. }
  18555. }
  18556. if (add_ass) {
  18557. ss << "### Response:\n";
  18558. }
  18559. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  18560. // CohereForAI/c4ai-command-r-plus
  18561. for (auto message : chat) {
  18562. std::string role(message->role);
  18563. if (role == "system") {
  18564. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18565. } else if (role == "user") {
  18566. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18567. } else if (role == "assistant") {
  18568. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18569. }
  18570. }
  18571. if (add_ass) {
  18572. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  18573. }
  18574. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  18575. // Llama 3
  18576. for (auto message : chat) {
  18577. std::string role(message->role);
  18578. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  18579. }
  18580. if (add_ass) {
  18581. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  18582. }
  18583. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  18584. // chatglm3-6b
  18585. ss << "[gMASK]" << "sop";
  18586. for (auto message : chat) {
  18587. std::string role(message->role);
  18588. ss << "<|" << role << "|>" << "\n " << message->content;
  18589. }
  18590. if (add_ass) {
  18591. ss << "<|assistant|>";
  18592. }
  18593. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  18594. ss << "[gMASK]" << "<sop>";
  18595. for (auto message : chat) {
  18596. std::string role(message->role);
  18597. ss << "<|" << role << "|>" << "\n" << message->content;
  18598. }
  18599. if (add_ass) {
  18600. ss << "<|assistant|>";
  18601. }
  18602. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  18603. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  18604. for (auto message : chat) {
  18605. std::string role(message->role);
  18606. if (role == "user") {
  18607. ss << LU8("<用户>");
  18608. ss << trim(message->content);
  18609. ss << "<AI>";
  18610. } else {
  18611. ss << trim(message->content);
  18612. }
  18613. }
  18614. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  18615. // DeepSeek-V2
  18616. for (auto message : chat) {
  18617. std::string role(message->role);
  18618. if (role == "system") {
  18619. ss << message->content << "\n\n";
  18620. } else if (role == "user") {
  18621. ss << "User: " << message->content << "\n\n";
  18622. } else if (role == "assistant") {
  18623. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  18624. }
  18625. }
  18626. if (add_ass) {
  18627. ss << "Assistant:";
  18628. }
  18629. } else if (tmpl == "exaone3" || (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]"))) {
  18630. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  18631. // EXAONE-3.0-7.8B-Instruct
  18632. for (auto message : chat) {
  18633. std::string role(message->role);
  18634. if (role == "system") {
  18635. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  18636. } else if (role == "user") {
  18637. ss << "[|user|]" << trim(message->content) << "\n";
  18638. } else if (role == "assistant") {
  18639. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  18640. }
  18641. }
  18642. if (add_ass) {
  18643. ss << "[|assistant|]";
  18644. }
  18645. } else {
  18646. // template not supported
  18647. return -1;
  18648. }
  18649. dest = ss.str();
  18650. return dest.size();
  18651. }
  18652. int32_t llama_chat_apply_template(
  18653. const struct llama_model * model,
  18654. const char * tmpl,
  18655. const struct llama_chat_message * chat,
  18656. size_t n_msg,
  18657. bool add_ass,
  18658. char * buf,
  18659. int32_t length) {
  18660. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  18661. if (tmpl == nullptr) {
  18662. GGML_ASSERT(model != nullptr);
  18663. // load template from model
  18664. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  18665. std::string template_key = "tokenizer.chat_template";
  18666. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  18667. if (res < 0) {
  18668. // worst case: there is no information about template, we will use chatml by default
  18669. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  18670. } else {
  18671. curr_tmpl = std::string(model_template.data(), model_template.size());
  18672. }
  18673. }
  18674. // format the chat to string
  18675. std::vector<const llama_chat_message *> chat_vec;
  18676. chat_vec.resize(n_msg);
  18677. for (size_t i = 0; i < n_msg; i++) {
  18678. chat_vec[i] = &chat[i];
  18679. }
  18680. std::string formatted_chat;
  18681. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  18682. if (res < 0) {
  18683. return res;
  18684. }
  18685. if (buf && length > 0) {
  18686. strncpy(buf, formatted_chat.c_str(), length);
  18687. }
  18688. return res;
  18689. }
  18690. //
  18691. // sampling
  18692. //
  18693. // TODO: remove indirection when vocab becomes accesible in llama-sampling.cpp
  18694. struct llama_sampler * llama_sampler_init_grammar(const struct llama_model * model, const char * grammar_str, const char * grammar_root) {
  18695. return llama_sampler_init_grammar_impl(model->vocab, grammar_str, grammar_root);
  18696. }
  18697. //
  18698. // model split
  18699. //
  18700. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  18701. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  18702. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  18703. return strlen(split_path);
  18704. }
  18705. return 0;
  18706. }
  18707. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  18708. std::string str_split_path(split_path);
  18709. char postfix[32];
  18710. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  18711. std::string str_postfix(postfix);
  18712. // check if dest ends with postfix
  18713. int size_prefix = str_split_path.size() - str_postfix.size();
  18714. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  18715. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  18716. return size_prefix;
  18717. }
  18718. return 0;
  18719. }
  18720. const char * llama_print_system_info(void) {
  18721. static std::string s;
  18722. s = "";
  18723. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  18724. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  18725. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  18726. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  18727. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  18728. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  18729. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  18730. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  18731. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  18732. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  18733. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  18734. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  18735. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  18736. s += "RISCV_VECT = " + std::to_string(ggml_cpu_has_riscv_v()) + " | ";
  18737. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  18738. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  18739. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  18740. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  18741. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  18742. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  18743. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  18744. return s.c_str();
  18745. }
  18746. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  18747. struct llama_perf_context_data data = {};
  18748. if (ctx == nullptr) {
  18749. return data;
  18750. }
  18751. data.t_start_ms = 1e-3 * ctx->t_start_us;
  18752. data.t_load_ms = 1e-3 * ctx->t_load_us;
  18753. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  18754. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  18755. data.n_p_eval = std::max(1, ctx->n_p_eval);
  18756. data.n_eval = std::max(1, ctx->n_eval);
  18757. return data;
  18758. }
  18759. void llama_perf_context_print(const struct llama_context * ctx) {
  18760. const auto data = llama_perf_context(ctx);
  18761. const double t_end_ms = 1e-3 * ggml_time_us();
  18762. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  18763. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  18764. __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);
  18765. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  18766. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  18767. 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));
  18768. }
  18769. void llama_perf_context_reset(struct llama_context * ctx) {
  18770. ctx->t_start_us = ggml_time_us();
  18771. ctx->t_eval_us = ctx->n_eval = 0;
  18772. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  18773. }
  18774. void llama_perf_dump_yaml(FILE * stream, const llama_context * ctx) {
  18775. fprintf(stream, "\n");
  18776. fprintf(stream, "###########\n");
  18777. fprintf(stream, "# Timings #\n");
  18778. fprintf(stream, "###########\n");
  18779. fprintf(stream, "\n");
  18780. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  18781. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  18782. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  18783. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  18784. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  18785. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  18786. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  18787. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  18788. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  18789. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  18790. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  18791. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  18792. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  18793. }
  18794. // For internal test use
  18795. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  18796. struct llama_context * ctx
  18797. ) {
  18798. return ctx->model.tensors_by_name;
  18799. }
  18800. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  18801. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  18802. g_state.log_callback_user_data = user_data;
  18803. #ifdef GGML_USE_METAL
  18804. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18805. #elif defined(GGML_USE_CUDA)
  18806. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18807. #elif defined(GGML_USE_CANN)
  18808. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  18809. #endif
  18810. }
  18811. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  18812. va_list args_copy;
  18813. va_copy(args_copy, args);
  18814. char buffer[128];
  18815. int len = vsnprintf(buffer, 128, format, args);
  18816. if (len < 128) {
  18817. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  18818. } else {
  18819. char * buffer2 = new char[len + 1];
  18820. vsnprintf(buffer2, len + 1, format, args_copy);
  18821. buffer2[len] = 0;
  18822. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  18823. delete[] buffer2;
  18824. }
  18825. va_end(args_copy);
  18826. }
  18827. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  18828. va_list args;
  18829. va_start(args, format);
  18830. llama_log_internal_v(level, format, args);
  18831. va_end(args);
  18832. }
  18833. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  18834. (void) level;
  18835. (void) user_data;
  18836. fputs(text, stderr);
  18837. fflush(stderr);
  18838. }