llama.cpp 918 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957
  1. #include "llama-impl.h"
  2. #include "llama-vocab.h"
  3. #include "llama-sampling.h"
  4. #include "unicode.h"
  5. #include "ggml.h"
  6. #include "ggml-alloc.h"
  7. #include "ggml-backend.h"
  8. #if defined(GGML_USE_KOMPUTE)
  9. # include "ggml-kompute.h"
  10. #elif defined(GGML_USE_CANN)
  11. # include "ggml-cann.h"
  12. #endif
  13. #ifndef __AMX_INT8__
  14. #undef GGML_USE_AMX
  15. #endif
  16. #ifdef GGML_USE_AMX
  17. # include "ggml-amx.h"
  18. #endif
  19. // TODO: replace with ggml API call
  20. #define QK_K 256
  21. #ifdef __has_include
  22. #if __has_include(<unistd.h>)
  23. #include <unistd.h>
  24. #if defined(_POSIX_MAPPED_FILES)
  25. #include <sys/mman.h>
  26. #include <fcntl.h>
  27. #endif
  28. #if defined(_POSIX_MEMLOCK_RANGE)
  29. #include <sys/resource.h>
  30. #endif
  31. #endif
  32. #endif
  33. #if defined(_WIN32)
  34. #define WIN32_LEAN_AND_MEAN
  35. #ifndef NOMINMAX
  36. #define NOMINMAX
  37. #endif
  38. #include <windows.h>
  39. #ifndef PATH_MAX
  40. #define PATH_MAX MAX_PATH
  41. #endif
  42. #include <io.h>
  43. #endif
  44. #if __cplusplus >= 202000L
  45. #define LU8(x) (const char*)(u8##x)
  46. #else
  47. #define LU8(x) u8##x
  48. #endif
  49. #include <algorithm>
  50. #include <array>
  51. #include <cassert>
  52. #include <cctype>
  53. #include <cfloat>
  54. #include <cinttypes>
  55. #include <climits>
  56. #include <cmath>
  57. #include <cstdarg>
  58. #include <cstddef>
  59. #include <cstdint>
  60. #include <cstdio>
  61. #include <cstring>
  62. #include <ctime>
  63. #include <fstream>
  64. #include <functional>
  65. #include <future>
  66. #include <initializer_list>
  67. #include <locale>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <set>
  73. #include <sstream>
  74. #include <thread>
  75. #include <type_traits>
  76. #include <unordered_map>
  77. #if defined(_MSC_VER)
  78. #pragma warning(disable: 4244 4267) // possible loss of data
  79. #endif
  80. // bump if necessary
  81. #define LLAMA_MAX_LAYERS 512
  82. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  83. //
  84. // helpers
  85. //
  86. // trim whitespace from the beginning and end of a string
  87. static std::string trim(const std::string & str) {
  88. size_t start = 0;
  89. size_t end = str.size();
  90. while (start < end && isspace(str[start])) {
  91. start += 1;
  92. }
  93. while (end > start && isspace(str[end - 1])) {
  94. end -= 1;
  95. }
  96. return str.substr(start, end - start);
  97. }
  98. static bool is_float_close(float a, float b, float abs_tol) {
  99. // Check for non-negative tolerance
  100. if (abs_tol < 0.0) {
  101. throw std::invalid_argument("Tolerance must be non-negative");
  102. }
  103. // Exact equality check
  104. if (a == b) {
  105. return true;
  106. }
  107. // Check for infinities
  108. if (std::isinf(a) || std::isinf(b)) {
  109. return false;
  110. }
  111. // Regular comparison using the provided absolute tolerance
  112. return std::fabs(b - a) <= abs_tol;
  113. }
  114. static void zeros(std::ofstream & file, size_t n) {
  115. char zero = 0;
  116. for (size_t i = 0; i < n; ++i) {
  117. file.write(&zero, 1);
  118. }
  119. }
  120. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  121. static std::string format(const char * fmt, ...) {
  122. va_list ap;
  123. va_list ap2;
  124. va_start(ap, fmt);
  125. va_copy(ap2, ap);
  126. int size = vsnprintf(NULL, 0, fmt, ap);
  127. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  128. std::vector<char> buf(size + 1);
  129. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  130. GGML_ASSERT(size2 == size);
  131. va_end(ap2);
  132. va_end(ap);
  133. return std::string(buf.data(), size);
  134. }
  135. //
  136. // gguf constants (sync with gguf.py)
  137. //
  138. enum llm_arch {
  139. LLM_ARCH_LLAMA,
  140. LLM_ARCH_FALCON,
  141. LLM_ARCH_BAICHUAN,
  142. LLM_ARCH_GROK,
  143. LLM_ARCH_GPT2,
  144. LLM_ARCH_GPTJ,
  145. LLM_ARCH_GPTNEOX,
  146. LLM_ARCH_MPT,
  147. LLM_ARCH_STARCODER,
  148. LLM_ARCH_REFACT,
  149. LLM_ARCH_BERT,
  150. LLM_ARCH_NOMIC_BERT,
  151. LLM_ARCH_JINA_BERT_V2,
  152. LLM_ARCH_BLOOM,
  153. LLM_ARCH_STABLELM,
  154. LLM_ARCH_QWEN,
  155. LLM_ARCH_QWEN2,
  156. LLM_ARCH_QWEN2MOE,
  157. LLM_ARCH_PHI2,
  158. LLM_ARCH_PHI3,
  159. LLM_ARCH_PLAMO,
  160. LLM_ARCH_CODESHELL,
  161. LLM_ARCH_ORION,
  162. LLM_ARCH_INTERNLM2,
  163. LLM_ARCH_MINICPM,
  164. LLM_ARCH_MINICPM3,
  165. LLM_ARCH_GEMMA,
  166. LLM_ARCH_GEMMA2,
  167. LLM_ARCH_STARCODER2,
  168. LLM_ARCH_MAMBA,
  169. LLM_ARCH_XVERSE,
  170. LLM_ARCH_COMMAND_R,
  171. LLM_ARCH_DBRX,
  172. LLM_ARCH_OLMO,
  173. LLM_ARCH_OLMOE,
  174. LLM_ARCH_OPENELM,
  175. LLM_ARCH_ARCTIC,
  176. LLM_ARCH_DEEPSEEK2,
  177. LLM_ARCH_CHATGLM,
  178. LLM_ARCH_BITNET,
  179. LLM_ARCH_T5,
  180. LLM_ARCH_T5ENCODER,
  181. LLM_ARCH_JAIS,
  182. LLM_ARCH_NEMOTRON,
  183. LLM_ARCH_EXAONE,
  184. LLM_ARCH_RWKV6,
  185. LLM_ARCH_GRANITE,
  186. LLM_ARCH_GRANITE_MOE,
  187. LLM_ARCH_CHAMELEON,
  188. LLM_ARCH_UNKNOWN,
  189. };
  190. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  191. { LLM_ARCH_LLAMA, "llama" },
  192. { LLM_ARCH_FALCON, "falcon" },
  193. { LLM_ARCH_GROK, "grok" },
  194. { LLM_ARCH_GPT2, "gpt2" },
  195. { LLM_ARCH_GPTJ, "gptj" },
  196. { LLM_ARCH_GPTNEOX, "gptneox" },
  197. { LLM_ARCH_MPT, "mpt" },
  198. { LLM_ARCH_BAICHUAN, "baichuan" },
  199. { LLM_ARCH_STARCODER, "starcoder" },
  200. { LLM_ARCH_REFACT, "refact" },
  201. { LLM_ARCH_BERT, "bert" },
  202. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  203. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  204. { LLM_ARCH_BLOOM, "bloom" },
  205. { LLM_ARCH_STABLELM, "stablelm" },
  206. { LLM_ARCH_QWEN, "qwen" },
  207. { LLM_ARCH_QWEN2, "qwen2" },
  208. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  209. { LLM_ARCH_PHI2, "phi2" },
  210. { LLM_ARCH_PHI3, "phi3" },
  211. { LLM_ARCH_PLAMO, "plamo" },
  212. { LLM_ARCH_CODESHELL, "codeshell" },
  213. { LLM_ARCH_ORION, "orion" },
  214. { LLM_ARCH_INTERNLM2, "internlm2" },
  215. { LLM_ARCH_MINICPM, "minicpm" },
  216. { LLM_ARCH_MINICPM3, "minicpm3" },
  217. { LLM_ARCH_GEMMA, "gemma" },
  218. { LLM_ARCH_GEMMA2, "gemma2" },
  219. { LLM_ARCH_STARCODER2, "starcoder2" },
  220. { LLM_ARCH_MAMBA, "mamba" },
  221. { LLM_ARCH_XVERSE, "xverse" },
  222. { LLM_ARCH_COMMAND_R, "command-r" },
  223. { LLM_ARCH_DBRX, "dbrx" },
  224. { LLM_ARCH_OLMO, "olmo" },
  225. { LLM_ARCH_OLMOE, "olmoe" },
  226. { LLM_ARCH_OPENELM, "openelm" },
  227. { LLM_ARCH_ARCTIC, "arctic" },
  228. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  229. { LLM_ARCH_CHATGLM, "chatglm" },
  230. { LLM_ARCH_BITNET, "bitnet" },
  231. { LLM_ARCH_T5, "t5" },
  232. { LLM_ARCH_T5ENCODER, "t5encoder" },
  233. { LLM_ARCH_JAIS, "jais" },
  234. { LLM_ARCH_NEMOTRON, "nemotron" },
  235. { LLM_ARCH_EXAONE, "exaone" },
  236. { LLM_ARCH_RWKV6, "rwkv6" },
  237. { LLM_ARCH_GRANITE, "granite" },
  238. { LLM_ARCH_GRANITE_MOE, "granitemoe" },
  239. { LLM_ARCH_CHAMELEON, "chameleon" },
  240. { LLM_ARCH_UNKNOWN, "(unknown)" },
  241. };
  242. enum llm_kv {
  243. LLM_KV_GENERAL_TYPE,
  244. LLM_KV_GENERAL_ARCHITECTURE,
  245. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  246. LLM_KV_GENERAL_ALIGNMENT,
  247. LLM_KV_GENERAL_NAME,
  248. LLM_KV_GENERAL_AUTHOR,
  249. LLM_KV_GENERAL_VERSION,
  250. LLM_KV_GENERAL_URL,
  251. LLM_KV_GENERAL_DESCRIPTION,
  252. LLM_KV_GENERAL_LICENSE,
  253. LLM_KV_GENERAL_SOURCE_URL,
  254. LLM_KV_GENERAL_SOURCE_HF_REPO,
  255. LLM_KV_VOCAB_SIZE,
  256. LLM_KV_CONTEXT_LENGTH,
  257. LLM_KV_EMBEDDING_LENGTH,
  258. LLM_KV_BLOCK_COUNT,
  259. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  260. LLM_KV_FEED_FORWARD_LENGTH,
  261. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  262. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  263. LLM_KV_USE_PARALLEL_RESIDUAL,
  264. LLM_KV_TENSOR_DATA_LAYOUT,
  265. LLM_KV_EXPERT_COUNT,
  266. LLM_KV_EXPERT_USED_COUNT,
  267. LLM_KV_EXPERT_SHARED_COUNT,
  268. LLM_KV_EXPERT_WEIGHTS_SCALE,
  269. LLM_KV_POOLING_TYPE,
  270. LLM_KV_LOGIT_SCALE,
  271. LLM_KV_DECODER_START_TOKEN_ID,
  272. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  273. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  274. LLM_KV_SWIN_NORM,
  275. LLM_KV_RESCALE_EVERY_N_LAYERS,
  276. LLM_KV_TIME_MIX_EXTRA_DIM,
  277. LLM_KV_TIME_DECAY_EXTRA_DIM,
  278. LLM_KV_RESIDUAL_SCALE,
  279. LLM_KV_EMBEDDING_SCALE,
  280. LLM_KV_ATTENTION_HEAD_COUNT,
  281. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  282. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  283. LLM_KV_ATTENTION_CLAMP_KQV,
  284. LLM_KV_ATTENTION_KEY_LENGTH,
  285. LLM_KV_ATTENTION_VALUE_LENGTH,
  286. LLM_KV_ATTENTION_LAYERNORM_EPS,
  287. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  288. LLM_KV_ATTENTION_CAUSAL,
  289. LLM_KV_ATTENTION_Q_LORA_RANK,
  290. LLM_KV_ATTENTION_KV_LORA_RANK,
  291. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  292. LLM_KV_ATTENTION_SLIDING_WINDOW,
  293. LLM_KV_ATTENTION_SCALE,
  294. LLM_KV_ROPE_DIMENSION_COUNT,
  295. LLM_KV_ROPE_FREQ_BASE,
  296. LLM_KV_ROPE_SCALE_LINEAR,
  297. LLM_KV_ROPE_SCALING_TYPE,
  298. LLM_KV_ROPE_SCALING_FACTOR,
  299. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  300. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  301. LLM_KV_ROPE_SCALING_FINETUNED,
  302. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  303. LLM_KV_SPLIT_NO,
  304. LLM_KV_SPLIT_COUNT,
  305. LLM_KV_SPLIT_TENSORS_COUNT,
  306. LLM_KV_SSM_INNER_SIZE,
  307. LLM_KV_SSM_CONV_KERNEL,
  308. LLM_KV_SSM_STATE_SIZE,
  309. LLM_KV_SSM_TIME_STEP_RANK,
  310. LLM_KV_SSM_DT_B_C_RMS,
  311. LLM_KV_WKV_HEAD_SIZE,
  312. LLM_KV_TOKENIZER_MODEL,
  313. LLM_KV_TOKENIZER_PRE,
  314. LLM_KV_TOKENIZER_LIST,
  315. LLM_KV_TOKENIZER_TOKEN_TYPE,
  316. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  317. LLM_KV_TOKENIZER_SCORES,
  318. LLM_KV_TOKENIZER_MERGES,
  319. LLM_KV_TOKENIZER_BOS_ID,
  320. LLM_KV_TOKENIZER_EOS_ID,
  321. LLM_KV_TOKENIZER_EOT_ID,
  322. LLM_KV_TOKENIZER_EOM_ID,
  323. LLM_KV_TOKENIZER_UNK_ID,
  324. LLM_KV_TOKENIZER_SEP_ID,
  325. LLM_KV_TOKENIZER_PAD_ID,
  326. LLM_KV_TOKENIZER_CLS_ID,
  327. LLM_KV_TOKENIZER_MASK_ID,
  328. LLM_KV_TOKENIZER_ADD_BOS,
  329. LLM_KV_TOKENIZER_ADD_EOS,
  330. LLM_KV_TOKENIZER_ADD_PREFIX,
  331. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  332. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  333. LLM_KV_TOKENIZER_HF_JSON,
  334. LLM_KV_TOKENIZER_RWKV,
  335. LLM_KV_TOKENIZER_FIM_PRE_ID,
  336. LLM_KV_TOKENIZER_FIM_SUF_ID,
  337. LLM_KV_TOKENIZER_FIM_MID_ID,
  338. LLM_KV_TOKENIZER_FIM_PAD_ID,
  339. LLM_KV_TOKENIZER_FIM_REP_ID,
  340. LLM_KV_TOKENIZER_FIM_SEP_ID,
  341. LLM_KV_ADAPTER_TYPE,
  342. LLM_KV_ADAPTER_LORA_ALPHA,
  343. // deprecated:
  344. LLM_KV_TOKENIZER_PREFIX_ID,
  345. LLM_KV_TOKENIZER_SUFFIX_ID,
  346. LLM_KV_TOKENIZER_MIDDLE_ID,
  347. };
  348. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  349. { LLM_KV_GENERAL_TYPE, "general.type" },
  350. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  351. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  352. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  353. { LLM_KV_GENERAL_NAME, "general.name" },
  354. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  355. { LLM_KV_GENERAL_VERSION, "general.version" },
  356. { LLM_KV_GENERAL_URL, "general.url" },
  357. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  358. { LLM_KV_GENERAL_LICENSE, "general.license" },
  359. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  360. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  361. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  362. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  363. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  364. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  365. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  366. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  367. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  368. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  369. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  370. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  371. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  372. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  373. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  374. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  375. { LLM_KV_POOLING_TYPE, "%s.pooling_type" },
  376. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  377. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  378. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  379. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  380. { LLM_KV_SWIN_NORM, "%s.swin_norm" },
  381. { LLM_KV_RESCALE_EVERY_N_LAYERS, "%s.rescale_every_n_layers" },
  382. { LLM_KV_TIME_MIX_EXTRA_DIM, "%s.time_mix_extra_dim" },
  383. { LLM_KV_TIME_DECAY_EXTRA_DIM, "%s.time_decay_extra_dim" },
  384. { LLM_KV_RESIDUAL_SCALE, "%s.residual_scale" },
  385. { LLM_KV_EMBEDDING_SCALE, "%s.embedding_scale" },
  386. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  387. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  388. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  389. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  390. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  391. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  392. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  393. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  394. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  395. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  396. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  397. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  398. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  399. { LLM_KV_ATTENTION_SCALE, "%s.attention.scale" },
  400. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  401. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  402. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  403. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  404. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  405. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  406. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  407. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  408. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  409. { LLM_KV_SPLIT_NO, "split.no" },
  410. { LLM_KV_SPLIT_COUNT, "split.count" },
  411. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  412. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  413. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  414. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  415. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  416. { LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
  417. { LLM_KV_WKV_HEAD_SIZE, "%s.wkv.head_size" },
  418. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  419. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  420. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  421. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  422. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  423. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  424. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  425. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  426. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  427. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  428. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  429. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  430. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  431. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  432. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  433. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  434. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  435. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  436. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  437. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  438. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  439. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  440. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  441. { LLM_KV_TOKENIZER_FIM_PRE_ID, "tokenizer.ggml.fim_pre_token_id" },
  442. { LLM_KV_TOKENIZER_FIM_SUF_ID, "tokenizer.ggml.fim_suf_token_id" },
  443. { LLM_KV_TOKENIZER_FIM_MID_ID, "tokenizer.ggml.fim_mid_token_id" },
  444. { LLM_KV_TOKENIZER_FIM_PAD_ID, "tokenizer.ggml.fim_pad_token_id" },
  445. { LLM_KV_TOKENIZER_FIM_REP_ID, "tokenizer.ggml.fim_rep_token_id" },
  446. { LLM_KV_TOKENIZER_FIM_SEP_ID, "tokenizer.ggml.fim_sep_token_id" },
  447. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  448. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  449. // deprecated
  450. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  451. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  452. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  453. };
  454. struct LLM_KV {
  455. LLM_KV(llm_arch arch) : arch(arch) {}
  456. llm_arch arch;
  457. std::string operator()(llm_kv kv) const {
  458. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  459. }
  460. };
  461. enum llm_tensor {
  462. LLM_TENSOR_TOKEN_EMBD,
  463. LLM_TENSOR_TOKEN_EMBD_NORM,
  464. LLM_TENSOR_TOKEN_TYPES,
  465. LLM_TENSOR_POS_EMBD,
  466. LLM_TENSOR_OUTPUT,
  467. LLM_TENSOR_OUTPUT_NORM,
  468. LLM_TENSOR_ROPE_FREQS,
  469. LLM_TENSOR_ROPE_FACTORS_LONG,
  470. LLM_TENSOR_ROPE_FACTORS_SHORT,
  471. LLM_TENSOR_ATTN_Q,
  472. LLM_TENSOR_ATTN_K,
  473. LLM_TENSOR_ATTN_V,
  474. LLM_TENSOR_ATTN_QKV,
  475. LLM_TENSOR_ATTN_OUT,
  476. LLM_TENSOR_ATTN_NORM,
  477. LLM_TENSOR_ATTN_NORM_2,
  478. LLM_TENSOR_ATTN_OUT_NORM,
  479. LLM_TENSOR_ATTN_POST_NORM,
  480. LLM_TENSOR_ATTN_ROT_EMBD,
  481. LLM_TENSOR_FFN_GATE_INP,
  482. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  483. LLM_TENSOR_FFN_NORM,
  484. LLM_TENSOR_FFN_POST_NORM,
  485. LLM_TENSOR_FFN_GATE,
  486. LLM_TENSOR_FFN_DOWN,
  487. LLM_TENSOR_FFN_UP,
  488. LLM_TENSOR_FFN_ACT,
  489. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  490. LLM_TENSOR_FFN_GATE_EXP,
  491. LLM_TENSOR_FFN_UP_EXP,
  492. LLM_TENSOR_FFN_NORM_EXPS,
  493. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  494. LLM_TENSOR_FFN_GATE_EXPS,
  495. LLM_TENSOR_FFN_UP_EXPS,
  496. LLM_TENSOR_FFN_DOWN_SHEXP,
  497. LLM_TENSOR_FFN_GATE_SHEXP,
  498. LLM_TENSOR_FFN_UP_SHEXP,
  499. LLM_TENSOR_ATTN_Q_NORM,
  500. LLM_TENSOR_ATTN_K_NORM,
  501. LLM_TENSOR_LAYER_OUT_NORM,
  502. LLM_TENSOR_SSM_IN,
  503. LLM_TENSOR_SSM_CONV1D,
  504. LLM_TENSOR_SSM_X,
  505. LLM_TENSOR_SSM_DT,
  506. LLM_TENSOR_SSM_A,
  507. LLM_TENSOR_SSM_D,
  508. LLM_TENSOR_SSM_OUT,
  509. LLM_TENSOR_TIME_MIX_W1,
  510. LLM_TENSOR_TIME_MIX_W2,
  511. LLM_TENSOR_TIME_MIX_LERP_X,
  512. LLM_TENSOR_TIME_MIX_LERP_W,
  513. LLM_TENSOR_TIME_MIX_LERP_K,
  514. LLM_TENSOR_TIME_MIX_LERP_V,
  515. LLM_TENSOR_TIME_MIX_LERP_R,
  516. LLM_TENSOR_TIME_MIX_LERP_G,
  517. LLM_TENSOR_TIME_MIX_FIRST,
  518. LLM_TENSOR_TIME_MIX_DECAY,
  519. LLM_TENSOR_TIME_MIX_DECAY_W1,
  520. LLM_TENSOR_TIME_MIX_DECAY_W2,
  521. LLM_TENSOR_TIME_MIX_KEY,
  522. LLM_TENSOR_TIME_MIX_VALUE,
  523. LLM_TENSOR_TIME_MIX_RECEPTANCE,
  524. LLM_TENSOR_TIME_MIX_GATE,
  525. LLM_TENSOR_TIME_MIX_LN,
  526. LLM_TENSOR_TIME_MIX_OUTPUT,
  527. LLM_TENSOR_CHANNEL_MIX_LERP_K,
  528. LLM_TENSOR_CHANNEL_MIX_LERP_R,
  529. LLM_TENSOR_CHANNEL_MIX_KEY,
  530. LLM_TENSOR_CHANNEL_MIX_RECEPTANCE,
  531. LLM_TENSOR_CHANNEL_MIX_VALUE,
  532. LLM_TENSOR_ATTN_Q_A,
  533. LLM_TENSOR_ATTN_Q_B,
  534. LLM_TENSOR_ATTN_KV_A_MQA,
  535. LLM_TENSOR_ATTN_KV_B,
  536. LLM_TENSOR_ATTN_Q_A_NORM,
  537. LLM_TENSOR_ATTN_KV_A_NORM,
  538. LLM_TENSOR_ATTN_SUB_NORM,
  539. LLM_TENSOR_FFN_SUB_NORM,
  540. LLM_TENSOR_DEC_ATTN_NORM,
  541. LLM_TENSOR_DEC_ATTN_Q,
  542. LLM_TENSOR_DEC_ATTN_K,
  543. LLM_TENSOR_DEC_ATTN_V,
  544. LLM_TENSOR_DEC_ATTN_OUT,
  545. LLM_TENSOR_DEC_ATTN_REL_B,
  546. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  547. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  548. LLM_TENSOR_DEC_CROSS_ATTN_K,
  549. LLM_TENSOR_DEC_CROSS_ATTN_V,
  550. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  551. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  552. LLM_TENSOR_DEC_FFN_NORM,
  553. LLM_TENSOR_DEC_FFN_GATE,
  554. LLM_TENSOR_DEC_FFN_DOWN,
  555. LLM_TENSOR_DEC_FFN_UP,
  556. LLM_TENSOR_DEC_OUTPUT_NORM,
  557. LLM_TENSOR_ENC_ATTN_NORM,
  558. LLM_TENSOR_ENC_ATTN_Q,
  559. LLM_TENSOR_ENC_ATTN_K,
  560. LLM_TENSOR_ENC_ATTN_V,
  561. LLM_TENSOR_ENC_ATTN_OUT,
  562. LLM_TENSOR_ENC_ATTN_REL_B,
  563. LLM_TENSOR_ENC_FFN_NORM,
  564. LLM_TENSOR_ENC_FFN_GATE,
  565. LLM_TENSOR_ENC_FFN_DOWN,
  566. LLM_TENSOR_ENC_FFN_UP,
  567. LLM_TENSOR_ENC_OUTPUT_NORM,
  568. LLM_TENSOR_CLS,
  569. LLM_TENSOR_CLS_OUT,
  570. };
  571. static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_NAMES = {
  572. {
  573. LLM_ARCH_LLAMA,
  574. {
  575. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  576. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  577. { LLM_TENSOR_OUTPUT, "output" },
  578. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  579. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  580. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  581. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  582. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  583. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  584. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  585. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  586. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  587. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  588. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  589. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  590. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  591. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  592. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  593. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  594. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  595. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  596. },
  597. },
  598. {
  599. LLM_ARCH_BAICHUAN,
  600. {
  601. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  602. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  603. { LLM_TENSOR_OUTPUT, "output" },
  604. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  605. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  606. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  607. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  608. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  609. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  610. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  611. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  612. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  613. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  614. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  615. },
  616. },
  617. {
  618. LLM_ARCH_FALCON,
  619. {
  620. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  621. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  622. { LLM_TENSOR_OUTPUT, "output" },
  623. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  624. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  625. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  626. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  627. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  628. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  629. },
  630. },
  631. {
  632. LLM_ARCH_GROK,
  633. {
  634. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  635. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  636. { LLM_TENSOR_OUTPUT, "output" },
  637. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  638. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  639. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  640. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  641. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  642. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  643. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  644. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  645. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  646. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  647. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  648. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  649. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  650. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  651. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  652. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  653. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  654. },
  655. },
  656. {
  657. LLM_ARCH_GPT2,
  658. {
  659. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  660. { LLM_TENSOR_POS_EMBD, "position_embd" },
  661. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  662. { LLM_TENSOR_OUTPUT, "output" },
  663. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  664. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  665. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  666. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  667. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  668. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  669. },
  670. },
  671. {
  672. LLM_ARCH_GPTJ,
  673. {
  674. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  675. },
  676. },
  677. {
  678. LLM_ARCH_GPTNEOX,
  679. {
  680. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  681. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  682. { LLM_TENSOR_OUTPUT, "output" },
  683. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  684. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  685. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  686. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  687. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  688. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  689. },
  690. },
  691. {
  692. LLM_ARCH_MPT,
  693. {
  694. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  695. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  696. { LLM_TENSOR_OUTPUT, "output"},
  697. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  698. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  699. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  700. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  701. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  702. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  703. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  704. { LLM_TENSOR_POS_EMBD, "position_embd" },
  705. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  706. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  707. },
  708. },
  709. {
  710. LLM_ARCH_STARCODER,
  711. {
  712. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  713. { LLM_TENSOR_POS_EMBD, "position_embd" },
  714. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  715. { LLM_TENSOR_OUTPUT, "output" },
  716. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  717. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  718. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  719. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  720. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  721. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  722. },
  723. },
  724. {
  725. LLM_ARCH_REFACT,
  726. {
  727. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  728. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  729. { LLM_TENSOR_OUTPUT, "output" },
  730. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  731. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  732. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  733. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  734. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  735. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  736. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  737. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  738. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  739. },
  740. },
  741. {
  742. LLM_ARCH_BERT,
  743. {
  744. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  745. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  746. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  747. { LLM_TENSOR_POS_EMBD, "position_embd" },
  748. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  749. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  750. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  751. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  752. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  753. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  754. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  755. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  756. { LLM_TENSOR_CLS, "cls" },
  757. { LLM_TENSOR_CLS_OUT, "cls.output" },
  758. },
  759. },
  760. {
  761. LLM_ARCH_NOMIC_BERT,
  762. {
  763. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  764. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  765. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  766. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  767. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  768. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  769. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  770. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  771. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  772. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  773. },
  774. },
  775. {
  776. LLM_ARCH_JINA_BERT_V2,
  777. {
  778. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  779. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  780. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  781. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  782. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  783. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  784. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  785. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  786. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  787. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  788. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  789. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  790. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  791. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  792. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  793. { LLM_TENSOR_CLS, "cls" },
  794. },
  795. },
  796. {
  797. LLM_ARCH_BLOOM,
  798. {
  799. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  800. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  801. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  802. { LLM_TENSOR_OUTPUT, "output" },
  803. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  804. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  805. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  806. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  807. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  808. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  809. },
  810. },
  811. {
  812. LLM_ARCH_STABLELM,
  813. {
  814. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  815. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  816. { LLM_TENSOR_OUTPUT, "output" },
  817. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  818. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  819. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  820. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  821. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  822. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  823. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  824. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  825. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  826. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  827. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  828. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  829. },
  830. },
  831. {
  832. LLM_ARCH_QWEN,
  833. {
  834. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  835. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  836. { LLM_TENSOR_OUTPUT, "output" },
  837. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  838. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  839. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  840. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  841. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  842. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  843. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  844. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  845. },
  846. },
  847. {
  848. LLM_ARCH_QWEN2,
  849. {
  850. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  851. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  852. { LLM_TENSOR_OUTPUT, "output" },
  853. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  854. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  855. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  856. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  857. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  858. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  859. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  860. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  861. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  862. },
  863. },
  864. {
  865. LLM_ARCH_QWEN2MOE,
  866. {
  867. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  868. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  869. { LLM_TENSOR_OUTPUT, "output" },
  870. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  871. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  872. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  873. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  874. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  875. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  876. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  877. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  878. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  879. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  880. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  881. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  882. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  883. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  884. },
  885. },
  886. {
  887. LLM_ARCH_PHI2,
  888. {
  889. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  890. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  891. { LLM_TENSOR_OUTPUT, "output" },
  892. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  893. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  894. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  895. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  896. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  897. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  898. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  899. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  900. },
  901. },
  902. {
  903. LLM_ARCH_PHI3,
  904. {
  905. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  906. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  907. { LLM_TENSOR_OUTPUT, "output" },
  908. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  909. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  910. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  911. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  912. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  913. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  914. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  915. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  916. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  917. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  918. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  919. },
  920. },
  921. {
  922. LLM_ARCH_PLAMO,
  923. {
  924. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  925. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  926. { LLM_TENSOR_OUTPUT, "output" },
  927. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  928. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  929. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  930. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  931. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  932. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  933. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  934. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  935. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  936. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  937. },
  938. },
  939. {
  940. LLM_ARCH_CODESHELL,
  941. {
  942. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  943. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  944. { LLM_TENSOR_OUTPUT, "output" },
  945. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  946. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  947. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  948. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  949. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  950. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  951. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  952. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  953. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  954. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  955. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  956. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  957. },
  958. },
  959. {
  960. LLM_ARCH_ORION,
  961. {
  962. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  963. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  964. { LLM_TENSOR_OUTPUT, "output" },
  965. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  966. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  967. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  968. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  969. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  970. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  971. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  972. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  973. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  974. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  975. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  976. },
  977. },
  978. {
  979. LLM_ARCH_INTERNLM2,
  980. {
  981. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  982. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  983. { LLM_TENSOR_OUTPUT, "output" },
  984. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  985. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  986. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  987. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  988. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  989. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  990. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  991. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  992. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  993. },
  994. },
  995. {
  996. LLM_ARCH_MINICPM,
  997. {
  998. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  999. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1000. { LLM_TENSOR_OUTPUT, "output" },
  1001. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1002. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1003. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1004. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1005. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1006. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1007. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1008. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1009. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1010. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1011. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1012. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1013. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  1014. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  1015. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  1016. },
  1017. },
  1018. {
  1019. LLM_ARCH_MINICPM3,
  1020. {
  1021. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1022. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1023. { LLM_TENSOR_OUTPUT, "output" },
  1024. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  1025. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  1026. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1027. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1028. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1029. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1030. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1031. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1032. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1033. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1034. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1035. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1036. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1037. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1038. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1039. },
  1040. },
  1041. {
  1042. LLM_ARCH_GEMMA,
  1043. {
  1044. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1045. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1046. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1047. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1048. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1049. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1050. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1051. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1052. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1053. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1054. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1055. },
  1056. },
  1057. {
  1058. LLM_ARCH_GEMMA2,
  1059. {
  1060. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1061. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1062. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1063. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1064. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1065. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1066. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1067. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1068. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1069. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1070. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1071. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1072. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1073. },
  1074. },
  1075. {
  1076. LLM_ARCH_STARCODER2,
  1077. {
  1078. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1079. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1080. { LLM_TENSOR_OUTPUT, "output" },
  1081. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1082. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1083. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1084. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1085. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1086. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1087. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1088. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1089. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1090. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1091. },
  1092. },
  1093. {
  1094. LLM_ARCH_MAMBA,
  1095. {
  1096. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1097. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1098. { LLM_TENSOR_OUTPUT, "output" },
  1099. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1100. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1101. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1102. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1103. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1104. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1105. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1106. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1107. },
  1108. },
  1109. {
  1110. LLM_ARCH_XVERSE,
  1111. {
  1112. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1113. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1114. { LLM_TENSOR_OUTPUT, "output" },
  1115. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1116. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1117. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1118. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1119. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1120. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1121. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  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_COMMAND_R,
  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_FFN_GATE, "blk.%d.ffn_gate" },
  1139. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1140. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1141. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1142. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1143. },
  1144. },
  1145. {
  1146. LLM_ARCH_DBRX,
  1147. {
  1148. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1149. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1150. { LLM_TENSOR_OUTPUT, "output" },
  1151. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1152. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1153. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1154. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1155. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1156. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1157. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1158. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1159. },
  1160. },
  1161. {
  1162. LLM_ARCH_OLMO,
  1163. {
  1164. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1165. { LLM_TENSOR_OUTPUT, "output" },
  1166. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1167. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1168. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1169. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1170. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1171. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1172. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1173. },
  1174. },
  1175. {
  1176. LLM_ARCH_OLMOE,
  1177. {
  1178. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1179. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1180. { LLM_TENSOR_OUTPUT, "output" },
  1181. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1182. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1183. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1184. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1185. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1186. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1187. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1188. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1189. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1190. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1191. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1192. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1193. },
  1194. },
  1195. {
  1196. LLM_ARCH_OPENELM,
  1197. {
  1198. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1199. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1200. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1201. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1202. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1203. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1204. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1205. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1206. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1207. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1208. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1209. },
  1210. },
  1211. {
  1212. LLM_ARCH_ARCTIC,
  1213. {
  1214. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1215. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1216. { LLM_TENSOR_OUTPUT, "output" },
  1217. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1218. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1219. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1220. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1221. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1222. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1223. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1224. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1225. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1226. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1227. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1228. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1229. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1230. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1231. },
  1232. },
  1233. {
  1234. LLM_ARCH_DEEPSEEK2,
  1235. {
  1236. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1237. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1238. { LLM_TENSOR_OUTPUT, "output" },
  1239. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1240. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1241. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1242. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1243. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1244. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1245. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1246. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1247. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1248. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1249. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1250. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1251. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1252. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1253. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1254. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1255. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1256. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1257. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1258. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1259. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1260. },
  1261. },
  1262. {
  1263. LLM_ARCH_CHATGLM,
  1264. {
  1265. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1266. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1267. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1268. { LLM_TENSOR_OUTPUT, "output" },
  1269. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1270. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1271. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1272. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1273. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1274. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1275. },
  1276. },
  1277. {
  1278. LLM_ARCH_BITNET,
  1279. {
  1280. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1281. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1282. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1283. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1284. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1285. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1286. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1287. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1288. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1289. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1290. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1291. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1292. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1293. },
  1294. },
  1295. {
  1296. LLM_ARCH_T5,
  1297. {
  1298. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1299. { LLM_TENSOR_OUTPUT, "output" },
  1300. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1301. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1302. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1303. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1304. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1305. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1306. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1307. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1308. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1309. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1310. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1311. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1312. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1313. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1314. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1315. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1316. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1317. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1318. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1319. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1320. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1321. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1322. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1323. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1324. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1325. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1326. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1327. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1328. },
  1329. },
  1330. {
  1331. LLM_ARCH_T5ENCODER,
  1332. {
  1333. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1334. { LLM_TENSOR_OUTPUT, "output" },
  1335. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1336. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1337. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1338. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1339. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1340. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1341. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1342. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1343. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1344. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1345. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1346. },
  1347. },
  1348. {
  1349. LLM_ARCH_JAIS,
  1350. {
  1351. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1352. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1353. { LLM_TENSOR_OUTPUT, "output" },
  1354. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1355. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1356. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1357. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1358. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1359. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1360. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1361. },
  1362. },
  1363. {
  1364. LLM_ARCH_NEMOTRON,
  1365. {
  1366. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1367. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1368. { LLM_TENSOR_OUTPUT, "output" },
  1369. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1370. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1371. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1372. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1373. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1374. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1375. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1376. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1377. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1378. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1379. },
  1380. },
  1381. {
  1382. LLM_ARCH_EXAONE,
  1383. {
  1384. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1385. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1386. { LLM_TENSOR_OUTPUT, "output" },
  1387. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1388. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1389. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1390. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1391. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1392. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1393. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1394. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1395. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1396. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1397. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1398. },
  1399. },
  1400. {
  1401. LLM_ARCH_RWKV6,
  1402. {
  1403. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1404. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  1405. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1406. { LLM_TENSOR_OUTPUT, "output" },
  1407. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1408. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  1409. { LLM_TENSOR_TIME_MIX_W1, "blk.%d.time_mix_w1" },
  1410. { LLM_TENSOR_TIME_MIX_W2, "blk.%d.time_mix_w2" },
  1411. { LLM_TENSOR_TIME_MIX_LERP_X, "blk.%d.time_mix_lerp_x" },
  1412. { LLM_TENSOR_TIME_MIX_LERP_W, "blk.%d.time_mix_lerp_w" },
  1413. { LLM_TENSOR_TIME_MIX_LERP_K, "blk.%d.time_mix_lerp_k" },
  1414. { LLM_TENSOR_TIME_MIX_LERP_V, "blk.%d.time_mix_lerp_v" },
  1415. { LLM_TENSOR_TIME_MIX_LERP_R, "blk.%d.time_mix_lerp_r" },
  1416. { LLM_TENSOR_TIME_MIX_LERP_G, "blk.%d.time_mix_lerp_g" },
  1417. { LLM_TENSOR_TIME_MIX_FIRST, "blk.%d.time_mix_first" },
  1418. { LLM_TENSOR_TIME_MIX_DECAY, "blk.%d.time_mix_decay" },
  1419. { LLM_TENSOR_TIME_MIX_DECAY_W1, "blk.%d.time_mix_decay_w1" },
  1420. { LLM_TENSOR_TIME_MIX_DECAY_W2, "blk.%d.time_mix_decay_w2" },
  1421. { LLM_TENSOR_TIME_MIX_KEY, "blk.%d.time_mix_key" },
  1422. { LLM_TENSOR_TIME_MIX_VALUE, "blk.%d.time_mix_value" },
  1423. { LLM_TENSOR_TIME_MIX_RECEPTANCE, "blk.%d.time_mix_receptance" },
  1424. { LLM_TENSOR_TIME_MIX_GATE, "blk.%d.time_mix_gate" },
  1425. { LLM_TENSOR_TIME_MIX_LN, "blk.%d.time_mix_ln" },
  1426. { LLM_TENSOR_TIME_MIX_OUTPUT, "blk.%d.time_mix_output" },
  1427. { LLM_TENSOR_CHANNEL_MIX_LERP_K, "blk.%d.channel_mix_lerp_k" },
  1428. { LLM_TENSOR_CHANNEL_MIX_LERP_R, "blk.%d.channel_mix_lerp_r" },
  1429. { LLM_TENSOR_CHANNEL_MIX_KEY, "blk.%d.channel_mix_key" },
  1430. { LLM_TENSOR_CHANNEL_MIX_VALUE, "blk.%d.channel_mix_value" },
  1431. { LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "blk.%d.channel_mix_receptance" },
  1432. },
  1433. },
  1434. {
  1435. LLM_ARCH_GRANITE,
  1436. {
  1437. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1438. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1439. { LLM_TENSOR_OUTPUT, "output" },
  1440. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1441. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1442. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1443. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1444. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1445. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1446. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1447. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1448. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1449. },
  1450. },
  1451. {
  1452. LLM_ARCH_GRANITE_MOE,
  1453. {
  1454. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1455. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1456. { LLM_TENSOR_OUTPUT, "output" },
  1457. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1458. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1459. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1460. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1462. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1463. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1464. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1465. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1466. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1467. },
  1468. },
  1469. {
  1470. LLM_ARCH_CHAMELEON,
  1471. {
  1472. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1473. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1474. { LLM_TENSOR_OUTPUT, "output" },
  1475. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1476. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1477. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1478. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1479. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1480. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1481. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1482. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1483. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1484. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1485. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1486. },
  1487. },
  1488. {
  1489. LLM_ARCH_UNKNOWN,
  1490. {
  1491. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1492. },
  1493. },
  1494. };
  1495. static llm_arch llm_arch_from_string(const std::string & name) {
  1496. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1497. if (kv.second == name) {
  1498. return kv.first;
  1499. }
  1500. }
  1501. return LLM_ARCH_UNKNOWN;
  1502. }
  1503. // helper to handle gguf constants
  1504. // usage:
  1505. //
  1506. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1507. //
  1508. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1509. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1510. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1511. //
  1512. struct LLM_TN {
  1513. LLM_TN(llm_arch arch) : arch(arch) {}
  1514. llm_arch arch;
  1515. std::string operator()(llm_tensor tensor) const {
  1516. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1517. return "__missing__";
  1518. }
  1519. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1520. }
  1521. std::string operator()(llm_tensor tensor, const char * suffix) const {
  1522. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1523. return "__missing__";
  1524. }
  1525. return std::string(LLM_TENSOR_NAMES.at(arch).at(tensor)) + "." + suffix;
  1526. }
  1527. std::string operator()(llm_tensor tensor, int bid) const {
  1528. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1529. return "__missing__";
  1530. }
  1531. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor), bid);
  1532. }
  1533. std::string operator()(llm_tensor tensor, const char * suffix, int bid) const {
  1534. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1535. return "__missing__";
  1536. }
  1537. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor), bid) + "." + suffix;
  1538. }
  1539. std::string operator()(llm_tensor tensor, const char * suffix, int bid, int xid) const {
  1540. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1541. return "__missing__";
  1542. }
  1543. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor), bid, xid) + "." + suffix;
  1544. }
  1545. };
  1546. //
  1547. // gguf helpers
  1548. //
  1549. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1550. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1551. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1552. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1553. };
  1554. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1555. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1556. if (kv.second == name) {
  1557. return (llama_rope_scaling_type) kv.first;
  1558. }
  1559. }
  1560. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1561. }
  1562. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1563. switch (type) {
  1564. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1565. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1566. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1567. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1568. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1569. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1570. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1571. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1572. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1573. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1574. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1575. default: return format("unknown type %d", type);
  1576. }
  1577. }
  1578. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1579. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1580. switch (type) {
  1581. case GGUF_TYPE_STRING:
  1582. return gguf_get_val_str(ctx_gguf, i);
  1583. case GGUF_TYPE_ARRAY:
  1584. {
  1585. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1586. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1587. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1588. std::stringstream ss;
  1589. ss << "[";
  1590. for (int j = 0; j < arr_n; j++) {
  1591. if (arr_type == GGUF_TYPE_STRING) {
  1592. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1593. // escape quotes
  1594. replace_all(val, "\\", "\\\\");
  1595. replace_all(val, "\"", "\\\"");
  1596. ss << '"' << val << '"';
  1597. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1598. ss << "???";
  1599. } else {
  1600. ss << gguf_data_to_str(arr_type, data, j);
  1601. }
  1602. if (j < arr_n - 1) {
  1603. ss << ", ";
  1604. }
  1605. }
  1606. ss << "]";
  1607. return ss.str();
  1608. }
  1609. default:
  1610. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1611. }
  1612. }
  1613. //
  1614. // llama helpers
  1615. //
  1616. #if defined(_WIN32)
  1617. static std::string llama_format_win_err(DWORD err) {
  1618. LPSTR buf;
  1619. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1620. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1621. if (!size) {
  1622. return "FormatMessageA failed";
  1623. }
  1624. std::string ret(buf, size);
  1625. LocalFree(buf);
  1626. return ret;
  1627. }
  1628. #endif
  1629. template <typename T>
  1630. struct no_init {
  1631. T value;
  1632. no_init() { /* do nothing */ }
  1633. };
  1634. struct llama_file {
  1635. #if defined(_WIN32)
  1636. // use FILE * so we don't have to re-open the file to mmap
  1637. FILE * fp;
  1638. HANDLE fp_win32;
  1639. size_t size;
  1640. private:
  1641. std::string GetErrorMessageWin32(DWORD error_code) const {
  1642. std::string ret;
  1643. LPSTR lpMsgBuf = NULL;
  1644. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1645. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1646. if (!bufLen) {
  1647. ret = format("Win32 error code: %s", error_code);
  1648. } else {
  1649. ret = lpMsgBuf;
  1650. LocalFree(lpMsgBuf);
  1651. }
  1652. return ret;
  1653. }
  1654. public:
  1655. llama_file(const char * fname, const char * mode) {
  1656. fp = ggml_fopen(fname, mode);
  1657. if (fp == NULL) {
  1658. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1659. }
  1660. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1661. seek(0, SEEK_END);
  1662. size = tell();
  1663. seek(0, SEEK_SET);
  1664. }
  1665. size_t tell() const {
  1666. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1667. LARGE_INTEGER li;
  1668. li.QuadPart = 0;
  1669. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1670. if (!ret) {
  1671. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1672. }
  1673. return li.QuadPart;
  1674. }
  1675. void seek(size_t offset, int whence) const {
  1676. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1677. // Still, keep static asserts to avoid failures in the future.
  1678. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1679. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1680. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1681. LARGE_INTEGER li;
  1682. li.QuadPart = offset;
  1683. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1684. if (!ret) {
  1685. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1686. }
  1687. }
  1688. void read_raw(void * ptr, size_t len) const {
  1689. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1690. // use the Win32 API to do file io instead of the C/C++ library functions.
  1691. // There are conditions under which ReadFile cannot read chunks >64MB.
  1692. // Thus split the operation into smaller chunks if len exceeds this limit.
  1693. size_t bytes_read = 0;
  1694. while (bytes_read < len) {
  1695. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1696. DWORD chunk_read = 0;
  1697. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1698. if (!result) {
  1699. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1700. }
  1701. if (chunk_read < chunk_size || chunk_read == 0) {
  1702. throw std::runtime_error("unexpectedly reached end of file");
  1703. }
  1704. bytes_read += chunk_read;
  1705. } ;
  1706. }
  1707. uint32_t read_u32() const {
  1708. uint32_t val;
  1709. read_raw(&val, sizeof(val));
  1710. return val;
  1711. }
  1712. void write_raw(const void * ptr, size_t len) const {
  1713. // There are conditions under which WriteFile cannot write chunks >64MB.
  1714. // Thus split the operation into smaller chunks if len exceeds this limit.
  1715. size_t bytes_written = 0;
  1716. while (bytes_written < len) {
  1717. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1718. DWORD chunk_written = 0;
  1719. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1720. if (!result) {
  1721. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1722. }
  1723. if (chunk_written < chunk_size || chunk_written == 0) {
  1724. throw std::runtime_error("unexpectedly failed to write bytes");
  1725. }
  1726. bytes_written += chunk_written;
  1727. }
  1728. }
  1729. void write_u32(std::uint32_t val) const {
  1730. write_raw(&val, sizeof(val));
  1731. }
  1732. ~llama_file() {
  1733. if (fp) {
  1734. std::fclose(fp);
  1735. }
  1736. }
  1737. #else
  1738. // use FILE * so we don't have to re-open the file to mmap
  1739. FILE * fp;
  1740. size_t size;
  1741. llama_file(const char * fname, const char * mode) {
  1742. fp = ggml_fopen(fname, mode);
  1743. if (fp == NULL) {
  1744. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1745. }
  1746. seek(0, SEEK_END);
  1747. size = tell();
  1748. seek(0, SEEK_SET);
  1749. }
  1750. size_t tell() const {
  1751. #ifdef _WIN32
  1752. __int64 ret = _ftelli64(fp);
  1753. #else
  1754. long ret = std::ftell(fp);
  1755. #endif
  1756. if (ret == -1) {
  1757. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1758. }
  1759. return (size_t) ret;
  1760. }
  1761. void seek(size_t offset, int whence) const {
  1762. #ifdef _WIN32
  1763. int ret = _fseeki64(fp, (__int64) offset, whence);
  1764. #else
  1765. int ret = std::fseek(fp, (long) offset, whence);
  1766. #endif
  1767. if (ret != 0) {
  1768. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1769. }
  1770. }
  1771. void read_raw(void * ptr, size_t len) const {
  1772. if (len == 0) {
  1773. return;
  1774. }
  1775. errno = 0;
  1776. std::size_t ret = std::fread(ptr, len, 1, fp);
  1777. if (ferror(fp)) {
  1778. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1779. }
  1780. if (ret != 1) {
  1781. throw std::runtime_error("unexpectedly reached end of file");
  1782. }
  1783. }
  1784. uint32_t read_u32() const {
  1785. uint32_t ret;
  1786. read_raw(&ret, sizeof(ret));
  1787. return ret;
  1788. }
  1789. void write_raw(const void * ptr, size_t len) const {
  1790. if (len == 0) {
  1791. return;
  1792. }
  1793. errno = 0;
  1794. size_t ret = std::fwrite(ptr, len, 1, fp);
  1795. if (ret != 1) {
  1796. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1797. }
  1798. }
  1799. void write_u32(std::uint32_t val) const {
  1800. write_raw(&val, sizeof(val));
  1801. }
  1802. ~llama_file() {
  1803. if (fp) {
  1804. std::fclose(fp);
  1805. }
  1806. }
  1807. #endif
  1808. };
  1809. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1810. struct llama_mmap {
  1811. void * addr;
  1812. size_t size;
  1813. llama_mmap(const llama_mmap &) = delete;
  1814. #ifdef _POSIX_MAPPED_FILES
  1815. static constexpr bool SUPPORTED = true;
  1816. // list of mapped fragments (first_offset, last_offset)
  1817. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1818. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1819. size = file->size;
  1820. int fd = fileno(file->fp);
  1821. int flags = MAP_SHARED;
  1822. // prefetch/readahead impairs performance on NUMA systems
  1823. if (numa) { prefetch = 0; }
  1824. #ifdef __linux__
  1825. // advise the kernel to read the file sequentially (increases readahead)
  1826. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1827. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1828. strerror(errno));
  1829. }
  1830. if (prefetch) { flags |= MAP_POPULATE; }
  1831. #endif
  1832. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1833. if (addr == MAP_FAILED) { // NOLINT
  1834. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1835. }
  1836. if (prefetch > 0) {
  1837. // advise the kernel to preload the mapped memory
  1838. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1839. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1840. strerror(errno));
  1841. }
  1842. }
  1843. if (numa) {
  1844. // advise the kernel not to use readahead
  1845. // (because the next page might not belong on the same node)
  1846. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1847. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1848. strerror(errno));
  1849. }
  1850. }
  1851. // initialize list of mapped_fragments
  1852. mapped_fragments.emplace_back(0, file->size);
  1853. }
  1854. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1855. // align first to the next page
  1856. size_t offset_in_page = *first & (page_size - 1);
  1857. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1858. *first += offset_to_page;
  1859. // align last to the previous page
  1860. *last = *last & ~(page_size - 1);
  1861. if (*last <= *first) {
  1862. *last = *first;
  1863. }
  1864. }
  1865. // partially unmap the file in the range [first, last)
  1866. void unmap_fragment(size_t first, size_t last) {
  1867. // note: this function must not be called multiple times with overlapping ranges
  1868. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1869. int page_size = sysconf(_SC_PAGESIZE);
  1870. align_range(&first, &last, page_size);
  1871. size_t len = last - first;
  1872. if (len == 0) {
  1873. return;
  1874. }
  1875. GGML_ASSERT(first % page_size == 0);
  1876. GGML_ASSERT(last % page_size == 0);
  1877. GGML_ASSERT(last > first);
  1878. void * next_page_start = (uint8_t *) addr + first;
  1879. // unmap the range
  1880. if (munmap(next_page_start, len)) {
  1881. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1882. }
  1883. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1884. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1885. for (const auto & frag : mapped_fragments) {
  1886. if (frag.first < first && frag.second > last) {
  1887. // the range is in the middle of the fragment, split it
  1888. new_mapped_fragments.emplace_back(frag.first, first);
  1889. new_mapped_fragments.emplace_back(last, frag.second);
  1890. } else if (frag.first < first && frag.second > first) {
  1891. // the range starts in the middle of the fragment
  1892. new_mapped_fragments.emplace_back(frag.first, first);
  1893. } else if (frag.first < last && frag.second > last) {
  1894. // the range ends in the middle of the fragment
  1895. new_mapped_fragments.emplace_back(last, frag.second);
  1896. } else if (frag.first >= first && frag.second <= last) {
  1897. // the range covers the entire fragment
  1898. } else {
  1899. // the range is outside the fragment
  1900. new_mapped_fragments.push_back(frag);
  1901. }
  1902. }
  1903. mapped_fragments = std::move(new_mapped_fragments);
  1904. }
  1905. ~llama_mmap() {
  1906. for (const auto & frag : mapped_fragments) {
  1907. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1908. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1909. }
  1910. }
  1911. }
  1912. #elif defined(_WIN32)
  1913. static constexpr bool SUPPORTED = true;
  1914. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1915. GGML_UNUSED(numa);
  1916. size = file->size;
  1917. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1918. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1919. if (hMapping == NULL) {
  1920. DWORD error = GetLastError();
  1921. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1922. }
  1923. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1924. DWORD error = GetLastError();
  1925. CloseHandle(hMapping);
  1926. if (addr == NULL) {
  1927. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1928. }
  1929. if (prefetch > 0) {
  1930. #if _WIN32_WINNT >= 0x602
  1931. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1932. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1933. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1934. // may fail on pre-Windows 8 systems
  1935. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1936. if (pPrefetchVirtualMemory) {
  1937. // advise the kernel to preload the mapped memory
  1938. WIN32_MEMORY_RANGE_ENTRY range;
  1939. range.VirtualAddress = addr;
  1940. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1941. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1942. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1943. llama_format_win_err(GetLastError()).c_str());
  1944. }
  1945. }
  1946. #else
  1947. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1948. #endif
  1949. }
  1950. }
  1951. void unmap_fragment(size_t first, size_t last) {
  1952. // not supported
  1953. GGML_UNUSED(first);
  1954. GGML_UNUSED(last);
  1955. }
  1956. ~llama_mmap() {
  1957. if (!UnmapViewOfFile(addr)) {
  1958. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1959. llama_format_win_err(GetLastError()).c_str());
  1960. }
  1961. }
  1962. #else
  1963. static constexpr bool SUPPORTED = false;
  1964. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1965. GGML_UNUSED(file);
  1966. GGML_UNUSED(prefetch);
  1967. GGML_UNUSED(numa);
  1968. throw std::runtime_error("mmap not supported");
  1969. }
  1970. void unmap_fragment(size_t first, size_t last) {
  1971. GGML_UNUSED(first);
  1972. GGML_UNUSED(last);
  1973. throw std::runtime_error("mmap not supported");
  1974. }
  1975. #endif
  1976. };
  1977. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1978. // Represents some region of memory being locked using mlock or VirtualLock;
  1979. // will automatically unlock on destruction.
  1980. struct llama_mlock {
  1981. void * addr = NULL;
  1982. size_t size = 0;
  1983. bool failed_already = false;
  1984. llama_mlock() {}
  1985. llama_mlock(const llama_mlock &) = delete;
  1986. ~llama_mlock() {
  1987. if (size) {
  1988. raw_unlock(addr, size);
  1989. }
  1990. }
  1991. void init(void * ptr) {
  1992. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1993. addr = ptr;
  1994. }
  1995. void grow_to(size_t target_size) {
  1996. GGML_ASSERT(addr);
  1997. if (failed_already) {
  1998. return;
  1999. }
  2000. size_t granularity = lock_granularity();
  2001. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  2002. if (target_size > size) {
  2003. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  2004. size = target_size;
  2005. } else {
  2006. failed_already = true;
  2007. }
  2008. }
  2009. }
  2010. #ifdef _POSIX_MEMLOCK_RANGE
  2011. static constexpr bool SUPPORTED = true;
  2012. static size_t lock_granularity() {
  2013. return (size_t) sysconf(_SC_PAGESIZE);
  2014. }
  2015. #ifdef __APPLE__
  2016. #define MLOCK_SUGGESTION \
  2017. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  2018. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  2019. #else
  2020. #define MLOCK_SUGGESTION \
  2021. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  2022. #endif
  2023. bool raw_lock(const void * addr, size_t size) const {
  2024. if (!mlock(addr, size)) {
  2025. return true;
  2026. }
  2027. char* errmsg = std::strerror(errno);
  2028. bool suggest = (errno == ENOMEM);
  2029. // Check if the resource limit is fine after all
  2030. struct rlimit lock_limit;
  2031. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  2032. suggest = false;
  2033. }
  2034. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  2035. suggest = false;
  2036. }
  2037. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  2038. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  2039. return false;
  2040. }
  2041. #undef MLOCK_SUGGESTION
  2042. static void raw_unlock(void * addr, size_t size) {
  2043. if (munlock(addr, size)) {
  2044. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  2045. }
  2046. }
  2047. #elif defined(_WIN32)
  2048. static constexpr bool SUPPORTED = true;
  2049. static size_t lock_granularity() {
  2050. SYSTEM_INFO si;
  2051. GetSystemInfo(&si);
  2052. return (size_t) si.dwPageSize;
  2053. }
  2054. bool raw_lock(void * ptr, size_t len) const {
  2055. for (int tries = 1; ; tries++) {
  2056. if (VirtualLock(ptr, len)) {
  2057. return true;
  2058. }
  2059. if (tries == 2) {
  2060. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  2061. len, size, llama_format_win_err(GetLastError()).c_str());
  2062. return false;
  2063. }
  2064. // It failed but this was only the first try; increase the working
  2065. // set size and try again.
  2066. SIZE_T min_ws_size, max_ws_size;
  2067. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  2068. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  2069. llama_format_win_err(GetLastError()).c_str());
  2070. return false;
  2071. }
  2072. // Per MSDN: "The maximum number of pages that a process can lock
  2073. // is equal to the number of pages in its minimum working set minus
  2074. // a small overhead."
  2075. // Hopefully a megabyte is enough overhead:
  2076. size_t increment = len + 1048576;
  2077. // The minimum must be <= the maximum, so we need to increase both:
  2078. min_ws_size += increment;
  2079. max_ws_size += increment;
  2080. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  2081. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  2082. llama_format_win_err(GetLastError()).c_str());
  2083. return false;
  2084. }
  2085. }
  2086. }
  2087. static void raw_unlock(void * ptr, size_t len) {
  2088. if (!VirtualUnlock(ptr, len)) {
  2089. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  2090. llama_format_win_err(GetLastError()).c_str());
  2091. }
  2092. }
  2093. #else
  2094. static constexpr bool SUPPORTED = false;
  2095. static size_t lock_granularity() {
  2096. return (size_t) 65536;
  2097. }
  2098. bool raw_lock(const void * addr, size_t len) const {
  2099. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  2100. return false;
  2101. }
  2102. static void raw_unlock(const void * addr, size_t len) {}
  2103. #endif
  2104. };
  2105. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  2106. // NOTE: avoid ever using this except for building the token_to_piece caches
  2107. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  2108. std::string piece;
  2109. piece.resize(piece.capacity()); // using string internal cache
  2110. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2111. if (n_chars < 0) {
  2112. piece.resize(-n_chars);
  2113. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  2114. GGML_ASSERT(check == -n_chars);
  2115. }
  2116. else {
  2117. piece.resize(n_chars);
  2118. }
  2119. return piece;
  2120. }
  2121. //
  2122. // globals
  2123. //
  2124. struct llama_logger_state {
  2125. ggml_log_callback log_callback = llama_log_callback_default;
  2126. void * log_callback_user_data = nullptr;
  2127. };
  2128. static llama_logger_state g_logger_state;
  2129. // available llama models
  2130. enum e_model {
  2131. MODEL_UNKNOWN,
  2132. MODEL_14M,
  2133. MODEL_17M,
  2134. MODEL_22M,
  2135. MODEL_33M,
  2136. MODEL_60M,
  2137. MODEL_70M,
  2138. MODEL_80M,
  2139. MODEL_109M,
  2140. MODEL_137M,
  2141. MODEL_160M,
  2142. MODEL_220M,
  2143. MODEL_250M,
  2144. MODEL_270M,
  2145. MODEL_335M,
  2146. MODEL_410M,
  2147. MODEL_450M,
  2148. MODEL_770M,
  2149. MODEL_780M,
  2150. MODEL_0_5B,
  2151. MODEL_1B,
  2152. MODEL_1_3B,
  2153. MODEL_1_4B,
  2154. MODEL_1_6B,
  2155. MODEL_2B,
  2156. MODEL_2_8B,
  2157. MODEL_3B,
  2158. MODEL_4B,
  2159. MODEL_6B,
  2160. MODEL_6_9B,
  2161. MODEL_7B,
  2162. MODEL_8B,
  2163. MODEL_9B,
  2164. MODEL_11B,
  2165. MODEL_12B,
  2166. MODEL_13B,
  2167. MODEL_14B,
  2168. MODEL_15B,
  2169. MODEL_16B,
  2170. MODEL_20B,
  2171. MODEL_30B,
  2172. MODEL_34B,
  2173. MODEL_35B,
  2174. MODEL_40B,
  2175. MODEL_65B,
  2176. MODEL_70B,
  2177. MODEL_236B,
  2178. MODEL_314B,
  2179. MODEL_SMALL,
  2180. MODEL_MEDIUM,
  2181. MODEL_LARGE,
  2182. MODEL_XL,
  2183. MODEL_A1_7B,
  2184. MODEL_A2_7B,
  2185. MODEL_8x7B,
  2186. MODEL_8x22B,
  2187. MODEL_16x12B,
  2188. MODEL_10B_128x3_66B,
  2189. MODEL_57B_A14B,
  2190. MODEL_27B,
  2191. };
  2192. static const size_t kiB = 1024;
  2193. static const size_t MiB = 1024*kiB;
  2194. static const size_t GiB = 1024*MiB;
  2195. struct llama_hparams {
  2196. bool vocab_only;
  2197. bool rope_finetuned;
  2198. bool use_par_res;
  2199. bool swin_norm;
  2200. uint32_t n_vocab;
  2201. uint32_t n_ctx_train; // context size the model was trained on
  2202. uint32_t n_embd;
  2203. uint32_t n_layer;
  2204. uint32_t n_rot;
  2205. uint32_t n_swa = 0; // sliding window attention (SWA)
  2206. 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
  2207. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2208. uint32_t n_expert = 0;
  2209. uint32_t n_expert_used = 0;
  2210. uint32_t n_vocab_type = 0; // for BERT-style token types
  2211. uint32_t n_rel_attn_bkts = 0;
  2212. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2213. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2214. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2215. uint32_t n_layer_dense_lead = 0;
  2216. uint32_t n_lora_q = 0;
  2217. uint32_t n_lora_kv = 0;
  2218. uint32_t n_ff_exp = 0;
  2219. uint32_t n_ff_shexp = 0;
  2220. uint32_t n_expert_shared = 0;
  2221. float expert_weights_scale = 0.0;
  2222. float f_norm_eps;
  2223. float f_norm_rms_eps;
  2224. float f_attn_logit_softcapping = 50.0f;
  2225. float f_final_logit_softcapping = 30.0f;
  2226. // for RWKV
  2227. uint32_t rescale_every_n_layers = 0;
  2228. uint32_t time_mix_extra_dim = 0;
  2229. uint32_t time_decay_extra_dim = 0;
  2230. uint32_t wkv_head_size = 0;
  2231. float rope_attn_factor = 1.0f;
  2232. float rope_freq_base_train;
  2233. float rope_freq_scale_train;
  2234. uint32_t n_ctx_orig_yarn;
  2235. float rope_yarn_log_mul;
  2236. // for State Space Models
  2237. uint32_t ssm_d_conv = 0;
  2238. uint32_t ssm_d_inner = 0;
  2239. uint32_t ssm_d_state = 0;
  2240. uint32_t ssm_dt_rank = 0;
  2241. bool ssm_dt_b_c_rms = false;
  2242. float f_clamp_kqv = 0.0f;
  2243. float f_max_alibi_bias = 0.0f;
  2244. float f_logit_scale = 0.0f;
  2245. // Additional scale factors (Granite/Granite MoE)
  2246. float f_residual_scale = 0.0f;
  2247. float f_embedding_scale = 0.0f;
  2248. float f_attention_scale = 0.0f;
  2249. bool causal_attn = true;
  2250. bool use_alibi = false;
  2251. bool attn_soft_cap = false;
  2252. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2253. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2254. llama_token dec_start_token_id = LLAMA_TOKEN_NULL;
  2255. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2256. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2257. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2258. bool operator!=(const llama_hparams & other) const {
  2259. if (this->vocab_only != other.vocab_only) return true;
  2260. if (this->n_vocab != other.n_vocab) return true;
  2261. if (this->n_ctx_train != other.n_ctx_train) return true;
  2262. if (this->n_embd != other.n_embd) return true;
  2263. if (this->n_layer != other.n_layer) return true;
  2264. if (this->n_rot != other.n_rot) return true;
  2265. if (this->n_swa != other.n_swa) return true;
  2266. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2267. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2268. if (this->n_expert != other.n_expert) return true;
  2269. if (this->n_expert_used != other.n_expert_used) return true;
  2270. if (this->n_head_arr != other.n_head_arr) return true;
  2271. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2272. if (this->n_ff_arr != other.n_ff_arr) return true;
  2273. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2274. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2275. if (this->n_lora_q != other.n_lora_q) return true;
  2276. if (this->n_lora_kv != other.n_lora_kv) return true;
  2277. if (this->n_ff_exp != other.n_ff_exp) return true;
  2278. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2279. if (this->n_expert_shared != other.n_expert_shared) return true;
  2280. if (this->rope_finetuned != other.rope_finetuned) return true;
  2281. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2282. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2283. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2284. if (this->ssm_d_state != other.ssm_d_state) return true;
  2285. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2286. if (this->ssm_dt_b_c_rms != other.ssm_dt_b_c_rms) return true;
  2287. if (this->rescale_every_n_layers != other.rescale_every_n_layers) return true;
  2288. if (this->time_mix_extra_dim != other.time_mix_extra_dim) return true;
  2289. if (this->time_decay_extra_dim != other.time_decay_extra_dim) return true;
  2290. if (this->wkv_head_size != other.wkv_head_size) return true;
  2291. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2292. const float EPSILON = 1e-9f;
  2293. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2294. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2295. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2296. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2297. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2298. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2299. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2300. if (!is_float_close(this->f_residual_scale, other.f_residual_scale, EPSILON)) return true;
  2301. if (!is_float_close(this->f_embedding_scale, other.f_embedding_scale, EPSILON)) return true;
  2302. if (!is_float_close(this->f_attention_scale, other.f_attention_scale, EPSILON)) return true;
  2303. return false;
  2304. }
  2305. uint32_t n_head(uint32_t il = 0) const {
  2306. if (il < n_layer) {
  2307. return n_head_arr[il];
  2308. }
  2309. GGML_ABORT("fatal error");
  2310. }
  2311. uint32_t n_head_kv(uint32_t il = 0) const {
  2312. if (il < n_layer) {
  2313. return n_head_kv_arr[il];
  2314. }
  2315. GGML_ABORT("fatal error");
  2316. }
  2317. uint32_t n_ff(uint32_t il = 0) const {
  2318. if (il < n_layer) {
  2319. return n_ff_arr[il];
  2320. }
  2321. GGML_ABORT("fatal error");
  2322. }
  2323. uint32_t n_gqa(uint32_t il = 0) const {
  2324. const uint32_t n_head = this->n_head(il);
  2325. const uint32_t n_head_kv = this->n_head_kv(il);
  2326. if (n_head_kv == 0) {
  2327. return 0;
  2328. }
  2329. return n_head/n_head_kv;
  2330. }
  2331. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2332. const uint32_t n_head_kv = this->n_head_kv(il);
  2333. return n_embd_head_k * n_head_kv;
  2334. }
  2335. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2336. const uint32_t n_head_kv = this->n_head_kv(il);
  2337. return n_embd_head_v * n_head_kv;
  2338. }
  2339. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2340. // corresponds to Mamba's conv_states size or RWKV's token_shift states size
  2341. if (wkv_head_size != 0) {
  2342. // for RWKV models
  2343. return 2 * n_embd;
  2344. } else {
  2345. // TODO: maybe support other convolution strides than 1
  2346. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2347. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2348. }
  2349. }
  2350. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2351. if (wkv_head_size != 0) {
  2352. // corresponds to RWKV's wkv_states size
  2353. return n_embd * wkv_head_size;
  2354. } else {
  2355. // corresponds to Mamba's ssm_states size
  2356. return ssm_d_state * ssm_d_inner;
  2357. }
  2358. }
  2359. };
  2360. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2361. struct llama_cparams {
  2362. uint32_t n_ctx; // context size used during inference
  2363. uint32_t n_batch;
  2364. uint32_t n_ubatch;
  2365. uint32_t n_seq_max;
  2366. int n_threads; // number of threads to use for generation
  2367. int n_threads_batch; // number of threads to use for batch processing
  2368. float rope_freq_base;
  2369. float rope_freq_scale;
  2370. uint32_t n_ctx_orig_yarn;
  2371. // These hyperparameters are not exposed in GGUF, because all
  2372. // existing YaRN models use the same values for them.
  2373. float yarn_ext_factor;
  2374. float yarn_attn_factor;
  2375. float yarn_beta_fast;
  2376. float yarn_beta_slow;
  2377. float defrag_thold;
  2378. bool embeddings;
  2379. bool causal_attn;
  2380. bool offload_kqv;
  2381. bool flash_attn;
  2382. bool no_perf;
  2383. enum llama_pooling_type pooling_type;
  2384. ggml_backend_sched_eval_callback cb_eval;
  2385. void * cb_eval_user_data;
  2386. };
  2387. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2388. struct llama_layer {
  2389. // normalization
  2390. struct ggml_tensor * attn_norm;
  2391. struct ggml_tensor * attn_norm_b;
  2392. struct ggml_tensor * attn_norm_2;
  2393. struct ggml_tensor * attn_norm_2_b;
  2394. struct ggml_tensor * attn_q_norm;
  2395. struct ggml_tensor * attn_q_norm_b;
  2396. struct ggml_tensor * attn_k_norm;
  2397. struct ggml_tensor * attn_k_norm_b;
  2398. struct ggml_tensor * attn_out_norm;
  2399. struct ggml_tensor * attn_out_norm_b;
  2400. struct ggml_tensor * attn_q_a_norm;
  2401. struct ggml_tensor * attn_kv_a_norm;
  2402. struct ggml_tensor * attn_sub_norm;
  2403. struct ggml_tensor * attn_post_norm;
  2404. struct ggml_tensor * ffn_sub_norm;
  2405. struct ggml_tensor * attn_norm_cross;
  2406. struct ggml_tensor * attn_norm_enc;
  2407. // attention
  2408. struct ggml_tensor * wq;
  2409. struct ggml_tensor * wk;
  2410. struct ggml_tensor * wv;
  2411. struct ggml_tensor * wo;
  2412. struct ggml_tensor * wqkv;
  2413. struct ggml_tensor * wq_a;
  2414. struct ggml_tensor * wq_b;
  2415. struct ggml_tensor * wkv_a_mqa;
  2416. struct ggml_tensor * wkv_b;
  2417. struct ggml_tensor * wq_cross;
  2418. struct ggml_tensor * wk_cross;
  2419. struct ggml_tensor * wv_cross;
  2420. struct ggml_tensor * wo_cross;
  2421. struct ggml_tensor * wq_enc;
  2422. struct ggml_tensor * wk_enc;
  2423. struct ggml_tensor * wv_enc;
  2424. struct ggml_tensor * wo_enc;
  2425. // attention bias
  2426. struct ggml_tensor * bq;
  2427. struct ggml_tensor * bk;
  2428. struct ggml_tensor * bv;
  2429. struct ggml_tensor * bo;
  2430. struct ggml_tensor * bqkv;
  2431. // relative position bias
  2432. struct ggml_tensor * attn_rel_b;
  2433. struct ggml_tensor * attn_rel_b_enc;
  2434. struct ggml_tensor * attn_rel_b_cross;
  2435. // normalization
  2436. struct ggml_tensor * ffn_norm;
  2437. struct ggml_tensor * ffn_norm_b;
  2438. struct ggml_tensor * ffn_post_norm;
  2439. struct ggml_tensor * layer_out_norm;
  2440. struct ggml_tensor * layer_out_norm_b;
  2441. struct ggml_tensor * ffn_norm_exps;
  2442. struct ggml_tensor * ffn_norm_enc;
  2443. // ff
  2444. struct ggml_tensor * ffn_gate; // w1
  2445. struct ggml_tensor * ffn_down; // w2
  2446. struct ggml_tensor * ffn_up; // w3
  2447. struct ggml_tensor * ffn_gate_enc;
  2448. struct ggml_tensor * ffn_down_enc;
  2449. struct ggml_tensor * ffn_up_enc;
  2450. // ff MoE
  2451. struct ggml_tensor * ffn_gate_inp;
  2452. struct ggml_tensor * ffn_gate_exps;
  2453. struct ggml_tensor * ffn_down_exps;
  2454. struct ggml_tensor * ffn_up_exps ;
  2455. // ff shared expert (shexp)
  2456. struct ggml_tensor * ffn_gate_inp_shexp;
  2457. struct ggml_tensor * ffn_gate_shexp;
  2458. struct ggml_tensor * ffn_down_shexp;
  2459. struct ggml_tensor * ffn_up_shexp;
  2460. // ff bias
  2461. struct ggml_tensor * ffn_gate_b = nullptr;
  2462. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2463. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2464. struct ggml_tensor * ffn_act;
  2465. // mamba proj
  2466. struct ggml_tensor * ssm_in;
  2467. struct ggml_tensor * ssm_x;
  2468. struct ggml_tensor * ssm_dt;
  2469. struct ggml_tensor * ssm_out;
  2470. // mamba
  2471. struct ggml_tensor * ssm_conv1d;
  2472. struct ggml_tensor * ssm_a;
  2473. struct ggml_tensor * ssm_d;
  2474. // mamba bias
  2475. struct ggml_tensor * ssm_conv1d_b;
  2476. struct ggml_tensor * ssm_dt_b;
  2477. // rwkv
  2478. struct ggml_tensor * time_mix_w1;
  2479. struct ggml_tensor * time_mix_w2;
  2480. struct ggml_tensor * time_mix_lerp_x;
  2481. struct ggml_tensor * time_mix_lerp_w;
  2482. struct ggml_tensor * time_mix_lerp_k;
  2483. struct ggml_tensor * time_mix_lerp_v;
  2484. struct ggml_tensor * time_mix_lerp_r;
  2485. struct ggml_tensor * time_mix_lerp_g;
  2486. struct ggml_tensor * time_mix_first;
  2487. struct ggml_tensor * time_mix_decay;
  2488. struct ggml_tensor * time_mix_decay_w1;
  2489. struct ggml_tensor * time_mix_decay_w2;
  2490. struct ggml_tensor * time_mix_key;
  2491. struct ggml_tensor * time_mix_value;
  2492. struct ggml_tensor * time_mix_receptance;
  2493. struct ggml_tensor * time_mix_gate;
  2494. struct ggml_tensor * time_mix_ln;
  2495. struct ggml_tensor * time_mix_ln_b;
  2496. struct ggml_tensor * time_mix_output;
  2497. struct ggml_tensor * channel_mix_lerp_k;
  2498. struct ggml_tensor * channel_mix_lerp_r;
  2499. struct ggml_tensor * channel_mix_key;
  2500. struct ggml_tensor * channel_mix_receptance;
  2501. struct ggml_tensor * channel_mix_value;
  2502. // long rope factors
  2503. struct ggml_tensor * rope_long = nullptr;
  2504. struct ggml_tensor * rope_short = nullptr;
  2505. struct ggml_tensor * rope_freqs = nullptr;
  2506. // bitnet scale
  2507. struct ggml_tensor * wq_scale;
  2508. struct ggml_tensor * wk_scale;
  2509. struct ggml_tensor * wv_scale;
  2510. struct ggml_tensor * wo_scale;
  2511. struct ggml_tensor * ffn_gate_scale;
  2512. struct ggml_tensor * ffn_up_scale;
  2513. struct ggml_tensor * ffn_down_scale;
  2514. };
  2515. // very similar to llama_batch,
  2516. // but has more metadata about sequences
  2517. struct llama_ubatch {
  2518. bool equal_seqs;
  2519. // TODO: whole_seqs for embeddings?
  2520. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2521. uint32_t n_seq_tokens; // tokens per sequence
  2522. uint32_t n_seqs;
  2523. llama_token * token; // [n_tokens]
  2524. float * embd; // [n_embd, n_tokens]
  2525. llama_pos * pos; // [n_tokens]
  2526. int32_t * n_seq_id; // [n_seqs]
  2527. llama_seq_id ** seq_id; // [n_seqs]
  2528. int8_t * output; // [n_tokens]
  2529. };
  2530. struct llama_kv_cell {
  2531. llama_pos pos = -1;
  2532. llama_pos delta = 0;
  2533. int32_t src = -1; // used by recurrent state models to copy states
  2534. int32_t tail = -1;
  2535. std::set<llama_seq_id> seq_id;
  2536. bool has_seq_id(const llama_seq_id & id) const {
  2537. return seq_id.find(id) != seq_id.end();
  2538. }
  2539. bool is_empty() const {
  2540. return seq_id.empty();
  2541. }
  2542. bool is_same_seq(const llama_kv_cell & other) const {
  2543. return seq_id == other.seq_id;
  2544. }
  2545. };
  2546. // ring-buffer of cached KV data
  2547. struct llama_kv_cache {
  2548. bool has_shift = false;
  2549. bool do_defrag = false;
  2550. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2551. bool v_trans = true; // the value tensor is transposed
  2552. // Note: The value of head isn't only used to optimize searching
  2553. // for a free KV slot. llama_decode_internal also uses it, so it
  2554. // cannot be freely changed after a slot has been allocated.
  2555. uint32_t head = 0;
  2556. uint32_t size = 0;
  2557. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2558. // computed before each graph build
  2559. uint32_t n = 0;
  2560. ggml_type type_k = GGML_TYPE_F16;
  2561. ggml_type type_v = GGML_TYPE_F16;
  2562. std::vector<llama_kv_cell> cells;
  2563. std::vector<struct ggml_tensor *> k_l; // per layer
  2564. std::vector<struct ggml_tensor *> v_l;
  2565. std::vector<struct ggml_context *> ctxs;
  2566. std::vector<ggml_backend_buffer_t> bufs;
  2567. size_t total_size() const {
  2568. size_t size = 0;
  2569. for (ggml_backend_buffer_t buf : bufs) {
  2570. size += ggml_backend_buffer_get_size(buf);
  2571. }
  2572. return size;
  2573. }
  2574. ~llama_kv_cache() {
  2575. for (struct ggml_context * ctx : ctxs) {
  2576. ggml_free(ctx);
  2577. }
  2578. for (ggml_backend_buffer_t buf : bufs) {
  2579. ggml_backend_buffer_free(buf);
  2580. }
  2581. }
  2582. };
  2583. struct llama_control_vector {
  2584. std::vector<struct ggml_tensor *> tensors; // per layer
  2585. std::vector<struct ggml_context *> ctxs;
  2586. std::vector<ggml_backend_buffer_t> bufs;
  2587. int32_t layer_start = -1;
  2588. int32_t layer_end = -1;
  2589. struct ggml_tensor * tensor_for(int il) const {
  2590. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2591. return nullptr;
  2592. }
  2593. return tensors[il];
  2594. }
  2595. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2596. ggml_tensor * layer_dir = tensor_for(il);
  2597. if (layer_dir != nullptr) {
  2598. cur = ggml_add(ctx, cur, layer_dir);
  2599. }
  2600. return cur;
  2601. }
  2602. ~llama_control_vector() {
  2603. for (struct ggml_context * ctx : ctxs) {
  2604. ggml_free(ctx);
  2605. }
  2606. for (ggml_backend_buffer_t buf : bufs) {
  2607. ggml_backend_buffer_free(buf);
  2608. }
  2609. }
  2610. };
  2611. struct llama_model {
  2612. e_model type = MODEL_UNKNOWN;
  2613. llm_arch arch = LLM_ARCH_UNKNOWN;
  2614. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2615. std::string name = "n/a";
  2616. llama_hparams hparams = {};
  2617. llama_vocab vocab;
  2618. // TODO: should init all tensors to nullptr
  2619. struct ggml_tensor * tok_embd;
  2620. struct ggml_tensor * type_embd;
  2621. struct ggml_tensor * pos_embd;
  2622. struct ggml_tensor * tok_norm;
  2623. struct ggml_tensor * tok_norm_b;
  2624. struct ggml_tensor * output_norm;
  2625. struct ggml_tensor * output_norm_b;
  2626. struct ggml_tensor * output;
  2627. struct ggml_tensor * output_b;
  2628. struct ggml_tensor * output_norm_enc;
  2629. // classifier
  2630. struct ggml_tensor * cls;
  2631. struct ggml_tensor * cls_b;
  2632. struct ggml_tensor * cls_out = nullptr;
  2633. struct ggml_tensor * cls_out_b = nullptr;
  2634. std::vector<llama_layer> layers;
  2635. // gguf metadata
  2636. std::unordered_map<std::string, std::string> gguf_kv;
  2637. llama_split_mode split_mode;
  2638. int main_gpu;
  2639. int n_gpu_layers;
  2640. // list of devices used in this model
  2641. std::vector<ggml_backend_dev_t> devices;
  2642. std::vector<std::string> rpc_servers;
  2643. // layer -> buffer type mapping
  2644. struct layer_buft {
  2645. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2646. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2647. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2648. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2649. ggml_backend_buffer_type_t buft; // everything else
  2650. };
  2651. layer_buft buft_input;
  2652. layer_buft buft_output;
  2653. std::vector<layer_buft> buft_layer;
  2654. // contexts where the model tensors metadata is stored
  2655. std::vector<struct ggml_context *> ctxs;
  2656. // the model memory buffers for the tensor data
  2657. std::vector<ggml_backend_buffer_t> bufs;
  2658. // model memory mapped files
  2659. llama_mmaps mappings;
  2660. // objects representing data potentially being locked in memory
  2661. llama_mlocks mlock_bufs;
  2662. llama_mlocks mlock_mmaps;
  2663. // for quantize-stats only
  2664. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2665. int64_t t_load_us = 0;
  2666. int64_t t_start_us = 0;
  2667. // keep track of loaded lora adapters
  2668. std::set<struct llama_lora_adapter *> lora_adapters;
  2669. ~llama_model() {
  2670. for (struct ggml_context * ctx : ctxs) {
  2671. ggml_free(ctx);
  2672. }
  2673. for (ggml_backend_buffer_t buf : bufs) {
  2674. ggml_backend_buffer_free(buf);
  2675. }
  2676. while (!lora_adapters.empty()) {
  2677. llama_lora_adapter_free(*lora_adapters.begin());
  2678. }
  2679. }
  2680. };
  2681. struct llama_sbatch_seq {
  2682. int32_t n_seq_id;
  2683. llama_seq_id * seq_id;
  2684. size_t offset;
  2685. size_t length;
  2686. };
  2687. // sequence-length-aware batch splitting
  2688. struct llama_sbatch {
  2689. // tokens left in this batch
  2690. size_t n_tokens;
  2691. size_t n_embd;
  2692. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2693. // sorted indices into the batch
  2694. std::vector<size_t> ids;
  2695. // batch indices of the output
  2696. std::vector<size_t> out_ids;
  2697. std::vector<llama_sbatch_seq> seq;
  2698. const llama_batch * batch = nullptr;
  2699. // buffers for the ubatch
  2700. std::vector<llama_token> ubatch_token;
  2701. std::vector<float> ubatch_embd;
  2702. std::vector<llama_pos> ubatch_pos;
  2703. std::vector<int32_t> ubatch_n_seq_id;
  2704. std::vector<llama_seq_id *> ubatch_seq_id;
  2705. std::vector<int8_t> ubatch_output;
  2706. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2707. // clear empty sequences
  2708. // the previous ubatch is assumed to be gone,
  2709. // so nothing should refer to values in these sequences anymore.
  2710. for (size_t i = seq.size(); i-- > 0;) {
  2711. if (seq[i].length == 0) {
  2712. seq.pop_back();
  2713. } else {
  2714. break;
  2715. }
  2716. }
  2717. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2718. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2719. ubatch_pos.resize(n_ubatch);
  2720. ubatch_n_seq_id.resize(n_ubatch);
  2721. ubatch_seq_id.resize(n_ubatch);
  2722. ubatch_output.resize(n_ubatch);
  2723. llama_ubatch ubatch = {
  2724. /*equal_seqs =*/ true,
  2725. /*n_tokens =*/ 0,
  2726. /*n_seq_tokens =*/ 0,
  2727. /*n_seqs =*/ 0,
  2728. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2729. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2730. /*pos =*/ ubatch_pos.data(),
  2731. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2732. /*seq_id =*/ ubatch_seq_id.data(),
  2733. /*output =*/ ubatch_output.data(),
  2734. };
  2735. return ubatch;
  2736. }
  2737. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2738. GGML_ASSERT(batch != nullptr);
  2739. GGML_ASSERT(length <= seq.length);
  2740. // Can only add sequences of equal lengths to a batch,
  2741. // otherwise it isn't clear to which sequence a token belongs
  2742. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2743. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2744. // NOTE: loops are separated for cache-friendliness
  2745. if (batch->token) {
  2746. if (ubatch.equal_seqs) {
  2747. for (size_t i = 0; i < length; ++i) {
  2748. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2749. }
  2750. } else {
  2751. // simple split
  2752. ubatch.token = batch->token + seq.offset;
  2753. }
  2754. } else {
  2755. ubatch.token = nullptr;
  2756. }
  2757. if (batch->embd) {
  2758. if (ubatch.equal_seqs) {
  2759. for (size_t i = 0; i < length; ++i) {
  2760. memcpy(
  2761. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2762. batch->embd + n_embd * ids[seq.offset + i],
  2763. n_embd * sizeof(float)
  2764. );
  2765. }
  2766. } else {
  2767. // simple split
  2768. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2769. }
  2770. } else {
  2771. ubatch.embd = nullptr;
  2772. }
  2773. if (ubatch.equal_seqs) {
  2774. for (size_t i = 0; i < length; ++i) {
  2775. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2776. }
  2777. } else {
  2778. // simple split
  2779. ubatch.pos = batch->pos + seq.offset;
  2780. }
  2781. if (ubatch.equal_seqs) {
  2782. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2783. if (seq.seq_id) {
  2784. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2785. }
  2786. } else {
  2787. // simple split
  2788. if (batch->n_seq_id) {
  2789. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  2790. } else {
  2791. for (size_t i = 0; i < length; ++i) {
  2792. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  2793. }
  2794. }
  2795. if (batch->seq_id) {
  2796. ubatch.seq_id = batch->seq_id + seq.offset;
  2797. }
  2798. }
  2799. if (logits_all) {
  2800. for (size_t i = 0; i < length; ++i) {
  2801. ubatch.output[ubatch.n_tokens + i] = 1;
  2802. out_ids.push_back(ids[seq.offset + i]);
  2803. }
  2804. } else if (batch->logits) {
  2805. if (ubatch.equal_seqs) {
  2806. for (size_t i = 0; i < length; ++i) {
  2807. size_t id = ids[seq.offset + i];
  2808. int8_t is_output = batch->logits[id];
  2809. ubatch.output[ubatch.n_tokens + i] = is_output;
  2810. if (is_output) { out_ids.push_back(id); }
  2811. }
  2812. } else {
  2813. // simple split
  2814. ubatch.output = batch->logits + seq.offset;
  2815. for (size_t i = 0; i < length; ++i) {
  2816. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  2817. }
  2818. }
  2819. } else {
  2820. // only get last output
  2821. for (size_t i = 0; i < length; ++i) {
  2822. size_t id = ids[seq.offset + i];
  2823. int8_t is_last = id == ids.size() - 1;
  2824. ubatch.output[ubatch.n_tokens + i] = is_last;
  2825. if (is_last) { out_ids.push_back(id); }
  2826. }
  2827. }
  2828. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  2829. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  2830. }
  2831. ubatch.n_tokens += length;
  2832. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  2833. seq.offset += length;
  2834. seq.length -= length;
  2835. n_tokens -= length;
  2836. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  2837. }
  2838. // simple split, unknown number of sequences of unequal lengths
  2839. llama_ubatch split_simple(size_t n_ubatch) {
  2840. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2841. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2842. ubatch.equal_seqs = false;
  2843. if (!seq.empty()) {
  2844. llama_sbatch_seq & s = seq[0];
  2845. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  2846. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  2847. add_seq_to_ubatch(ubatch, s, length);
  2848. }
  2849. return ubatch;
  2850. }
  2851. // make batches of equal-length sequences
  2852. llama_ubatch split_equal(size_t n_ubatch) {
  2853. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2854. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2855. if (!seq.empty()) {
  2856. size_t length = 0;
  2857. size_t n_tokens_in_ubatch = 0;
  2858. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  2859. // smallest first, because it's easier to split this way;
  2860. // starting from the end to pop in constant time.
  2861. for (size_t i = seq.size(); i-- > 0;) {
  2862. llama_sbatch_seq & s = seq[i];
  2863. GGML_ASSERT(s.length > 0);
  2864. if (length == 0) {
  2865. length = s.length < n_ubatch ? s.length : n_ubatch;
  2866. }
  2867. add_seq_to_ubatch(ubatch, s, length);
  2868. n_tokens_in_ubatch += length;
  2869. // shared prompts can't be mixed with any of their sequences,
  2870. // so it's safer to compute them in their own ubatch
  2871. if (s.n_seq_id > 1) { break; }
  2872. // stop when there isn't enough space for another sequence
  2873. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  2874. }
  2875. }
  2876. return ubatch;
  2877. }
  2878. // sequence-wise split
  2879. llama_ubatch split_seq(size_t n_ubatch) {
  2880. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2881. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2882. if (!seq.empty()) {
  2883. llama_sbatch_seq & s = seq[seq.size() - 1];
  2884. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  2885. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  2886. add_seq_to_ubatch(ubatch, s, length);
  2887. }
  2888. return ubatch;
  2889. }
  2890. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  2891. GGML_ASSERT(batch.n_tokens >= 0);
  2892. this->batch = &batch;
  2893. this->n_embd = n_embd;
  2894. this->logits_all = logits_all;
  2895. n_tokens = batch.n_tokens;
  2896. ids.resize(n_tokens);
  2897. out_ids.clear();
  2898. // TODO: reserve out_ids and seq
  2899. for (size_t i = 0; i < n_tokens; ++i) {
  2900. ids[i] = i;
  2901. }
  2902. if (simple_split) {
  2903. seq.resize(1);
  2904. llama_sbatch_seq & s = seq[0];
  2905. s.n_seq_id = 0;
  2906. s.seq_id = nullptr;
  2907. s.offset = 0;
  2908. s.length = n_tokens;
  2909. return;
  2910. }
  2911. std::sort(ids.begin(), ids.end(),
  2912. [&batch](size_t a, size_t b) {
  2913. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  2914. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  2915. // sort by seq_id, then by pos
  2916. if (n_seq_a == n_seq_b) {
  2917. if (batch.seq_id) {
  2918. for (int32_t i = 0; i < n_seq_a; ++i) {
  2919. llama_seq_id seq_id_a = batch.seq_id[a][i];
  2920. llama_seq_id seq_id_b = batch.seq_id[b][i];
  2921. // smaller seq_ids go first
  2922. if (seq_id_a != seq_id_b) {
  2923. return seq_id_a < seq_id_b;
  2924. }
  2925. }
  2926. }
  2927. // when all else is equal, sort by pos
  2928. if (batch.pos) {
  2929. return batch.pos[a] < batch.pos[b];
  2930. }
  2931. // no pos, sort by id
  2932. return a < b;
  2933. }
  2934. // shared prompts go first
  2935. return n_seq_a > n_seq_b;
  2936. }
  2937. );
  2938. // init seq
  2939. llama_sbatch_seq * last_seq = nullptr;
  2940. for (size_t i = 0; i < n_tokens; ++i) {
  2941. const size_t bi = ids[i];
  2942. const int32_t n_seqs = batch.n_seq_id[bi];
  2943. llama_seq_id * seq_ids = batch.seq_id[bi];
  2944. if (last_seq != nullptr) {
  2945. bool same = n_seqs == last_seq->n_seq_id;
  2946. for (int32_t j = 0; same && j < n_seqs; ++j) {
  2947. if (seq_ids[j] != last_seq->seq_id[j]) {
  2948. same = false;
  2949. }
  2950. }
  2951. if (same) {
  2952. last_seq->length += 1;
  2953. continue;
  2954. }
  2955. }
  2956. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1};
  2957. seq.push_back(new_seq);
  2958. last_seq = &seq.back();
  2959. }
  2960. // keep shared prompts first at the end, then sort by length descending.
  2961. std::sort(seq.begin(), seq.end(),
  2962. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  2963. if (a.n_seq_id == b.n_seq_id) {
  2964. return a.length > b.length;
  2965. }
  2966. return a.n_seq_id < b.n_seq_id;
  2967. }
  2968. );
  2969. }
  2970. };
  2971. struct llama_context {
  2972. llama_context(const llama_model & model)
  2973. : model(model)
  2974. , t_start_us(model.t_start_us)
  2975. , t_load_us(model.t_load_us) {}
  2976. ~llama_context() {
  2977. ggml_backend_sched_free(sched);
  2978. for (ggml_backend_t backend : backends) {
  2979. ggml_backend_free(backend);
  2980. }
  2981. ggml_backend_buffer_free(buf_output);
  2982. }
  2983. const struct llama_model & model;
  2984. struct llama_cparams cparams;
  2985. struct llama_sbatch sbatch;
  2986. struct llama_kv_cache kv_self;
  2987. struct llama_control_vector cvec;
  2988. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  2989. std::vector<ggml_backend_t> backends;
  2990. std::vector<std::pair<ggml_backend_t, ggml_backend_set_n_threads_t>> set_n_threads_fns;
  2991. ggml_backend_t backend_cpu = nullptr;
  2992. ggml_threadpool_t threadpool = nullptr;
  2993. ggml_threadpool_t threadpool_batch = nullptr;
  2994. bool has_evaluated_once = false;
  2995. mutable int64_t t_start_us;
  2996. mutable int64_t t_load_us;
  2997. mutable int64_t t_p_eval_us = 0;
  2998. mutable int64_t t_eval_us = 0;
  2999. mutable int64_t t_compute_start_us = 0;
  3000. mutable int64_t n_queued_tokens = 0;
  3001. mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  3002. mutable int32_t n_eval = 0; // number of eval calls
  3003. // host buffer for the model output (logits and embeddings)
  3004. ggml_backend_buffer_t buf_output = nullptr;
  3005. // decode output (2-dimensional array: [n_outputs][n_vocab])
  3006. size_t logits_size = 0; // capacity (of floats) for logits
  3007. float * logits = nullptr;
  3008. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  3009. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  3010. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  3011. bool logits_all = false;
  3012. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  3013. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  3014. size_t embd_size = 0; // capacity (of floats) for embeddings
  3015. float * embd = nullptr;
  3016. // sequence embeddings output (map of [n_embd] vectors)
  3017. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  3018. std::map<llama_seq_id, std::vector<float>> embd_seq;
  3019. // whether we are computing encoder output or decoder output
  3020. bool is_encoding = false;
  3021. // output of the encoder part of the encoder-decoder models
  3022. std::vector<float> embd_enc;
  3023. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  3024. // memory buffers used to evaluate the model
  3025. std::vector<uint8_t> buf_compute_meta;
  3026. ggml_backend_sched_t sched = nullptr;
  3027. ggml_abort_callback abort_callback = nullptr;
  3028. void * abort_callback_data = nullptr;
  3029. // input tensors
  3030. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  3031. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  3032. struct ggml_tensor * inp_pos; // I32 [n_batch]
  3033. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  3034. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  3035. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  3036. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  3037. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  3038. struct ggml_tensor * inp_cls; // I32 [n_batch]
  3039. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  3040. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  3041. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  3042. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  3043. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  3044. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  3045. };
  3046. struct llama_lora_weight {
  3047. struct ggml_tensor * a = nullptr;
  3048. struct ggml_tensor * b = nullptr;
  3049. llama_lora_weight() = default;
  3050. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  3051. };
  3052. struct llama_lora_adapter {
  3053. struct llama_model * base_model;
  3054. // map tensor name to lora_a_b
  3055. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  3056. std::vector<struct ggml_context *> ctxs;
  3057. std::vector<ggml_backend_buffer_t> bufs;
  3058. float alpha;
  3059. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  3060. base_model->lora_adapters.insert(this);
  3061. }
  3062. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  3063. std::string name(w->name);
  3064. auto pos = ab_map.find(name);
  3065. if (ab_map.find(name) != ab_map.end()) {
  3066. return &pos->second;
  3067. }
  3068. return nullptr;
  3069. }
  3070. ~llama_lora_adapter() {
  3071. for (struct ggml_context * ctx : ctxs) {
  3072. ggml_free(ctx);
  3073. }
  3074. for (ggml_backend_buffer_t buf : bufs) {
  3075. ggml_backend_buffer_free(buf);
  3076. }
  3077. auto pos = base_model->lora_adapters.find(this);
  3078. if (pos != base_model->lora_adapters.end()) {
  3079. base_model->lora_adapters.erase(pos);
  3080. }
  3081. }
  3082. };
  3083. static int llama_get_device_count(const llama_model & model) {
  3084. int count = (int) model.devices.size();
  3085. #if defined(GGML_USE_RPC)
  3086. count += (int) model.rpc_servers.size();
  3087. #endif
  3088. #if defined(GGML_USE_CANN)
  3089. count += ggml_backend_cann_get_device_count();
  3090. #endif
  3091. return count;
  3092. GGML_UNUSED(model);
  3093. }
  3094. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(const llama_model & model, bool host_buffer) {
  3095. ggml_backend_buffer_type_t buft = nullptr;
  3096. if (host_buffer) {
  3097. for (auto * dev : model.devices) {
  3098. buft = ggml_backend_dev_host_buffer_type(dev);
  3099. if (buft != nullptr) {
  3100. break;
  3101. }
  3102. }
  3103. }
  3104. #if defined(GGML_USE_CANN)
  3105. if (host_buffer) {
  3106. buft = ggml_backend_cann_host_buffer_type();
  3107. }
  3108. #elif defined(GGML_USE_CPU_HBM)
  3109. buft = ggml_backend_cpu_hbm_buffer_type();
  3110. #endif
  3111. if (buft == nullptr) {
  3112. buft = ggml_backend_cpu_buffer_type();
  3113. }
  3114. return buft;
  3115. GGML_UNUSED(host_buffer);
  3116. }
  3117. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int device) {
  3118. ggml_backend_buffer_type_t buft = nullptr;
  3119. if (device < (int)model.devices.size()) {
  3120. return ggml_backend_dev_buffer_type(model.devices[device]);
  3121. }
  3122. device -= (int)model.devices.size();
  3123. #if defined(GGML_USE_KOMPUTE)
  3124. buft = ggml_backend_kompute_buffer_type(device);
  3125. #elif defined(GGML_USE_CANN)
  3126. buft = ggml_backend_cann_buffer_type(device);
  3127. #endif
  3128. if (buft == nullptr) {
  3129. buft = llama_default_buffer_type_cpu(model, true);
  3130. }
  3131. return buft;
  3132. GGML_UNUSED(model);
  3133. }
  3134. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  3135. ggml_backend_buffer_type_t buft = nullptr;
  3136. // find a backend that supports split buffers
  3137. for (size_t i = 0; i < ggml_backend_reg_count(); ++i) {
  3138. ggml_backend_reg_t reg = ggml_backend_reg_get(i);
  3139. auto ggml_backend_split_buffer_type_fn = (ggml_backend_split_buffer_type_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_split_buffer_type");
  3140. if (ggml_backend_split_buffer_type_fn) {
  3141. buft = ggml_backend_split_buffer_type_fn(tensor_split);
  3142. if (buft != nullptr) {
  3143. break;
  3144. }
  3145. }
  3146. }
  3147. if (buft == nullptr) {
  3148. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  3149. }
  3150. return buft;
  3151. GGML_UNUSED(tensor_split);
  3152. }
  3153. static size_t llama_get_device_memory(const llama_model & model, int device) {
  3154. if (device < (int)model.devices.size()) {
  3155. ggml_backend_dev_t dev = model.devices[device];
  3156. size_t total;
  3157. size_t free;
  3158. ggml_backend_dev_memory(dev, &free, &total);
  3159. return free;
  3160. }
  3161. #if defined(GGML_USE_CANN)
  3162. size_t total;
  3163. size_t free;
  3164. ggml_backend_cann_get_device_memory(device, &free, &total);
  3165. return free;
  3166. #else
  3167. return 1;
  3168. #endif
  3169. GGML_UNUSED(model);
  3170. GGML_UNUSED(device);
  3171. }
  3172. //
  3173. // kv cache helpers
  3174. //
  3175. static bool llama_kv_cache_init(
  3176. struct llama_kv_cache & cache,
  3177. const llama_context * ctx,
  3178. ggml_type type_k,
  3179. ggml_type type_v,
  3180. uint32_t kv_size,
  3181. bool offload) {
  3182. const llama_model & model = ctx->model;
  3183. const llama_cparams & cparams = ctx->cparams;
  3184. const struct llama_hparams & hparams = model.hparams;
  3185. const int64_t n_layer = hparams.n_layer;
  3186. cache.has_shift = false;
  3187. cache.recurrent = llama_model_is_recurrent(&model);
  3188. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3189. cache.head = 0;
  3190. cache.size = kv_size;
  3191. cache.used = 0;
  3192. cache.type_k = type_k;
  3193. cache.type_v = type_v;
  3194. cache.cells.clear();
  3195. cache.cells.resize(kv_size);
  3196. // count used buffer types
  3197. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3198. if (offload) {
  3199. for (int64_t i = 0; i < n_layer; ++i) {
  3200. buft_layer_count[model.buft_layer[i].buft]++;
  3201. }
  3202. } else {
  3203. buft_layer_count[llama_default_buffer_type_cpu(model, true)] = n_layer;
  3204. }
  3205. // create a context for each buffer type
  3206. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3207. for (auto & it : buft_layer_count) {
  3208. int n_layers = it.second;
  3209. struct ggml_init_params params = {
  3210. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  3211. /*.mem_buffer =*/ NULL,
  3212. /*.no_alloc =*/ true,
  3213. };
  3214. ggml_context * ctx = ggml_init(params);
  3215. if (!ctx) {
  3216. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  3217. return false;
  3218. }
  3219. ctx_map[it.first] = ctx;
  3220. cache.ctxs.push_back(ctx);
  3221. }
  3222. cache.k_l.reserve(n_layer);
  3223. cache.v_l.reserve(n_layer);
  3224. for (int i = 0; i < (int) n_layer; i++) {
  3225. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3226. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3227. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3228. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3229. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3230. ggml_format_name(k, "cache_k_l%d", i);
  3231. ggml_format_name(v, "cache_v_l%d", i);
  3232. cache.k_l.push_back(k);
  3233. cache.v_l.push_back(v);
  3234. }
  3235. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3236. for (auto it : ctx_map) {
  3237. ggml_backend_buffer_type_t buft = it.first;
  3238. ggml_context * ctx = it.second;
  3239. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3240. if (!buf) {
  3241. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3242. return false;
  3243. }
  3244. ggml_backend_buffer_clear(buf, 0);
  3245. 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);
  3246. cache.bufs.push_back(buf);
  3247. }
  3248. return true;
  3249. }
  3250. // find an empty slot of size "n_tokens" in the cache
  3251. // updates the cache head
  3252. // Note: On success, it's important that cache.head points
  3253. // to the first cell of the slot.
  3254. static bool llama_kv_cache_find_slot(
  3255. struct llama_kv_cache & cache,
  3256. const struct llama_ubatch & batch) {
  3257. const uint32_t n_tokens = batch.n_tokens;
  3258. const uint32_t n_seqs = batch.n_seqs;
  3259. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3260. if (cache.recurrent) {
  3261. // For recurrent state architectures (like Mamba or RWKV),
  3262. // each cache cell can store the state for a whole sequence.
  3263. // A slot should be always be contiguous.
  3264. // can only process batches with an equal number of new tokens in each sequence
  3265. GGML_ASSERT(batch.equal_seqs);
  3266. int32_t min = cache.size - 1;
  3267. int32_t max = 0;
  3268. // everything should fit if all seq_ids are smaller than the max
  3269. for (uint32_t s = 0; s < n_seqs; ++s) {
  3270. const uint32_t n_seq_id = batch.n_seq_id[s];
  3271. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3272. const llama_seq_id seq_id = batch.seq_id[s][j];
  3273. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3274. // too big seq_id
  3275. // TODO: would it be possible to resize the cache instead?
  3276. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3277. return false;
  3278. }
  3279. if (j > 0) {
  3280. llama_kv_cell & seq = cache.cells[seq_id];
  3281. if (seq.tail >= 0) {
  3282. llama_kv_cell & cell = cache.cells[seq.tail];
  3283. // clear cells from seq_ids that become shared
  3284. // (should not normally happen, but let's handle it anyway)
  3285. cell.seq_id.erase(seq_id);
  3286. seq.tail = -1;
  3287. if (cell.seq_id.empty()) {
  3288. cell.pos = -1;
  3289. cell.src = -1;
  3290. cache.used -= 1;
  3291. }
  3292. }
  3293. }
  3294. }
  3295. }
  3296. #ifndef NDEBUG
  3297. {
  3298. std::vector<int32_t> tails_verif;
  3299. tails_verif.assign(cache.size, -1);
  3300. for (uint32_t i = 0; i < cache.size; ++i) {
  3301. llama_kv_cell & cell = cache.cells[i];
  3302. for (llama_seq_id seq_id : cell.seq_id) {
  3303. if (tails_verif[seq_id] != -1) {
  3304. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3305. }
  3306. tails_verif[seq_id] = i;
  3307. }
  3308. }
  3309. for (uint32_t i = 0; i < cache.size; ++i) {
  3310. if (tails_verif[i] != cache.cells[i].tail) {
  3311. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3312. }
  3313. }
  3314. }
  3315. #endif
  3316. // find next empty cell
  3317. uint32_t next_empty_cell = cache.head;
  3318. for (uint32_t i = 0; i < cache.size; ++i) {
  3319. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3320. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3321. if (cell.is_empty()) { break; }
  3322. next_empty_cell += 1;
  3323. }
  3324. // find usable cell range
  3325. for (uint32_t s = 0; s < n_seqs; ++s) {
  3326. const llama_seq_id seq_id = batch.seq_id[s][0];
  3327. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3328. bool has_cell = false;
  3329. if (seq_meta.tail >= 0) {
  3330. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3331. GGML_ASSERT(cell.has_seq_id(seq_id));
  3332. // does this seq_id "own" the cell?
  3333. if (cell.seq_id.size() == 1) { has_cell = true; }
  3334. }
  3335. if (!has_cell) {
  3336. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3337. GGML_ASSERT(empty_cell.is_empty());
  3338. // copy old tail into the empty cell
  3339. if (seq_meta.tail >= 0) {
  3340. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3341. empty_cell.pos = orig_cell.pos;
  3342. empty_cell.src = orig_cell.src;
  3343. orig_cell.seq_id.erase(seq_id);
  3344. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3345. }
  3346. seq_meta.tail = next_empty_cell;
  3347. // find next empty cell
  3348. if (s + 1 < n_seqs) {
  3349. next_empty_cell += 1;
  3350. for (uint32_t i = 0; i < cache.size; ++i) {
  3351. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3352. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3353. if (cell.is_empty()) { break; }
  3354. next_empty_cell += 1;
  3355. }
  3356. }
  3357. }
  3358. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3359. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3360. }
  3361. // gather and re-order
  3362. for (uint32_t s = 0; s < n_seqs; ++s) {
  3363. int32_t dst_id = s + min;
  3364. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3365. if (dst_id != src_id) {
  3366. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3367. llama_kv_cell & src_cell = cache.cells[src_id];
  3368. std::swap(dst_cell.pos, src_cell.pos);
  3369. std::swap(dst_cell.src, src_cell.src);
  3370. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3371. // swap tails (assuming they NEVER overlap)
  3372. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3373. cache.cells[seq_id].tail = src_id;
  3374. }
  3375. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3376. cache.cells[seq_id].tail = dst_id;
  3377. }
  3378. }
  3379. }
  3380. // update the pos of the used seqs
  3381. for (uint32_t s = 0; s < n_seqs; ++s) {
  3382. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3383. int32_t cell_id = s + min;
  3384. llama_kv_cell & cell = cache.cells[cell_id];
  3385. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3386. // What should happen when the pos backtracks or skips a value?
  3387. // Clearing the state mid-batch would require special-casing which isn't done.
  3388. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3389. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3390. }
  3391. cell.pos = last_pos;
  3392. cell.seq_id.clear();
  3393. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3394. const llama_seq_id seq_id = batch.seq_id[s][j];
  3395. cell.seq_id.insert(seq_id);
  3396. cache.cells[seq_id].tail = cell_id;
  3397. }
  3398. }
  3399. // allow getting the range of used cells, from head to head + n
  3400. cache.head = min;
  3401. cache.n = max - min + 1;
  3402. // sanity check
  3403. return cache.n >= n_seqs;
  3404. }
  3405. // otherwise, one cell per token.
  3406. if (n_tokens > cache.size) {
  3407. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3408. return false;
  3409. }
  3410. uint32_t n_tested = 0;
  3411. while (true) {
  3412. if (cache.head + n_tokens > cache.size) {
  3413. n_tested += cache.size - cache.head;
  3414. cache.head = 0;
  3415. continue;
  3416. }
  3417. bool found = true;
  3418. for (uint32_t i = 0; i < n_tokens; i++) {
  3419. if (cache.cells[cache.head + i].pos >= 0) {
  3420. found = false;
  3421. cache.head += i + 1;
  3422. n_tested += i + 1;
  3423. break;
  3424. }
  3425. }
  3426. if (found) {
  3427. break;
  3428. }
  3429. if (n_tested >= cache.size) {
  3430. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3431. return false;
  3432. }
  3433. }
  3434. for (uint32_t s = 0; s < n_seqs; s++) {
  3435. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3436. uint32_t k = s*n_seq_tokens + i;
  3437. cache.cells[cache.head + k].pos = batch.pos[k];
  3438. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3439. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3440. }
  3441. }
  3442. }
  3443. cache.used += n_tokens;
  3444. return true;
  3445. }
  3446. // find how many cells are currently in use
  3447. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3448. for (uint32_t i = cache.size; i > 0; --i) {
  3449. const llama_kv_cell & cell = cache.cells[i - 1];
  3450. if (cell.pos >= 0 && !cell.is_empty()) {
  3451. return i;
  3452. }
  3453. }
  3454. return 0;
  3455. }
  3456. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3457. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3458. cache.cells[i].pos = -1;
  3459. cache.cells[i].seq_id.clear();
  3460. cache.cells[i].src = -1;
  3461. cache.cells[i].tail = -1;
  3462. }
  3463. cache.head = 0;
  3464. cache.used = 0;
  3465. for (auto & buf : cache.bufs) {
  3466. ggml_backend_buffer_clear(buf, 0);
  3467. }
  3468. }
  3469. static bool llama_kv_cache_seq_rm(
  3470. struct llama_kv_cache & cache,
  3471. llama_seq_id seq_id,
  3472. llama_pos p0,
  3473. llama_pos p1) {
  3474. uint32_t new_head = cache.size;
  3475. if (p0 < 0) p0 = 0;
  3476. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3477. // models like Mamba or RWKV can't have a state partially erased
  3478. if (cache.recurrent) {
  3479. if (seq_id >= (int64_t) cache.size) {
  3480. // could be fatal
  3481. return false;
  3482. }
  3483. if (0 <= seq_id) {
  3484. int32_t & tail_id = cache.cells[seq_id].tail;
  3485. if (tail_id >= 0) {
  3486. const llama_kv_cell & cell = cache.cells[tail_id];
  3487. // partial intersection is invalid
  3488. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3489. return false;
  3490. }
  3491. // invalidate tails which will be cleared
  3492. if (p0 <= cell.pos && cell.pos < p1) {
  3493. tail_id = -1;
  3494. }
  3495. }
  3496. } else {
  3497. // seq_id is negative, then the range should include everything or nothing
  3498. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3499. return false;
  3500. }
  3501. }
  3502. }
  3503. for (uint32_t i = 0; i < cache.size; ++i) {
  3504. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3505. if (seq_id < 0) {
  3506. cache.cells[i].seq_id.clear();
  3507. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3508. cache.cells[i].seq_id.erase(seq_id);
  3509. } else {
  3510. continue;
  3511. }
  3512. if (cache.cells[i].is_empty()) {
  3513. // keep count of the number of used cells
  3514. if (cache.cells[i].pos >= 0) cache.used--;
  3515. cache.cells[i].pos = -1;
  3516. cache.cells[i].src = -1;
  3517. if (new_head == cache.size) new_head = i;
  3518. }
  3519. }
  3520. }
  3521. // If we freed up a slot, set head to it so searching can start there.
  3522. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3523. return true;
  3524. }
  3525. static void llama_kv_cache_seq_cp(
  3526. struct llama_kv_cache & cache,
  3527. llama_seq_id seq_id_src,
  3528. llama_seq_id seq_id_dst,
  3529. llama_pos p0,
  3530. llama_pos p1) {
  3531. if (p0 < 0) p0 = 0;
  3532. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3533. if (cache.recurrent) {
  3534. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3535. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3536. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3537. if (tail_dst.tail >= 0) {
  3538. // clear destination seq_id if it wasn't empty
  3539. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3540. cell_dst.seq_id.erase(seq_id_dst);
  3541. tail_dst.tail = -1;
  3542. if (cell_dst.seq_id.empty()) {
  3543. cell_dst.pos = -1;
  3544. cell_dst.delta = -1;
  3545. cell_dst.src = -1;
  3546. cache.used -= 1;
  3547. }
  3548. }
  3549. if (tail_src.tail >= 0) {
  3550. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3551. cell_src.seq_id.insert(seq_id_dst);
  3552. tail_dst.tail = tail_src.tail;
  3553. }
  3554. }
  3555. return;
  3556. }
  3557. // otherwise, this is the KV cache of a Transformer-like model
  3558. cache.head = 0;
  3559. for (uint32_t i = 0; i < cache.size; ++i) {
  3560. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3561. cache.cells[i].seq_id.insert(seq_id_dst);
  3562. }
  3563. }
  3564. }
  3565. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3566. uint32_t new_head = cache.size;
  3567. for (uint32_t i = 0; i < cache.size; ++i) {
  3568. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3569. cache.cells[i].tail = -1;
  3570. }
  3571. if (!cache.cells[i].has_seq_id(seq_id)) {
  3572. if (cache.cells[i].pos >= 0) cache.used--;
  3573. cache.cells[i].pos = -1;
  3574. cache.cells[i].src = -1;
  3575. cache.cells[i].seq_id.clear();
  3576. if (new_head == cache.size) new_head = i;
  3577. } else {
  3578. cache.cells[i].seq_id.clear();
  3579. cache.cells[i].seq_id.insert(seq_id);
  3580. }
  3581. }
  3582. // If we freed up a slot, set head to it so searching can start there.
  3583. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3584. }
  3585. static void llama_kv_cache_seq_add(
  3586. struct llama_kv_cache & cache,
  3587. llama_seq_id seq_id,
  3588. llama_pos p0,
  3589. llama_pos p1,
  3590. llama_pos delta) {
  3591. uint32_t new_head = cache.size;
  3592. if (p0 < 0) p0 = 0;
  3593. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3594. // If there is no range then return early to avoid looping over the cache.
  3595. if (p0 == p1) return;
  3596. if (cache.recurrent) {
  3597. // for Mamba-like or RWKV models, only the pos needs to be shifted
  3598. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3599. const int32_t tail_id = cache.cells[seq_id].tail;
  3600. if (tail_id >= 0) {
  3601. llama_kv_cell & cell = cache.cells[tail_id];
  3602. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3603. cell.pos += delta;
  3604. }
  3605. }
  3606. }
  3607. return;
  3608. }
  3609. for (uint32_t i = 0; i < cache.size; ++i) {
  3610. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3611. cache.has_shift = true;
  3612. cache.cells[i].pos += delta;
  3613. cache.cells[i].delta += delta;
  3614. if (cache.cells[i].pos < 0) {
  3615. if (!cache.cells[i].is_empty()) {
  3616. cache.used--;
  3617. }
  3618. cache.cells[i].pos = -1;
  3619. cache.cells[i].seq_id.clear();
  3620. if (new_head == cache.size) {
  3621. new_head = i;
  3622. }
  3623. }
  3624. }
  3625. }
  3626. // If we freed up a slot, set head to it so searching can start there.
  3627. // Otherwise we just start the next search from the beginning.
  3628. cache.head = new_head != cache.size ? new_head : 0;
  3629. }
  3630. static void llama_kv_cache_seq_div(
  3631. struct llama_kv_cache & cache,
  3632. llama_seq_id seq_id,
  3633. llama_pos p0,
  3634. llama_pos p1,
  3635. int d) {
  3636. if (p0 < 0) p0 = 0;
  3637. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3638. // If there is no range then return early to avoid looping over the cache.
  3639. if (p0 == p1) return;
  3640. if (cache.recurrent) {
  3641. // for Mamba-like or RWKV models, only the pos needs to be changed
  3642. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3643. const int32_t tail_id = cache.cells[seq_id].tail;
  3644. if (tail_id >= 0) {
  3645. llama_kv_cell & cell = cache.cells[tail_id];
  3646. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3647. cell.pos /= d;
  3648. }
  3649. }
  3650. }
  3651. return;
  3652. }
  3653. for (uint32_t i = 0; i < cache.size; ++i) {
  3654. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3655. cache.has_shift = true;
  3656. {
  3657. llama_pos p_old = cache.cells[i].pos;
  3658. cache.cells[i].pos /= d;
  3659. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3660. }
  3661. }
  3662. }
  3663. }
  3664. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3665. llama_pos result = 0;
  3666. for (uint32_t i = 0; i < cache.size; ++i) {
  3667. if (cache.cells[i].has_seq_id(seq_id)) {
  3668. result = std::max(result, cache.cells[i].pos);
  3669. }
  3670. }
  3671. return result;
  3672. }
  3673. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3674. if (!cache.recurrent) {
  3675. cache.do_defrag = true;
  3676. }
  3677. }
  3678. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3679. // the FA kernels require padding to avoid extra runtime boundary checks
  3680. return cparams.flash_attn ? 256u : 32u;
  3681. }
  3682. //
  3683. // model loading and saving
  3684. //
  3685. enum llama_fver {
  3686. GGUF_FILE_VERSION_V1 = 1,
  3687. GGUF_FILE_VERSION_V2 = 2,
  3688. GGUF_FILE_VERSION_V3 = 3,
  3689. };
  3690. static const char * llama_file_version_name(llama_fver version) {
  3691. switch (version) {
  3692. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3693. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3694. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3695. }
  3696. return "unknown";
  3697. }
  3698. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3699. char buf[256];
  3700. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3701. for (size_t i = 1; i < ne.size(); i++) {
  3702. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3703. }
  3704. return buf;
  3705. }
  3706. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3707. char buf[256];
  3708. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3709. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3710. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3711. }
  3712. return buf;
  3713. }
  3714. namespace GGUFMeta {
  3715. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3716. struct GKV_Base_Type {
  3717. static constexpr gguf_type gt = gt_;
  3718. static T getter(const gguf_context * ctx, const int kid) {
  3719. return gfun(ctx, kid);
  3720. }
  3721. };
  3722. template<typename T> struct GKV_Base;
  3723. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3724. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3725. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3726. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3727. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3728. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3729. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3730. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3731. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3732. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3733. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3734. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3735. template<> struct GKV_Base<std::string> {
  3736. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3737. static std::string getter(const gguf_context * ctx, const int kid) {
  3738. return gguf_get_val_str(ctx, kid);
  3739. }
  3740. };
  3741. struct ArrayInfo {
  3742. const gguf_type gt;
  3743. const size_t length;
  3744. const void * data;
  3745. };
  3746. template<> struct GKV_Base<ArrayInfo> {
  3747. public:
  3748. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3749. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3750. return ArrayInfo {
  3751. gguf_get_arr_type(ctx, k),
  3752. size_t(gguf_get_arr_n(ctx, k)),
  3753. gguf_get_arr_data(ctx, k),
  3754. };
  3755. }
  3756. };
  3757. template<typename T>
  3758. class GKV : public GKV_Base<T> {
  3759. GKV() = delete;
  3760. public:
  3761. static T get_kv(const gguf_context * ctx, const int k) {
  3762. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3763. if (kt != GKV::gt) {
  3764. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3765. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3766. }
  3767. return GKV::getter(ctx, k);
  3768. }
  3769. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3770. switch (ty) {
  3771. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3772. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3773. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3774. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3775. }
  3776. return "unknown";
  3777. }
  3778. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3779. if (!ovrd) { return false; }
  3780. if (ovrd->tag == expected_type) {
  3781. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3782. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3783. switch (ovrd->tag) {
  3784. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3785. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3786. } break;
  3787. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3788. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3789. } break;
  3790. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3791. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3792. } break;
  3793. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3794. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  3795. } break;
  3796. default:
  3797. // Shouldn't be possible to end up here, but just in case...
  3798. throw std::runtime_error(
  3799. format("Unsupported attempt to override %s type for metadata key %s\n",
  3800. override_type_to_str(ovrd->tag), ovrd->key));
  3801. }
  3802. return true;
  3803. }
  3804. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  3805. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  3806. return false;
  3807. }
  3808. template<typename OT>
  3809. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  3810. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3811. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  3812. target = ovrd->val_bool;
  3813. return true;
  3814. }
  3815. return false;
  3816. }
  3817. template<typename OT>
  3818. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  3819. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3820. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  3821. target = ovrd->val_i64;
  3822. return true;
  3823. }
  3824. return false;
  3825. }
  3826. template<typename OT>
  3827. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  3828. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3829. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  3830. target = ovrd->val_f64;
  3831. return true;
  3832. }
  3833. return false;
  3834. }
  3835. template<typename OT>
  3836. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  3837. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3838. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  3839. target = ovrd->val_str;
  3840. return true;
  3841. }
  3842. return false;
  3843. }
  3844. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3845. if (try_override<T>(target, ovrd)) {
  3846. return true;
  3847. }
  3848. if (k < 0) { return false; }
  3849. target = get_kv(ctx, k);
  3850. return true;
  3851. }
  3852. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3853. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  3854. }
  3855. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3856. return set(ctx, key.c_str(), target, ovrd);
  3857. }
  3858. };
  3859. }
  3860. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  3861. static size_t llama_model_max_nodes(const llama_model & model) {
  3862. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  3863. }
  3864. struct llama_model_loader {
  3865. int n_kv = 0;
  3866. int n_tensors = 0;
  3867. int n_created = 0;
  3868. int64_t n_elements = 0;
  3869. size_t n_bytes = 0;
  3870. bool use_mmap = false;
  3871. bool check_tensors;
  3872. llama_files files;
  3873. llama_ftype ftype;
  3874. llama_fver fver;
  3875. llama_mmaps mappings;
  3876. // Holds information on a model weight
  3877. struct llama_tensor_weight {
  3878. uint16_t idx; // source file index
  3879. size_t offs; // tensor data offset in the original file
  3880. ggml_tensor * tensor;
  3881. 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) {
  3882. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  3883. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  3884. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  3885. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  3886. }
  3887. }
  3888. };
  3889. std::vector<llama_tensor_weight> weights;
  3890. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  3891. struct gguf_context * meta = NULL;
  3892. std::vector<ggml_context *> contexts;
  3893. std::string arch_name;
  3894. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  3895. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  3896. int trace = 0;
  3897. if (getenv("LLAMA_TRACE")) {
  3898. trace = atoi(getenv("LLAMA_TRACE"));
  3899. }
  3900. if (param_overrides_p != nullptr) {
  3901. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  3902. kv_overrides.insert({std::string(p->key), *p});
  3903. }
  3904. }
  3905. struct ggml_context * ctx = NULL;
  3906. struct gguf_init_params params = {
  3907. /*.no_alloc = */ true,
  3908. /*.ctx = */ &ctx,
  3909. };
  3910. meta = gguf_init_from_file(fname.c_str(), params);
  3911. if (!meta) {
  3912. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  3913. }
  3914. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  3915. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  3916. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  3917. contexts.emplace_back(ctx);
  3918. // Save tensors data offset of the main file.
  3919. // For subsidiary files, `meta` tensor data offset must not be used,
  3920. // so we build a unified tensors index for weights.
  3921. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3922. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  3923. }
  3924. uint16_t n_split = 0;
  3925. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  3926. // Load additional GGML contexts
  3927. if (n_split > 1) {
  3928. uint16_t idx = 0;
  3929. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  3930. if (idx != 0) {
  3931. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  3932. }
  3933. char split_prefix[PATH_MAX] = {0};
  3934. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  3935. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  3936. }
  3937. if (trace > 0) {
  3938. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  3939. }
  3940. char split_path[PATH_MAX] = {0};
  3941. for (idx = 1; idx < n_split; idx++) {
  3942. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  3943. struct gguf_init_params split_params = {
  3944. /*.no_alloc = */ true,
  3945. /*.ctx = */ &ctx,
  3946. };
  3947. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  3948. if (!ctx_gguf) {
  3949. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  3950. }
  3951. files.emplace_back(new llama_file(split_path, "rb"));
  3952. contexts.emplace_back(ctx);
  3953. // Save tensors data offset info of the shard.
  3954. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3955. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  3956. }
  3957. gguf_free(ctx_gguf);
  3958. }
  3959. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  3960. // sanity check
  3961. {
  3962. const int n_tensors_loaded = (int) weights.size();
  3963. if (n_tensors != n_tensors_loaded) {
  3964. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  3965. }
  3966. }
  3967. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  3968. }
  3969. n_kv = gguf_get_n_kv(meta);
  3970. n_tensors = weights.size();
  3971. fver = (enum llama_fver) gguf_get_version(meta);
  3972. std::set<std::string> tensor_names;
  3973. for (auto & w : weights) {
  3974. n_elements += ggml_nelements(w.tensor);
  3975. n_bytes += ggml_nbytes(w.tensor);
  3976. // make sure there is no duplicated tensor names
  3977. const std::string name(w.tensor->name);
  3978. auto found = tensor_names.find(name);
  3979. if (found != tensor_names.end()) {
  3980. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  3981. }
  3982. tensor_names.insert(name);
  3983. }
  3984. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  3985. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  3986. // determine file type based on the number of tensors for each quantization and print meta data
  3987. // TODO: make optional
  3988. {
  3989. std::map<enum ggml_type, uint32_t> n_type;
  3990. uint32_t n_type_max = 0;
  3991. enum ggml_type type_max = GGML_TYPE_F32;
  3992. for (int i = 0; i < n_tensors; i++) {
  3993. const ggml_tensor * tensor = weights.at(i).tensor;
  3994. enum ggml_type type = tensor->type;
  3995. n_type[type]++;
  3996. if (n_type_max < n_type[type]) {
  3997. n_type_max = n_type[type];
  3998. type_max = type;
  3999. }
  4000. if (trace > 0) {
  4001. const uint16_t sid = weights.at(i).idx;
  4002. 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());
  4003. }
  4004. }
  4005. switch (type_max) {
  4006. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  4007. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  4008. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  4009. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  4010. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  4011. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  4012. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  4013. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  4014. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  4015. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  4016. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  4017. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  4018. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  4019. case GGML_TYPE_TQ1_0: ftype = LLAMA_FTYPE_MOSTLY_TQ1_0; break;
  4020. case GGML_TYPE_TQ2_0: ftype = LLAMA_FTYPE_MOSTLY_TQ2_0; break;
  4021. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  4022. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  4023. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  4024. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  4025. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  4026. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  4027. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  4028. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  4029. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  4030. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  4031. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  4032. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  4033. default:
  4034. {
  4035. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  4036. ftype = LLAMA_FTYPE_ALL_F32;
  4037. } break;
  4038. }
  4039. // this is a way to mark that we have "guessed" the file type
  4040. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  4041. {
  4042. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  4043. if (kid >= 0) {
  4044. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  4045. }
  4046. }
  4047. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  4048. for (int i = 0; i < n_kv; i++) {
  4049. const char * name = gguf_get_key(meta, i);
  4050. const enum gguf_type type = gguf_get_kv_type(meta, i);
  4051. const std::string type_name =
  4052. type == GGUF_TYPE_ARRAY
  4053. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  4054. : gguf_type_name(type);
  4055. std::string value = gguf_kv_to_str(meta, i);
  4056. const size_t MAX_VALUE_LEN = 40;
  4057. if (value.size() > MAX_VALUE_LEN) {
  4058. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  4059. }
  4060. replace_all(value, "\n", "\\n");
  4061. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  4062. }
  4063. // print type counts
  4064. for (auto & kv : n_type) {
  4065. if (kv.second == 0) {
  4066. continue;
  4067. }
  4068. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  4069. }
  4070. }
  4071. if (!llama_mmap::SUPPORTED) {
  4072. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  4073. use_mmap = false;
  4074. }
  4075. this->use_mmap = use_mmap;
  4076. this->check_tensors = check_tensors;
  4077. }
  4078. ~llama_model_loader() {
  4079. if (meta) {
  4080. gguf_free(meta);
  4081. }
  4082. for (auto * ctx : contexts) {
  4083. ggml_free(ctx);
  4084. }
  4085. }
  4086. template<typename T>
  4087. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4088. get_arr_n(const std::string & key, T & result, const bool required = true) {
  4089. const int kid = gguf_find_key(meta, key.c_str());
  4090. if (kid < 0) {
  4091. if (required) {
  4092. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4093. }
  4094. return false;
  4095. }
  4096. struct GGUFMeta::ArrayInfo arr_info =
  4097. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4098. result = arr_info.length;
  4099. return true;
  4100. }
  4101. template<typename T>
  4102. typename std::enable_if<std::is_integral<T>::value, bool>::type
  4103. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  4104. return get_arr_n(llm_kv(kid), result, required);
  4105. }
  4106. template<typename T>
  4107. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  4108. const int kid = gguf_find_key(meta, key.c_str());
  4109. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4110. if (required) {
  4111. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4112. }
  4113. return false;
  4114. }
  4115. struct GGUFMeta::ArrayInfo arr_info =
  4116. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4117. switch (arr_info.gt) {
  4118. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4119. case GGUF_TYPE_INT32: GGML_ASSERT(
  4120. (std::is_same<T, int32_t>::value) ||
  4121. (std::is_same<T, uint32_t>::value)); break;
  4122. default:
  4123. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4124. }
  4125. result.resize(arr_info.length);
  4126. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  4127. return true;
  4128. }
  4129. template<typename T, size_t N_MAX>
  4130. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  4131. const int kid = gguf_find_key(meta, key.c_str());
  4132. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  4133. if (required) {
  4134. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  4135. }
  4136. return false;
  4137. }
  4138. struct GGUFMeta::ArrayInfo arr_info =
  4139. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4140. switch (arr_info.gt) {
  4141. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  4142. case GGUF_TYPE_INT32: GGML_ASSERT(
  4143. (std::is_same<T, int32_t>::value) ||
  4144. (std::is_same<T, uint32_t>::value)); break;
  4145. default:
  4146. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  4147. }
  4148. if (arr_info.length > N_MAX) {
  4149. 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));
  4150. }
  4151. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  4152. return true;
  4153. }
  4154. template<typename T>
  4155. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  4156. return get_arr(llm_kv(kid), result, required);
  4157. }
  4158. template<typename T>
  4159. bool get_key(const std::string & key, T & result, const bool required = true) {
  4160. auto it = kv_overrides.find(key);
  4161. const struct llama_model_kv_override * override =
  4162. it != kv_overrides.end() ? &it->second : nullptr;
  4163. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  4164. if (required && !found) {
  4165. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4166. }
  4167. return found;
  4168. }
  4169. template<typename T>
  4170. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4171. return get_key(llm_kv(kid), result, required);
  4172. }
  4173. // get array of n <= N_MAX elements, or a single element repeated n times
  4174. template<typename T, size_t N_MAX>
  4175. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4176. const int kid = gguf_find_key(meta, key.c_str());
  4177. if (kid < 0) {
  4178. if (required) {
  4179. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4180. }
  4181. return false;
  4182. }
  4183. if (n > N_MAX) {
  4184. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4185. }
  4186. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  4187. struct GGUFMeta::ArrayInfo arr_info =
  4188. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4189. if (n != arr_info.length) {
  4190. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4191. }
  4192. return get_arr(key, result, required);
  4193. } else {
  4194. T value;
  4195. bool ok = get_key(key, value, required);
  4196. if (!ok) {
  4197. return false;
  4198. }
  4199. for (uint32_t i = 0; i < n; i++) {
  4200. result[i] = value;
  4201. }
  4202. return true;
  4203. }
  4204. }
  4205. template<typename T>
  4206. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4207. return get_key_or_arr(llm_kv(kid), result, n, required);
  4208. }
  4209. std::string get_arch_name() const {
  4210. return arch_name;
  4211. }
  4212. enum llm_arch get_arch() const {
  4213. return llm_kv.arch;
  4214. }
  4215. const char * get_tensor_name(int i) const {
  4216. return weights.at(i).tensor->name;
  4217. }
  4218. const llama_tensor_weight * get_weight(const char * name) const {
  4219. for (const auto & weight : weights) {
  4220. if (strcmp(name, weight.tensor->name) == 0) {
  4221. return &weight;
  4222. }
  4223. }
  4224. return nullptr;
  4225. }
  4226. const llama_tensor_weight * get_weight(int i) const {
  4227. return get_weight(get_tensor_name(i));
  4228. }
  4229. const llama_tensor_weight & require_weight(const char * name) const {
  4230. const llama_tensor_weight * weight = get_weight(name);
  4231. if (!weight) {
  4232. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4233. }
  4234. return *weight;
  4235. }
  4236. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4237. const auto * weight = get_weight(name);
  4238. if (!weight) {
  4239. return nullptr;
  4240. }
  4241. return weight->tensor;
  4242. }
  4243. struct ggml_tensor * require_tensor_meta(const char * name) const {
  4244. struct ggml_tensor * tensor = get_tensor_meta(name);
  4245. if (!tensor) {
  4246. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4247. }
  4248. return tensor;
  4249. }
  4250. struct ggml_tensor * get_tensor_meta(int i) const {
  4251. return get_tensor_meta(get_tensor_name(i));
  4252. }
  4253. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  4254. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4255. ggml_set_name(tensor, ggml_get_name(cur));
  4256. if (duplicated) {
  4257. size_data += ggml_nbytes(cur);
  4258. } else {
  4259. n_created++;
  4260. }
  4261. return tensor;
  4262. }
  4263. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4264. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4265. if (cur == NULL) {
  4266. if (!required) {
  4267. return NULL;
  4268. }
  4269. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4270. }
  4271. {
  4272. bool is_ok = true;
  4273. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4274. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4275. is_ok = false;
  4276. break;
  4277. }
  4278. }
  4279. if (!is_ok) {
  4280. throw std::runtime_error(
  4281. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4282. __func__, name.c_str(),
  4283. llama_format_tensor_shape(ne).c_str(),
  4284. llama_format_tensor_shape(cur).c_str()));
  4285. }
  4286. }
  4287. return cur;
  4288. }
  4289. static const int TENSOR_NOT_REQUIRED = 1;
  4290. static const int TENSOR_DUPLICATED = 2;
  4291. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::initializer_list<int64_t> & ne, int flags = 0) {
  4292. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4293. if (cur == NULL) {
  4294. return NULL;
  4295. }
  4296. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  4297. }
  4298. struct ggml_tensor * create_tensor_as_view(struct ggml_context * ctx, struct ggml_tensor * base, const std::string & name, const std::initializer_list<int64_t> & ne, size_t offset, bool required = true) {
  4299. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4300. if (cur == NULL) {
  4301. return NULL;
  4302. }
  4303. if (cur->type != base->type) {
  4304. 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)));
  4305. }
  4306. std::array<int64_t, GGML_MAX_DIMS> dims;
  4307. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4308. dims[i] = i < ne.size() ? ne.begin()[i] : 1;
  4309. }
  4310. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4311. dims[0], dims[1], dims[2], dims[3],
  4312. cur->nb[1], cur->nb[2], cur->nb[3],
  4313. offset);
  4314. ggml_set_name(tensor, name.c_str());
  4315. n_created++;
  4316. return tensor;
  4317. }
  4318. void done_getting_tensors() const {
  4319. if (n_created != n_tensors) {
  4320. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4321. }
  4322. }
  4323. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4324. if (use_mmap) {
  4325. mappings.reserve(files.size());
  4326. mmaps_used.reserve(files.size());
  4327. for (const auto & file : files) {
  4328. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  4329. mmaps_used.emplace_back(mapping->size, 0);
  4330. if (mlock_mmaps) {
  4331. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4332. mlock_mmap->init(mapping->addr);
  4333. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4334. }
  4335. mappings.emplace_back(std::move(mapping));
  4336. }
  4337. }
  4338. // compute the total size of all tensors for progress reporting
  4339. for (auto & w : weights) {
  4340. size_data += ggml_nbytes(w.tensor);
  4341. }
  4342. }
  4343. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4344. GGML_ASSERT(!mappings.empty());
  4345. const auto & mapping = mappings.at(idx);
  4346. *first = mapping->size;
  4347. *last = 0;
  4348. *addr = mapping->addr;
  4349. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4350. try {
  4351. const auto * weight = get_weight(ggml_get_name(tensor));
  4352. if (!weight) {
  4353. continue;
  4354. }
  4355. if (weight->idx != idx) {
  4356. continue;
  4357. }
  4358. *first = std::min(*first, weight->offs);
  4359. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4360. } catch(...) {
  4361. // the tensor is not in the model
  4362. }
  4363. }
  4364. }
  4365. // for backwards compatibility, does not support ggml-backend
  4366. void load_data_for(struct ggml_tensor * cur) const {
  4367. const auto & w = require_weight(ggml_get_name(cur));
  4368. if (use_mmap) {
  4369. const auto & mapping = mappings.at(w.idx);
  4370. if (cur->data == nullptr) {
  4371. cur->data = (uint8_t *)mapping->addr + w.offs;
  4372. } else {
  4373. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4374. }
  4375. } else {
  4376. GGML_ASSERT(cur->data != nullptr);
  4377. GGML_ASSERT(w.idx < files.size());
  4378. const auto & file = files.at(w.idx);
  4379. file->seek(w.offs, SEEK_SET);
  4380. file->read_raw(cur->data, ggml_nbytes(cur));
  4381. }
  4382. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4383. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4384. }
  4385. }
  4386. size_t size_done = 0;
  4387. size_t size_data = 0;
  4388. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4389. // Returns false if cancelled by progress_callback
  4390. bool load_all_data(
  4391. struct ggml_context * ctx,
  4392. llama_buf_map & bufs,
  4393. llama_mlocks * lmlocks,
  4394. llama_progress_callback progress_callback,
  4395. void * progress_callback_user_data) {
  4396. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4397. std::vector<no_init<uint8_t>> read_buf;
  4398. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4399. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4400. // NVMe raid configurations might require more / larger buffers.
  4401. constexpr size_t n_buffers = 4;
  4402. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4403. std::vector<ggml_backend_buffer_t> host_buffers;
  4404. std::vector<ggml_backend_event_t> events;
  4405. std::vector<void *> host_ptrs;
  4406. size_t buffer_idx = 0; // buffer to use for async loads
  4407. ggml_backend_t upload_backend = [&](const char * fn) -> ggml_backend_t {
  4408. if (use_mmap || check_tensors) {
  4409. return nullptr;
  4410. }
  4411. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4412. // First determine if the backend supports the necessary features for async uploads.
  4413. auto * buf = bufs.count(0) ? bufs.at(0) : nullptr;
  4414. if (!buf) {
  4415. LLAMA_LOG_DEBUG("%s: no buffer found for async uploads\n", fn);
  4416. return nullptr;
  4417. }
  4418. auto * buft = ggml_backend_buffer_get_type(buf);
  4419. auto * dev = ggml_backend_buft_get_device(buft);
  4420. if (!dev) {
  4421. LLAMA_LOG_DEBUG("%s: no device found for buffer type %s for async uploads\n", fn,
  4422. ggml_backend_buft_name(buft));
  4423. return nullptr;
  4424. }
  4425. if (buft != ggml_backend_dev_buffer_type(dev)) {
  4426. LLAMA_LOG_DEBUG("%s: buffer type %s is not the default buffer type for device %s for async uploads\n", fn,
  4427. ggml_backend_buft_name(buft), ggml_backend_dev_name(dev));
  4428. return nullptr;
  4429. }
  4430. ggml_backend_dev_props props;
  4431. ggml_backend_dev_get_props(dev, &props);
  4432. if (!props.caps.async || !props.caps.host_buffer || !props.caps.events) {
  4433. LLAMA_LOG_DEBUG("%s: device %s does not support async, host buffers or events\n", fn,
  4434. ggml_backend_dev_name(dev));
  4435. return nullptr;
  4436. }
  4437. auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
  4438. if (!host_buft) {
  4439. LLAMA_LOG_DEBUG("%s: no host buffer type found for device %s\n", fn,
  4440. ggml_backend_dev_name(dev));
  4441. return nullptr;
  4442. }
  4443. // If the backend is supported, create pinned memory buffers and events for synchronisation.
  4444. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4445. auto * buf = ggml_backend_buft_alloc_buffer(host_buft, buffer_size);
  4446. if (!buf) {
  4447. LLAMA_LOG_DEBUG("%s: failed to allocate host buffer for async uploads for device %s\n", fn,
  4448. ggml_backend_dev_name(dev));
  4449. return nullptr;
  4450. }
  4451. host_buffers.emplace_back(buf);
  4452. host_ptrs.emplace_back(ggml_backend_buffer_get_base(buf));
  4453. auto * event = ggml_backend_event_new(dev);
  4454. if (!event) {
  4455. LLAMA_LOG_DEBUG("%s: failed to create event for async uploads for device %s\n", fn,
  4456. ggml_backend_dev_name(dev));
  4457. return nullptr;
  4458. }
  4459. events.emplace_back(event);
  4460. }
  4461. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  4462. if (!backend) {
  4463. LLAMA_LOG_DEBUG("%s: failed to initialize backend for device %s for async uploads\n", fn,
  4464. ggml_backend_dev_name(dev));
  4465. return nullptr;
  4466. }
  4467. return backend;
  4468. }(__func__);
  4469. if (upload_backend) {
  4470. LLAMA_LOG_DEBUG("%s: using async uploads for device %s, buffer type %s, backend %s\n", __func__,
  4471. ggml_backend_dev_name(ggml_backend_get_device(upload_backend)),
  4472. ggml_backend_buft_name(ggml_backend_buffer_get_type(bufs.at(0))),
  4473. ggml_backend_name(upload_backend));
  4474. }
  4475. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4476. const auto * weight = get_weight(ggml_get_name(cur));
  4477. if (weight == nullptr) {
  4478. // this can happen with split experts models
  4479. continue;
  4480. }
  4481. if (progress_callback) {
  4482. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4483. return false;
  4484. }
  4485. }
  4486. size_t n_size = ggml_nbytes(cur);
  4487. if (use_mmap) {
  4488. const auto & mapping = mappings.at(weight->idx);
  4489. ggml_backend_buffer_t buf_mmap = nullptr;
  4490. if (bufs.count(weight->idx)) {
  4491. buf_mmap = bufs.at(weight->idx);
  4492. }
  4493. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4494. if (check_tensors) {
  4495. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4496. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4497. }));
  4498. }
  4499. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4500. if (buf_mmap && cur->data == nullptr) {
  4501. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4502. if (lmlocks) {
  4503. const auto & lmlock = lmlocks->at(weight->idx);
  4504. lmlock->grow_to(weight->offs + n_size);
  4505. }
  4506. auto & mmap_used = mmaps_used[weight->idx];
  4507. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4508. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4509. } else {
  4510. ggml_backend_tensor_set(cur, data, 0, n_size);
  4511. }
  4512. } else {
  4513. GGML_ASSERT(weight->idx < files.size());
  4514. const auto & file = files.at(weight->idx);
  4515. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4516. file->seek(weight->offs, SEEK_SET);
  4517. file->read_raw(cur->data, n_size);
  4518. if (check_tensors) {
  4519. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4520. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4521. }));
  4522. }
  4523. } else {
  4524. // If upload_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4525. if (upload_backend) {
  4526. file->seek(weight->offs, SEEK_SET);
  4527. size_t bytes_read = 0;
  4528. while (bytes_read < n_size) {
  4529. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4530. ggml_backend_event_synchronize(events[buffer_idx]);
  4531. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4532. ggml_backend_tensor_set_async(upload_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4533. ggml_backend_event_record(events[buffer_idx], upload_backend);
  4534. bytes_read += read_iteration;
  4535. ++buffer_idx;
  4536. buffer_idx %= n_buffers;
  4537. }
  4538. } else {
  4539. read_buf.resize(n_size);
  4540. file->seek(weight->offs, SEEK_SET);
  4541. file->read_raw(read_buf.data(), n_size);
  4542. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4543. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4544. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4545. }
  4546. }
  4547. }
  4548. }
  4549. size_done += n_size;
  4550. }
  4551. // free temporary resources used for async uploads
  4552. for (auto * event : events) {
  4553. ggml_backend_event_synchronize(event);
  4554. ggml_backend_event_free(event);
  4555. }
  4556. for (auto * buf : host_buffers) {
  4557. ggml_backend_buffer_free(buf);
  4558. }
  4559. ggml_backend_free(upload_backend);
  4560. // check validation results
  4561. bool validation_failed = false;
  4562. for (auto & future : validation_result) {
  4563. auto result = future.get();
  4564. if (!result.second) {
  4565. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4566. validation_failed = true;
  4567. }
  4568. }
  4569. if (validation_failed) {
  4570. throw std::runtime_error("found tensors with invalid data");
  4571. }
  4572. // check if this is the last call and do final cleanup
  4573. if (size_done >= size_data) {
  4574. // unmap offloaded tensors and metadata
  4575. if (use_mmap) {
  4576. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4577. const auto & mmap_used = mmaps_used.at(idx);
  4578. auto & mapping = mappings.at(idx);
  4579. mapping->unmap_fragment(0, mmap_used.first);
  4580. if (mmap_used.second != 0) {
  4581. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4582. }
  4583. }
  4584. }
  4585. if (progress_callback) {
  4586. // Even though the model is done loading, we still honor
  4587. // cancellation since we need to free allocations.
  4588. return progress_callback(1.0f, progress_callback_user_data);
  4589. }
  4590. }
  4591. return true;
  4592. }
  4593. };
  4594. template<>
  4595. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4596. uint32_t tmp;
  4597. const bool found = get_key(kid, tmp, required);
  4598. if (found) {
  4599. result = (enum llama_pooling_type) tmp;
  4600. } else {
  4601. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4602. }
  4603. return found;
  4604. }
  4605. //
  4606. // load LLaMA models
  4607. //
  4608. static const char * llama_model_arch_name(llm_arch arch) {
  4609. auto it = LLM_ARCH_NAMES.find(arch);
  4610. if (it == LLM_ARCH_NAMES.end()) {
  4611. return "unknown";
  4612. }
  4613. return it->second;
  4614. }
  4615. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4616. if (ftype & LLAMA_FTYPE_GUESSED) {
  4617. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4618. }
  4619. switch (ftype) {
  4620. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4621. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4622. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4623. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4624. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4625. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4626. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4627. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4628. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4629. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4630. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4631. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4632. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4633. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4634. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4635. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4636. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4637. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4638. case LLAMA_FTYPE_MOSTLY_TQ1_0: return "TQ1_0 - 1.69 bpw ternary";
  4639. case LLAMA_FTYPE_MOSTLY_TQ2_0: return "TQ2_0 - 2.06 bpw ternary";
  4640. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4641. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4642. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4643. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4644. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4645. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4646. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4647. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4648. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4649. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4650. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4651. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4652. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  4653. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  4654. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  4655. default: return "unknown, may not work";
  4656. }
  4657. }
  4658. static const char * llama_model_type_name(e_model type) {
  4659. switch (type) {
  4660. case MODEL_14M: return "14M";
  4661. case MODEL_17M: return "17M";
  4662. case MODEL_22M: return "22M";
  4663. case MODEL_33M: return "33M";
  4664. case MODEL_60M: return "60M";
  4665. case MODEL_70M: return "70M";
  4666. case MODEL_80M: return "80M";
  4667. case MODEL_109M: return "109M";
  4668. case MODEL_137M: return "137M";
  4669. case MODEL_160M: return "160M";
  4670. case MODEL_220M: return "220M";
  4671. case MODEL_250M: return "250M";
  4672. case MODEL_270M: return "270M";
  4673. case MODEL_335M: return "335M";
  4674. case MODEL_410M: return "410M";
  4675. case MODEL_450M: return "450M";
  4676. case MODEL_770M: return "770M";
  4677. case MODEL_780M: return "780M";
  4678. case MODEL_0_5B: return "0.5B";
  4679. case MODEL_1B: return "1B";
  4680. case MODEL_1_3B: return "1.3B";
  4681. case MODEL_1_4B: return "1.4B";
  4682. case MODEL_1_6B: return "1.6B";
  4683. case MODEL_2B: return "2B";
  4684. case MODEL_2_8B: return "2.8B";
  4685. case MODEL_3B: return "3B";
  4686. case MODEL_4B: return "4B";
  4687. case MODEL_6B: return "6B";
  4688. case MODEL_6_9B: return "6.9B";
  4689. case MODEL_7B: return "7B";
  4690. case MODEL_8B: return "8B";
  4691. case MODEL_9B: return "9B";
  4692. case MODEL_11B: return "11B";
  4693. case MODEL_12B: return "12B";
  4694. case MODEL_13B: return "13B";
  4695. case MODEL_14B: return "14B";
  4696. case MODEL_15B: return "15B";
  4697. case MODEL_16B: return "16B";
  4698. case MODEL_20B: return "20B";
  4699. case MODEL_30B: return "30B";
  4700. case MODEL_34B: return "34B";
  4701. case MODEL_35B: return "35B";
  4702. case MODEL_40B: return "40B";
  4703. case MODEL_65B: return "65B";
  4704. case MODEL_70B: return "70B";
  4705. case MODEL_236B: return "236B";
  4706. case MODEL_314B: return "314B";
  4707. case MODEL_SMALL: return "0.1B";
  4708. case MODEL_MEDIUM: return "0.4B";
  4709. case MODEL_LARGE: return "0.8B";
  4710. case MODEL_XL: return "1.5B";
  4711. case MODEL_A1_7B: return "A1.7B";
  4712. case MODEL_A2_7B: return "A2.7B";
  4713. case MODEL_8x7B: return "8x7B";
  4714. case MODEL_8x22B: return "8x22B";
  4715. case MODEL_16x12B: return "16x12B";
  4716. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4717. case MODEL_57B_A14B: return "57B.A14B";
  4718. case MODEL_27B: return "27B";
  4719. default: return "?B";
  4720. }
  4721. }
  4722. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4723. switch (type) {
  4724. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4725. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4726. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4727. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4728. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4729. case LLAMA_VOCAB_TYPE_RWKV: return "RWKV";
  4730. default: return "unknown";
  4731. }
  4732. }
  4733. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4734. model.arch = ml.get_arch();
  4735. if (model.arch == LLM_ARCH_UNKNOWN) {
  4736. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4737. }
  4738. }
  4739. static void llm_load_hparams(
  4740. llama_model_loader & ml,
  4741. llama_model & model) {
  4742. auto & hparams = model.hparams;
  4743. const gguf_context * ctx = ml.meta;
  4744. // get metadata as string
  4745. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4746. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4747. if (type == GGUF_TYPE_ARRAY) {
  4748. continue;
  4749. }
  4750. const char * name = gguf_get_key(ctx, i);
  4751. const std::string value = gguf_kv_to_str(ctx, i);
  4752. model.gguf_kv.emplace(name, value);
  4753. }
  4754. // get general kv
  4755. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4756. // get hparams kv
  4757. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4758. // everything past this point is not vocab-related
  4759. if (hparams.vocab_only) {
  4760. return;
  4761. }
  4762. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4763. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4764. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4765. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4766. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4767. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4768. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4769. if (hparams.n_expert > 0) {
  4770. GGML_ASSERT(hparams.n_expert_used > 0);
  4771. } else {
  4772. GGML_ASSERT(hparams.n_expert_used == 0);
  4773. }
  4774. // zero-out the per-layer hparams
  4775. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4776. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4777. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4778. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4779. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4780. // n_head_kv is optional, default to n_head
  4781. hparams.n_head_kv_arr = hparams.n_head_arr;
  4782. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4783. bool rope_finetuned = false;
  4784. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4785. hparams.rope_finetuned = rope_finetuned;
  4786. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4787. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4788. // rope_freq_base (optional)
  4789. hparams.rope_freq_base_train = 10000.0f;
  4790. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4791. std::string rope_scaling("linear");
  4792. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4793. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4794. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4795. // rope_freq_scale (inverse of the kv) is optional
  4796. float ropescale = 0.0f;
  4797. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4798. // try the old key name
  4799. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4800. }
  4801. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4802. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4803. // non-transformer models do not have attention heads
  4804. if (hparams.n_head() > 0) {
  4805. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4806. // gpt-j n_rot = rotary_dim
  4807. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4808. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4809. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  4810. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  4811. // sanity check for n_rot (optional)
  4812. hparams.n_rot = hparams.n_embd_head_k;
  4813. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  4814. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  4815. if (hparams.n_rot != hparams.n_embd_head_k) {
  4816. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  4817. }
  4818. }
  4819. } else {
  4820. hparams.n_rot = 0;
  4821. hparams.n_embd_head_k = 0;
  4822. hparams.n_embd_head_v = 0;
  4823. }
  4824. // arch-specific KVs
  4825. switch (model.arch) {
  4826. case LLM_ARCH_LLAMA:
  4827. {
  4828. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4829. if (hparams.n_expert == 8) {
  4830. switch (hparams.n_layer) {
  4831. case 32: model.type = e_model::MODEL_8x7B; break;
  4832. case 56: model.type = e_model::MODEL_8x22B; break;
  4833. default: model.type = e_model::MODEL_UNKNOWN;
  4834. }
  4835. } else {
  4836. switch (hparams.n_layer) {
  4837. case 16: model.type = e_model::MODEL_1B; break; // Llama 3.2 1B
  4838. case 22: model.type = e_model::MODEL_1B; break;
  4839. case 26: model.type = e_model::MODEL_3B; break;
  4840. case 28: model.type = e_model::MODEL_3B; break; // Llama 3.2 3B
  4841. // granite uses a vocab with len 49152
  4842. 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;
  4843. case 36: model.type = e_model::MODEL_8B; break; // granite
  4844. case 40: model.type = e_model::MODEL_13B; break;
  4845. case 48: model.type = e_model::MODEL_34B; break;
  4846. case 60: model.type = e_model::MODEL_30B; break;
  4847. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  4848. default: model.type = e_model::MODEL_UNKNOWN;
  4849. }
  4850. }
  4851. } break;
  4852. case LLM_ARCH_MINICPM:
  4853. {
  4854. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4855. switch (hparams.n_layer) {
  4856. case 40: model.type = e_model::MODEL_2B; break;
  4857. default: model.type = e_model::MODEL_UNKNOWN;
  4858. }
  4859. } break;
  4860. case LLM_ARCH_MINICPM3:
  4861. {
  4862. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4863. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  4864. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  4865. switch (hparams.n_layer) {
  4866. case 62: model.type = e_model::MODEL_4B; break;
  4867. default: model.type = e_model::MODEL_UNKNOWN;
  4868. }
  4869. } break;
  4870. case LLM_ARCH_GROK:
  4871. {
  4872. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4873. switch (hparams.n_layer) {
  4874. case 64: model.type = e_model::MODEL_314B; break;
  4875. default: model.type = e_model::MODEL_UNKNOWN;
  4876. }
  4877. } break;
  4878. case LLM_ARCH_FALCON:
  4879. {
  4880. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4881. switch (hparams.n_layer) {
  4882. case 32: model.type = e_model::MODEL_7B; break;
  4883. case 60: model.type = e_model::MODEL_40B; break;
  4884. default: model.type = e_model::MODEL_UNKNOWN;
  4885. }
  4886. } break;
  4887. case LLM_ARCH_BAICHUAN:
  4888. {
  4889. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4890. switch (hparams.n_layer) {
  4891. case 32: model.type = e_model::MODEL_7B; break;
  4892. case 40: model.type = e_model::MODEL_13B; break;
  4893. default: model.type = e_model::MODEL_UNKNOWN;
  4894. }
  4895. if (model.type == e_model::MODEL_13B) {
  4896. // TODO: become GGUF KV parameter
  4897. hparams.f_max_alibi_bias = 8.0f;
  4898. }
  4899. } break;
  4900. case LLM_ARCH_STARCODER:
  4901. {
  4902. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4903. switch (hparams.n_layer) {
  4904. case 24: model.type = e_model::MODEL_1B; break;
  4905. case 36: model.type = e_model::MODEL_3B; break;
  4906. case 42: model.type = e_model::MODEL_7B; break;
  4907. case 40: model.type = e_model::MODEL_15B; break;
  4908. default: model.type = e_model::MODEL_UNKNOWN;
  4909. }
  4910. } break;
  4911. case LLM_ARCH_REFACT:
  4912. {
  4913. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4914. switch (hparams.n_layer) {
  4915. case 32: model.type = e_model::MODEL_1B; break;
  4916. default: model.type = e_model::MODEL_UNKNOWN;
  4917. }
  4918. // TODO: become GGUF KV parameter
  4919. hparams.f_max_alibi_bias = 8.0f;
  4920. } break;
  4921. case LLM_ARCH_BERT:
  4922. {
  4923. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4924. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4925. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4926. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4927. switch (hparams.n_layer) {
  4928. case 3:
  4929. model.type = e_model::MODEL_17M; break; // bge-micro
  4930. case 6:
  4931. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  4932. case 12:
  4933. switch (hparams.n_embd) {
  4934. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  4935. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  4936. } break;
  4937. case 24:
  4938. model.type = e_model::MODEL_335M; break; // bge-large
  4939. }
  4940. } break;
  4941. case LLM_ARCH_JINA_BERT_V2:
  4942. {
  4943. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4944. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4945. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4946. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4947. hparams.f_max_alibi_bias = 8.0f;
  4948. switch (hparams.n_layer) {
  4949. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  4950. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  4951. }
  4952. } break;
  4953. case LLM_ARCH_NOMIC_BERT:
  4954. {
  4955. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4956. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4957. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4958. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4959. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  4960. model.type = e_model::MODEL_137M;
  4961. }
  4962. } break;
  4963. case LLM_ARCH_BLOOM:
  4964. {
  4965. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4966. switch (hparams.n_layer) {
  4967. case 24: model.type = e_model::MODEL_1B; break;
  4968. case 30:
  4969. switch (hparams.n_embd) {
  4970. case 2560: model.type = e_model::MODEL_3B; break;
  4971. case 4096: model.type = e_model::MODEL_7B; break;
  4972. } break;
  4973. }
  4974. // TODO: become GGUF KV parameter
  4975. hparams.f_max_alibi_bias = 8.0f;
  4976. } break;
  4977. case LLM_ARCH_MPT:
  4978. {
  4979. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4980. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4981. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4982. switch (hparams.n_layer) {
  4983. case 32: model.type = e_model::MODEL_7B; break;
  4984. case 48: model.type = e_model::MODEL_30B; break;
  4985. default: model.type = e_model::MODEL_UNKNOWN;
  4986. }
  4987. } break;
  4988. case LLM_ARCH_STABLELM:
  4989. {
  4990. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4991. switch (hparams.n_layer) {
  4992. case 24: model.type = e_model::MODEL_1B; break;
  4993. case 32: model.type = e_model::MODEL_3B; break;
  4994. case 40: model.type = e_model::MODEL_12B; break;
  4995. default: model.type = e_model::MODEL_UNKNOWN;
  4996. }
  4997. } break;
  4998. case LLM_ARCH_QWEN:
  4999. {
  5000. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5001. switch (hparams.n_layer) {
  5002. case 32: model.type = e_model::MODEL_7B; break;
  5003. case 40: model.type = e_model::MODEL_13B; break;
  5004. default: model.type = e_model::MODEL_UNKNOWN;
  5005. }
  5006. } break;
  5007. case LLM_ARCH_QWEN2:
  5008. {
  5009. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5010. switch (hparams.n_layer) {
  5011. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  5012. case 32: model.type = e_model::MODEL_7B; break;
  5013. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  5014. case 80: model.type = e_model::MODEL_70B; break;
  5015. default: model.type = e_model::MODEL_UNKNOWN;
  5016. }
  5017. } break;
  5018. case LLM_ARCH_QWEN2MOE:
  5019. {
  5020. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  5021. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  5022. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5023. switch (hparams.n_layer) {
  5024. case 24: model.type = e_model::MODEL_A2_7B; break;
  5025. case 28: model.type = e_model::MODEL_57B_A14B; break;
  5026. default: model.type = e_model::MODEL_UNKNOWN;
  5027. }
  5028. } break;
  5029. case LLM_ARCH_PHI2:
  5030. {
  5031. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5032. switch (hparams.n_layer) {
  5033. case 24: model.type = e_model::MODEL_1B; break;
  5034. case 32: model.type = e_model::MODEL_3B; break;
  5035. default: model.type = e_model::MODEL_UNKNOWN;
  5036. }
  5037. } break;
  5038. case LLM_ARCH_PHI3:
  5039. {
  5040. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5041. switch (hparams.n_layer) {
  5042. case 24: model.type = e_model::MODEL_1B; break;
  5043. case 32: model.type = e_model::MODEL_3B; break;
  5044. case 40: model.type = e_model::MODEL_14B; break;
  5045. default: model.type = e_model::MODEL_UNKNOWN;
  5046. }
  5047. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  5048. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  5049. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  5050. hparams.n_swa = 2047;
  5051. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  5052. // default value for Phi-3-mini-128k-instruct
  5053. hparams.n_swa = 262144;
  5054. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  5055. // default value for Phi-3-medium-128k-instruct
  5056. hparams.n_swa = 131072;
  5057. }
  5058. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5059. if (!found_swa && hparams.n_swa == 0) {
  5060. throw std::runtime_error("invalid value for sliding_window");
  5061. }
  5062. } break;
  5063. case LLM_ARCH_PLAMO:
  5064. {
  5065. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5066. switch (hparams.n_layer) {
  5067. case 40: model.type = e_model::MODEL_13B; break;
  5068. default: model.type = e_model::MODEL_UNKNOWN;
  5069. }
  5070. } break;
  5071. case LLM_ARCH_GPT2:
  5072. {
  5073. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5074. switch (hparams.n_layer) {
  5075. case 12: model.type = e_model::MODEL_SMALL; break;
  5076. case 24: model.type = e_model::MODEL_MEDIUM; break;
  5077. case 36: model.type = e_model::MODEL_LARGE; break;
  5078. case 48: model.type = e_model::MODEL_XL; break;
  5079. default: model.type = e_model::MODEL_UNKNOWN;
  5080. }
  5081. } break;
  5082. case LLM_ARCH_CODESHELL:
  5083. {
  5084. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5085. switch (hparams.n_layer) {
  5086. case 42: model.type = e_model::MODEL_7B; break;
  5087. default: model.type = e_model::MODEL_UNKNOWN;
  5088. }
  5089. } break;
  5090. case LLM_ARCH_ORION:
  5091. {
  5092. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5093. switch (hparams.n_layer) {
  5094. case 40: model.type = e_model::MODEL_14B; break;
  5095. default: model.type = e_model::MODEL_UNKNOWN;
  5096. }
  5097. } break;
  5098. case LLM_ARCH_INTERNLM2:
  5099. {
  5100. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5101. switch (hparams.n_layer) {
  5102. case 32: model.type = e_model::MODEL_7B; break;
  5103. case 48: model.type = e_model::MODEL_20B; break;
  5104. default: model.type = e_model::MODEL_UNKNOWN;
  5105. }
  5106. } break;
  5107. case LLM_ARCH_GEMMA:
  5108. {
  5109. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5110. switch (hparams.n_layer) {
  5111. case 18: model.type = e_model::MODEL_2B; break;
  5112. case 28: model.type = e_model::MODEL_7B; break;
  5113. default: model.type = e_model::MODEL_UNKNOWN;
  5114. }
  5115. } break;
  5116. case LLM_ARCH_GEMMA2:
  5117. {
  5118. hparams.n_swa = 4096; // default value of gemma 2
  5119. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  5120. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5121. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  5122. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  5123. hparams.attn_soft_cap = true;
  5124. switch (hparams.n_layer) {
  5125. case 26: model.type = e_model::MODEL_2B; break;
  5126. case 42: model.type = e_model::MODEL_9B; break;
  5127. case 46: model.type = e_model::MODEL_27B; break;
  5128. default: model.type = e_model::MODEL_UNKNOWN;
  5129. }
  5130. } break;
  5131. case LLM_ARCH_STARCODER2:
  5132. {
  5133. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5134. switch (hparams.n_layer) {
  5135. case 30: model.type = e_model::MODEL_3B; break;
  5136. case 32: model.type = e_model::MODEL_7B; break;
  5137. case 40: model.type = e_model::MODEL_15B; break;
  5138. case 52: model.type = e_model::MODEL_20B; break; // granite
  5139. case 88: model.type = e_model::MODEL_34B; break; // granite
  5140. default: model.type = e_model::MODEL_UNKNOWN;
  5141. }
  5142. } break;
  5143. case LLM_ARCH_MAMBA:
  5144. {
  5145. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  5146. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  5147. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  5148. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  5149. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  5150. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5151. switch (hparams.n_layer) {
  5152. case 24:
  5153. switch (hparams.n_embd) {
  5154. case 768: model.type = e_model::MODEL_SMALL; break;
  5155. default: model.type = e_model::MODEL_UNKNOWN;
  5156. } break;
  5157. case 48:
  5158. switch (hparams.n_embd) {
  5159. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  5160. case 1536: model.type = e_model::MODEL_LARGE; break;
  5161. case 2048: model.type = e_model::MODEL_XL; break;
  5162. default: model.type = e_model::MODEL_UNKNOWN;
  5163. } break;
  5164. case 64:
  5165. switch (hparams.n_embd) {
  5166. case 2560: model.type = e_model::MODEL_3B; break;
  5167. default: model.type = e_model::MODEL_UNKNOWN;
  5168. } break;
  5169. default: model.type = e_model::MODEL_UNKNOWN;
  5170. }
  5171. } break;
  5172. case LLM_ARCH_XVERSE:
  5173. {
  5174. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5175. switch (hparams.n_layer) {
  5176. case 32: model.type = e_model::MODEL_7B; break;
  5177. case 40: model.type = e_model::MODEL_13B; break;
  5178. case 80: model.type = e_model::MODEL_65B; break;
  5179. default: model.type = e_model::MODEL_UNKNOWN;
  5180. }
  5181. } break;
  5182. case LLM_ARCH_COMMAND_R:
  5183. {
  5184. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5185. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5186. switch (hparams.n_layer) {
  5187. case 40: model.type = e_model::MODEL_35B; break;
  5188. default: model.type = e_model::MODEL_UNKNOWN;
  5189. }
  5190. } break;
  5191. case LLM_ARCH_DBRX:
  5192. {
  5193. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5194. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  5195. switch (hparams.n_layer) {
  5196. case 40: model.type = e_model::MODEL_16x12B; break;
  5197. default: model.type = e_model::MODEL_UNKNOWN;
  5198. }
  5199. } break;
  5200. case LLM_ARCH_OLMO:
  5201. {
  5202. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5203. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  5204. switch (hparams.n_layer) {
  5205. case 22: model.type = e_model::MODEL_1B; break;
  5206. case 32: model.type = e_model::MODEL_7B; break;
  5207. case 80: model.type = e_model::MODEL_70B; break;
  5208. default: model.type = e_model::MODEL_UNKNOWN;
  5209. }
  5210. } break;
  5211. case LLM_ARCH_OLMOE:
  5212. {
  5213. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5214. switch (hparams.n_layer) {
  5215. case 16: model.type = e_model::MODEL_A1_7B; break;
  5216. default: model.type = e_model::MODEL_UNKNOWN;
  5217. }
  5218. } break;
  5219. case LLM_ARCH_OPENELM:
  5220. {
  5221. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5222. switch (hparams.n_layer) {
  5223. case 16: model.type = e_model::MODEL_270M; break;
  5224. case 20: model.type = e_model::MODEL_450M; break;
  5225. case 28: model.type = e_model::MODEL_1B; break;
  5226. case 36: model.type = e_model::MODEL_3B; break;
  5227. default: model.type = e_model::MODEL_UNKNOWN;
  5228. }
  5229. } break;
  5230. case LLM_ARCH_GPTNEOX:
  5231. {
  5232. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5233. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5234. switch (hparams.n_layer) {
  5235. case 6:
  5236. switch (hparams.n_ff()) {
  5237. case 512: model.type = e_model::MODEL_14M; break;
  5238. case 2048: model.type = e_model::MODEL_70M; break;
  5239. default: model.type = e_model::MODEL_UNKNOWN;
  5240. } break;
  5241. case 12:
  5242. switch (hparams.n_ff()) {
  5243. case 3072: model.type = e_model::MODEL_160M; break;
  5244. default: model.type = e_model::MODEL_UNKNOWN;
  5245. } break;
  5246. case 16:
  5247. switch (hparams.n_ff()) {
  5248. case 8192: model.type = e_model::MODEL_1B; break;
  5249. default: model.type = e_model::MODEL_UNKNOWN;
  5250. } break;
  5251. case 24:
  5252. switch (hparams.n_ff()) {
  5253. case 4096: model.type = e_model::MODEL_410M; break;
  5254. case 8192: model.type = e_model::MODEL_1_4B; break;
  5255. default: model.type = e_model::MODEL_UNKNOWN;
  5256. } break;
  5257. case 32:
  5258. switch (hparams.n_ff()) {
  5259. case 10240: model.type = e_model::MODEL_2_8B; break;
  5260. case 16384: model.type = e_model::MODEL_6_9B; break;
  5261. default: model.type = e_model::MODEL_UNKNOWN;
  5262. } break;
  5263. case 36:
  5264. switch (hparams.n_ff()) {
  5265. case 20480: model.type = e_model::MODEL_12B; break;
  5266. default: model.type = e_model::MODEL_UNKNOWN;
  5267. } break;
  5268. case 44:
  5269. switch (hparams.n_ff()) {
  5270. case 24576: model.type = e_model::MODEL_20B; break;
  5271. default: model.type = e_model::MODEL_UNKNOWN;
  5272. } break;
  5273. default: model.type = e_model::MODEL_UNKNOWN;
  5274. }
  5275. } break;
  5276. case LLM_ARCH_ARCTIC:
  5277. {
  5278. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5279. if (hparams.n_expert == 128) {
  5280. switch (hparams.n_layer) {
  5281. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5282. default: model.type = e_model::MODEL_UNKNOWN;
  5283. }
  5284. } else {
  5285. model.type = e_model::MODEL_UNKNOWN;
  5286. }
  5287. } break;
  5288. case LLM_ARCH_DEEPSEEK2:
  5289. {
  5290. bool is_lite = (hparams.n_layer == 27);
  5291. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5292. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5293. if (!is_lite) {
  5294. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5295. }
  5296. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5297. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5298. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5299. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5300. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5301. switch (hparams.n_layer) {
  5302. case 27: model.type = e_model::MODEL_16B; break;
  5303. case 60: model.type = e_model::MODEL_236B; break;
  5304. default: model.type = e_model::MODEL_UNKNOWN;
  5305. }
  5306. } break;
  5307. case LLM_ARCH_CHATGLM:
  5308. {
  5309. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5310. switch (hparams.n_layer) {
  5311. case 28: model.type = e_model::MODEL_6B; break;
  5312. case 40: model.type = e_model::MODEL_9B; break;
  5313. default: model.type = e_model::MODEL_UNKNOWN;
  5314. }
  5315. } break;
  5316. case LLM_ARCH_BITNET:
  5317. {
  5318. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5319. switch (hparams.n_layer) {
  5320. case 26: model.type = e_model::MODEL_3B; break;
  5321. default: model.type = e_model::MODEL_UNKNOWN;
  5322. }
  5323. } break;
  5324. case LLM_ARCH_T5:
  5325. {
  5326. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5327. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5328. uint32_t dec_start_token_id;
  5329. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5330. hparams.dec_start_token_id = dec_start_token_id;
  5331. }
  5332. switch (hparams.n_layer) {
  5333. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5334. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5335. case 12:
  5336. switch (hparams.n_ff()) {
  5337. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5338. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5339. default: model.type = e_model::MODEL_UNKNOWN;
  5340. } break;
  5341. case 24:
  5342. switch (hparams.n_ff()) {
  5343. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5344. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5345. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5346. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5347. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5348. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5349. default: model.type = e_model::MODEL_UNKNOWN;
  5350. } break;
  5351. default: model.type = e_model::MODEL_UNKNOWN;
  5352. }
  5353. } break;
  5354. case LLM_ARCH_T5ENCODER:
  5355. {
  5356. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5357. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5358. model.type = e_model::MODEL_UNKNOWN;
  5359. } break;
  5360. case LLM_ARCH_JAIS:
  5361. {
  5362. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5363. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5364. switch (hparams.n_layer) {
  5365. case 24: model.type = e_model::MODEL_1_3B; break;
  5366. case 40: model.type = e_model::MODEL_13B; break;
  5367. /* TODO: add variants */
  5368. default: model.type = e_model::MODEL_UNKNOWN;
  5369. }
  5370. } break;
  5371. case LLM_ARCH_NEMOTRON:
  5372. {
  5373. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5374. switch (hparams.n_layer) {
  5375. case 32: model.type = e_model::MODEL_4B; break;
  5376. default: model.type = e_model::MODEL_UNKNOWN;
  5377. }
  5378. } break;
  5379. case LLM_ARCH_EXAONE:
  5380. {
  5381. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5382. switch (hparams.n_layer) {
  5383. case 32: model.type = e_model::MODEL_8B; break;
  5384. default: model.type = e_model::MODEL_UNKNOWN;
  5385. }
  5386. } break;
  5387. case LLM_ARCH_RWKV6:
  5388. {
  5389. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5390. ml.get_key(LLM_KV_WKV_HEAD_SIZE, hparams.wkv_head_size);
  5391. ml.get_key(LLM_KV_TIME_MIX_EXTRA_DIM, hparams.time_mix_extra_dim);
  5392. ml.get_key(LLM_KV_TIME_DECAY_EXTRA_DIM, hparams.time_decay_extra_dim);
  5393. ml.get_key(LLM_KV_RESCALE_EVERY_N_LAYERS, hparams.rescale_every_n_layers, false);
  5394. switch (hparams.n_layer) {
  5395. case 24: model.type = e_model::MODEL_1_6B; break;
  5396. case 32:
  5397. switch (hparams.n_embd) {
  5398. case 2560: model.type = e_model::MODEL_3B; break;
  5399. case 4096: model.type = e_model::MODEL_7B; break;
  5400. default: model.type = e_model::MODEL_UNKNOWN;
  5401. } break;
  5402. case 61: model.type = e_model::MODEL_14B; break;
  5403. default: model.type = e_model::MODEL_UNKNOWN;
  5404. }
  5405. } break;
  5406. case LLM_ARCH_GRANITE:
  5407. case LLM_ARCH_GRANITE_MOE:
  5408. {
  5409. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5410. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  5411. ml.get_key(LLM_KV_RESIDUAL_SCALE, hparams.f_residual_scale);
  5412. ml.get_key(LLM_KV_EMBEDDING_SCALE, hparams.f_embedding_scale);
  5413. ml.get_key(LLM_KV_ATTENTION_SCALE, hparams.f_attention_scale);
  5414. switch (hparams.n_layer) {
  5415. case 32: model.type = e_model::MODEL_3B; break;
  5416. case 40: model.type = e_model::MODEL_3B; break;
  5417. // Add additional layer/vocab/etc checks here for other model sizes
  5418. default: model.type = e_model::MODEL_UNKNOWN;
  5419. }
  5420. } break;
  5421. case LLM_ARCH_CHAMELEON:
  5422. {
  5423. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5424. hparams.f_norm_eps = 1e-5; // eps for qk-norm, torch default
  5425. ml.get_key(LLM_KV_SWIN_NORM, hparams.swin_norm);
  5426. switch (hparams.n_layer) {
  5427. case 32: model.type = e_model::MODEL_7B; break;
  5428. case 48: model.type = e_model::MODEL_34B; break;
  5429. default: model.type = e_model::MODEL_UNKNOWN;
  5430. }
  5431. } break;
  5432. default: (void)0;
  5433. }
  5434. model.ftype = ml.ftype;
  5435. if (hparams.f_max_alibi_bias > 0.0f) {
  5436. hparams.use_alibi = true;
  5437. }
  5438. hparams.rope_type = llama_rope_type(&model);
  5439. }
  5440. static void llm_load_vocab(
  5441. llama_model_loader & ml,
  5442. llama_model & model) {
  5443. auto & vocab = model.vocab;
  5444. struct gguf_context * ctx = ml.meta;
  5445. const auto kv = LLM_KV(model.arch);
  5446. // determine vocab type
  5447. {
  5448. std::string tokenizer_model;
  5449. std::string tokenizer_pre;
  5450. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5451. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5452. if (tokenizer_model == "no_vocab") {
  5453. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5454. // default special tokens
  5455. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5456. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5457. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5458. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5459. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5460. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5461. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5462. vocab.linefeed_id = LLAMA_TOKEN_NULL;
  5463. // read vocab size from metadata
  5464. if (!ml.get_key(LLM_KV_VOCAB_SIZE, vocab.n_vocab, false)) {
  5465. vocab.n_vocab = 0;
  5466. LLAMA_LOG_WARN("%s: there is no vocab_size in metadata, vocab.n_vocab will be set to %u\n", __func__, vocab.n_vocab);
  5467. }
  5468. return;
  5469. }
  5470. if (tokenizer_model == "llama") {
  5471. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5472. // default special tokens
  5473. vocab.special_bos_id = 1;
  5474. vocab.special_eos_id = 2;
  5475. vocab.special_unk_id = 0;
  5476. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5477. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5478. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5479. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5480. } else if (tokenizer_model == "bert") {
  5481. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5482. // default special tokens
  5483. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5484. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5485. vocab.special_unk_id = 100;
  5486. vocab.special_sep_id = 102;
  5487. vocab.special_pad_id = 0;
  5488. vocab.special_cls_id = 101;
  5489. vocab.special_mask_id = 103;
  5490. } else if (tokenizer_model == "gpt2") {
  5491. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5492. // read bpe merges and populate bpe ranks
  5493. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5494. if (merges_keyidx == -1) {
  5495. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5496. }
  5497. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5498. for (int i = 0; i < n_merges; i++) {
  5499. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5500. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5501. std::string first;
  5502. std::string second;
  5503. const size_t pos = word.find(' ', 1);
  5504. if (pos != std::string::npos) {
  5505. first = word.substr(0, pos);
  5506. second = word.substr(pos + 1);
  5507. }
  5508. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5509. }
  5510. // default special tokens
  5511. vocab.special_bos_id = 11;
  5512. vocab.special_eos_id = 11;
  5513. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5514. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5515. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5516. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5517. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5518. } else if (tokenizer_model == "t5") {
  5519. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5520. // default special tokens
  5521. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5522. vocab.special_eos_id = 1;
  5523. vocab.special_unk_id = 2;
  5524. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5525. vocab.special_pad_id = 0;
  5526. vocab.special_cls_id = LLAMA_TOKEN_NULL;
  5527. vocab.special_mask_id = LLAMA_TOKEN_NULL;
  5528. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5529. if (precompiled_charsmap_keyidx != -1) {
  5530. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5531. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5532. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5533. #ifdef IS_BIG_ENDIAN
  5534. // correct endiannes of data in precompiled_charsmap binary blob
  5535. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5536. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5537. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5538. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5539. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5540. for (size_t i = 0; i < xcda_array_size; ++i) {
  5541. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5542. }
  5543. #endif
  5544. }
  5545. } else if (tokenizer_model == "rwkv") {
  5546. vocab.type = LLAMA_VOCAB_TYPE_RWKV;
  5547. // default special tokens
  5548. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5549. vocab.special_eos_id = LLAMA_TOKEN_NULL;
  5550. vocab.special_unk_id = LLAMA_TOKEN_NULL;
  5551. vocab.special_sep_id = LLAMA_TOKEN_NULL;
  5552. vocab.special_pad_id = LLAMA_TOKEN_NULL;
  5553. } else {
  5554. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5555. }
  5556. // for now, only BPE models have pre-tokenizers
  5557. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5558. vocab.tokenizer_add_space_prefix = false;
  5559. vocab.tokenizer_clean_spaces = true;
  5560. if (tokenizer_pre.empty()) {
  5561. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  5562. LLAMA_LOG_WARN("%s: \n", __func__);
  5563. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  5564. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  5565. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  5566. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  5567. LLAMA_LOG_WARN("%s: \n", __func__);
  5568. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5569. } else if (tokenizer_pre == "default") {
  5570. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5571. } else if (
  5572. tokenizer_pre == "llama3" ||
  5573. tokenizer_pre == "llama-v3" ||
  5574. tokenizer_pre == "llama-bpe") {
  5575. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5576. vocab.tokenizer_ignore_merges = true;
  5577. vocab.tokenizer_add_bos = true;
  5578. } else if (
  5579. tokenizer_pre == "deepseek-llm") {
  5580. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5581. vocab.tokenizer_clean_spaces = false;
  5582. } else if (
  5583. tokenizer_pre == "deepseek-coder") {
  5584. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5585. vocab.tokenizer_clean_spaces = false;
  5586. } else if (
  5587. tokenizer_pre == "falcon") {
  5588. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5589. } else if (
  5590. tokenizer_pre == "mpt") {
  5591. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5592. } else if (
  5593. tokenizer_pre == "starcoder") {
  5594. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5595. } else if (
  5596. tokenizer_pre == "gpt-2" ||
  5597. tokenizer_pre == "phi-2" ||
  5598. tokenizer_pre == "jina-es" ||
  5599. tokenizer_pre == "jina-de" ||
  5600. tokenizer_pre == "jina-v1-en" ||
  5601. tokenizer_pre == "jina-v2-es" ||
  5602. tokenizer_pre == "jina-v2-de" ||
  5603. tokenizer_pre == "jina-v2-code") {
  5604. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5605. } else if (
  5606. tokenizer_pre == "refact") {
  5607. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5608. } else if (
  5609. tokenizer_pre == "command-r") {
  5610. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5611. vocab.tokenizer_clean_spaces = false;
  5612. } else if (
  5613. tokenizer_pre == "qwen2") {
  5614. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5615. vocab.tokenizer_clean_spaces = false;
  5616. } else if (
  5617. tokenizer_pre == "stablelm2") {
  5618. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5619. } else if (
  5620. tokenizer_pre == "olmo") {
  5621. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5622. } else if (
  5623. tokenizer_pre == "dbrx") {
  5624. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5625. } else if (
  5626. tokenizer_pre == "smaug-bpe") {
  5627. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5628. } else if (
  5629. tokenizer_pre == "poro-chat") {
  5630. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5631. vocab.tokenizer_clean_spaces = false;
  5632. } else if (
  5633. tokenizer_pre == "chatglm-bpe") {
  5634. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5635. vocab.special_bos_id = LLAMA_TOKEN_NULL;
  5636. } else if (
  5637. tokenizer_pre == "viking") {
  5638. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5639. vocab.tokenizer_clean_spaces = false;
  5640. } else if (
  5641. tokenizer_pre == "jais") {
  5642. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5643. } else if (
  5644. tokenizer_pre == "tekken") {
  5645. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5646. vocab.tokenizer_clean_spaces = false;
  5647. vocab.tokenizer_ignore_merges = true;
  5648. vocab.tokenizer_add_bos = true;
  5649. } else if (
  5650. tokenizer_pre == "smollm") {
  5651. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5652. vocab.tokenizer_clean_spaces = false;
  5653. } else if (
  5654. tokenizer_pre == "codeshell") {
  5655. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5656. } else if (
  5657. tokenizer_pre == "bloom") {
  5658. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5659. } else if (
  5660. tokenizer_pre == "gpt3-finnish") {
  5661. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5662. } else if (
  5663. tokenizer_pre == "exaone") {
  5664. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5665. } else if (
  5666. tokenizer_pre == "chameleon") {
  5667. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHAMELEON;
  5668. vocab.tokenizer_add_bos = true;
  5669. vocab.tokenizer_clean_spaces = false;
  5670. } else {
  5671. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  5672. }
  5673. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5674. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5675. vocab.tokenizer_add_space_prefix = true;
  5676. vocab.tokenizer_clean_spaces = false;
  5677. vocab.tokenizer_add_bos = true;
  5678. vocab.tokenizer_add_eos = false;
  5679. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5680. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5681. vocab.tokenizer_add_space_prefix = false;
  5682. vocab.tokenizer_clean_spaces = true;
  5683. vocab.tokenizer_add_bos = true;
  5684. vocab.tokenizer_add_eos = false;
  5685. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  5686. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5687. vocab.tokenizer_add_bos = false;
  5688. vocab.tokenizer_add_eos = true;
  5689. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5690. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5691. vocab.tokenizer_add_space_prefix = false;
  5692. vocab.tokenizer_clean_spaces = false;
  5693. vocab.tokenizer_add_bos = false;
  5694. vocab.tokenizer_add_eos = false;
  5695. } else {
  5696. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5697. }
  5698. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  5699. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  5700. }
  5701. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  5702. if (token_idx == -1) {
  5703. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  5704. }
  5705. const float * scores = nullptr;
  5706. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  5707. if (score_idx != -1) {
  5708. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  5709. }
  5710. const int * toktypes = nullptr;
  5711. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  5712. if (toktype_idx != -1) {
  5713. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  5714. }
  5715. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  5716. vocab.n_vocab = n_vocab;
  5717. vocab.id_to_token.resize(n_vocab);
  5718. for (uint32_t i = 0; i < n_vocab; i++) {
  5719. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  5720. //GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5721. if (word.empty()) {
  5722. LLAMA_LOG_WARN("%s: empty token at index %u\n", __func__, i);
  5723. word = "[EMPTY_" + std::to_string(i) + "]";
  5724. }
  5725. vocab.token_to_id[word] = i;
  5726. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  5727. auto & token_data = vocab.id_to_token[i];
  5728. token_data.text = std::move(word);
  5729. token_data.score = scores ? scores[i] : 0.0f;
  5730. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  5731. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  5732. switch(toktypes[i]) {
  5733. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  5734. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  5735. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  5736. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  5737. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  5738. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  5739. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5740. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5741. }
  5742. }
  5743. }
  5744. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  5745. vocab.init_tokenizer();
  5746. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  5747. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5748. try {
  5749. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  5750. } catch (const std::exception & e) {
  5751. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  5752. vocab.linefeed_id = vocab.special_pad_id;
  5753. }
  5754. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5755. vocab.linefeed_id = vocab.special_pad_id;
  5756. } else if (vocab.type == LLAMA_VOCAB_TYPE_RWKV) {
  5757. const std::vector<int> ids = llama_tokenize_internal(vocab, "\n", false);
  5758. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  5759. vocab.linefeed_id = ids[0];
  5760. } else {
  5761. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  5762. //GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  5763. if (ids.empty()) {
  5764. LLAMA_LOG_WARN("%s: model vocab missing newline token, using special_pad_id instead\n", __func__);
  5765. vocab.linefeed_id = vocab.special_pad_id;
  5766. } else {
  5767. vocab.linefeed_id = ids[0];
  5768. }
  5769. }
  5770. // special tokens
  5771. {
  5772. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  5773. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  5774. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  5775. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  5776. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  5777. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  5778. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  5779. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  5780. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  5781. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  5782. { LLM_KV_TOKENIZER_FIM_PRE_ID, vocab.special_fim_pre_id },
  5783. { LLM_KV_TOKENIZER_FIM_SUF_ID, vocab.special_fim_suf_id },
  5784. { LLM_KV_TOKENIZER_FIM_MID_ID, vocab.special_fim_mid_id },
  5785. { LLM_KV_TOKENIZER_FIM_PAD_ID, vocab.special_fim_pad_id },
  5786. { LLM_KV_TOKENIZER_FIM_REP_ID, vocab.special_fim_rep_id },
  5787. { LLM_KV_TOKENIZER_FIM_SEP_ID, vocab.special_fim_sep_id },
  5788. // deprecated
  5789. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_fim_pre_id },
  5790. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_fim_suf_id },
  5791. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_fim_mid_id },
  5792. };
  5793. for (const auto & it : special_token_types) {
  5794. const std::string & key = kv(std::get<0>(it));
  5795. int32_t & id = std::get<1>(it);
  5796. uint32_t new_id;
  5797. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  5798. continue;
  5799. }
  5800. if (new_id >= vocab.id_to_token.size()) {
  5801. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  5802. __func__, key.c_str(), new_id, id);
  5803. } else {
  5804. id = new_id;
  5805. }
  5806. }
  5807. // Handle add_bos_token and add_eos_token
  5808. {
  5809. bool temp = true;
  5810. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  5811. vocab.tokenizer_add_bos = temp;
  5812. }
  5813. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  5814. vocab.tokenizer_add_eos = temp;
  5815. }
  5816. }
  5817. // auto-detect special tokens by text
  5818. // TODO: convert scripts should provide these tokens through the KV metadata LLM_KV_TOKENIZER_...
  5819. // for now, we apply this workaround to find the tokens based on their text
  5820. for (const auto & t : vocab.token_to_id) {
  5821. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  5822. if (vocab.special_eot_id == LLAMA_TOKEN_NULL) {
  5823. if (false
  5824. || t.first == "<|eot_id|>"
  5825. || t.first == "<|im_end|>"
  5826. || t.first == "<|end|>"
  5827. || t.first == "<end_of_turn>"
  5828. || t.first == "<|endoftext|>"
  5829. || t.first == "<EOT>"
  5830. || t.first == "<|end▁of▁sentence|>" // DeepSeek
  5831. ) {
  5832. vocab.special_eot_id = t.second;
  5833. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5834. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5835. __func__, t.second, t.first.c_str());
  5836. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5837. }
  5838. }
  5839. }
  5840. // find EOM token: "<|eom_id|>"
  5841. if (vocab.special_eom_id == LLAMA_TOKEN_NULL) {
  5842. if (false
  5843. || t.first == "<|eom_id|>"
  5844. ) {
  5845. vocab.special_eom_id = t.second;
  5846. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5847. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5848. __func__, t.second, t.first.c_str());
  5849. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5850. }
  5851. }
  5852. }
  5853. // find FIM_PRE token: "<|fim_prefix|>", "<fim-prefix>", "<PRE>", etc.
  5854. if (vocab.special_fim_pre_id == LLAMA_TOKEN_NULL) {
  5855. if (false
  5856. || t.first == "<|fim_prefix|>" // Qwen
  5857. || t.first == "<fim-prefix>"
  5858. || t.first == "<|fim▁begin|>" // DeepSeek
  5859. || t.first == "<PRE>"
  5860. ) {
  5861. vocab.special_fim_pre_id = t.second;
  5862. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5863. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5864. __func__, t.second, t.first.c_str());
  5865. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5866. }
  5867. }
  5868. }
  5869. // find FIM_SUF token: "<|fim_suffix|>", "<fim-suffix>", "<SUF>", etc.
  5870. if (vocab.special_fim_suf_id == LLAMA_TOKEN_NULL) {
  5871. if (false
  5872. || t.first == "<|fim_suffix|>" // Qwen
  5873. || t.first == "<fim-suffix>"
  5874. || t.first == "<|fim▁hole|>" // DeepSeek
  5875. || t.first == "<SUF>"
  5876. ) {
  5877. vocab.special_fim_suf_id = t.second;
  5878. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5879. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5880. __func__, t.second, t.first.c_str());
  5881. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5882. }
  5883. }
  5884. }
  5885. // find FIM_MID token: "<|fim_middle|>", "<fim-middle>", "<MID>", etc.
  5886. if (vocab.special_fim_mid_id == LLAMA_TOKEN_NULL) {
  5887. if (false
  5888. || t.first == "<|fim_middle|>" // Qwen
  5889. || t.first == "<fim-middle>"
  5890. || t.first == "<|fim▁end|>" // DeepSeek
  5891. || t.first == "<MID>"
  5892. ) {
  5893. vocab.special_fim_mid_id = t.second;
  5894. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5895. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5896. __func__, t.second, t.first.c_str());
  5897. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5898. }
  5899. }
  5900. }
  5901. // find FIM_PAD token: "<|fim_pad|>", "<fim-pad>", "<PAD>", etc.
  5902. if (vocab.special_fim_pad_id == LLAMA_TOKEN_NULL) {
  5903. if (false
  5904. || t.first == "<|fim_pad|>" // Qwen
  5905. || t.first == "<fim-pad>"
  5906. || t.first == "<PAD>"
  5907. ) {
  5908. vocab.special_fim_pad_id = t.second;
  5909. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5910. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5911. __func__, t.second, t.first.c_str());
  5912. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5913. }
  5914. }
  5915. }
  5916. // find FIM_REP token: "<|fim_repo|>", "<fim-repo>", "<REP>", etc.
  5917. if (vocab.special_fim_rep_id == LLAMA_TOKEN_NULL) {
  5918. if (false
  5919. || t.first == "<|fim_repo|>" // Qwen
  5920. || t.first == "<|repo_name|>"
  5921. || t.first == "<fim-repo>"
  5922. || t.first == "<REPO>"
  5923. ) {
  5924. vocab.special_fim_rep_id = t.second;
  5925. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5926. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5927. __func__, t.second, t.first.c_str());
  5928. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5929. }
  5930. }
  5931. }
  5932. // find FIM_SEP token: "<|file_sep|>"
  5933. if (vocab.special_fim_sep_id == LLAMA_TOKEN_NULL) {
  5934. if (false
  5935. || t.first == "<|file_sep|>" // Qwen
  5936. ) {
  5937. vocab.special_fim_sep_id = t.second;
  5938. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5939. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5940. __func__, t.second, t.first.c_str());
  5941. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5942. }
  5943. }
  5944. }
  5945. }
  5946. // maintain a list of tokens that cause end-of-generation
  5947. // this is currently determined based on the token text, which is obviously not ideal
  5948. // ref: https://github.com/ggerganov/llama.cpp/issues/9606
  5949. vocab.special_eog_ids.clear();
  5950. if (vocab.special_fim_pad_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_pad_id) == 0) {
  5951. vocab.special_eog_ids.insert(vocab.special_fim_pad_id);
  5952. }
  5953. if (vocab.special_fim_rep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_rep_id) == 0) {
  5954. vocab.special_eog_ids.insert(vocab.special_fim_rep_id);
  5955. }
  5956. if (vocab.special_fim_sep_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_fim_sep_id) == 0) {
  5957. vocab.special_eog_ids.insert(vocab.special_fim_sep_id);
  5958. }
  5959. for (const auto & t : vocab.token_to_id) {
  5960. if (false
  5961. || t.first == "<|eot_id|>"
  5962. || t.first == "<|im_end|>"
  5963. || t.first == "<|end|>"
  5964. || t.first == "<end_of_turn>"
  5965. || t.first == "<|endoftext|>"
  5966. || t.first == "<|eom_id|>"
  5967. || t.first == "<EOT>"
  5968. ) {
  5969. vocab.special_eog_ids.insert(t.second);
  5970. if ((vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) {
  5971. LLAMA_LOG_WARN("%s: control-looking token: %6d '%s' was not control-type; this is probably a bug in the model. its type will be overridden\n",
  5972. __func__, t.second, t.first.c_str());
  5973. vocab.id_to_token[t.second].attr = LLAMA_TOKEN_ATTR_CONTROL;
  5974. }
  5975. } else {
  5976. // token is control, but not marked as EOG -> print a debug log
  5977. if (vocab.id_to_token[t.second].attr & LLAMA_TOKEN_ATTR_CONTROL && vocab.special_eog_ids.count(t.second) == 0) {
  5978. LLAMA_LOG_DEBUG("%s: control token: %6d '%s' is not marked as EOG\n",
  5979. __func__, t.second, t.first.c_str());
  5980. }
  5981. }
  5982. }
  5983. // sanity checks
  5984. if (vocab.special_eos_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eos_id) == 0) {
  5985. vocab.special_eog_ids.insert(vocab.special_eos_id);
  5986. LLAMA_LOG_WARN("%s: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  5987. }
  5988. if (vocab.special_eot_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eot_id) == 0) {
  5989. vocab.special_eog_ids.insert(vocab.special_eot_id);
  5990. LLAMA_LOG_WARN("%s: special_eot_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  5991. }
  5992. if (vocab.special_eom_id != LLAMA_TOKEN_NULL && vocab.special_eog_ids.count(vocab.special_eom_id) == 0) {
  5993. vocab.special_eog_ids.insert(vocab.special_eom_id);
  5994. LLAMA_LOG_WARN("%s: special_eom_id is not in special_eog_ids - the tokenizer config may be incorrect\n", __func__);
  5995. }
  5996. }
  5997. // build special tokens cache
  5998. {
  5999. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  6000. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  6001. vocab.cache_special_tokens.push_back(id);
  6002. }
  6003. }
  6004. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  6005. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  6006. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  6007. }
  6008. );
  6009. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  6010. }
  6011. // build token to piece cache
  6012. {
  6013. size_t size_cache = 0;
  6014. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  6015. for (uint32_t id = 0; id < n_vocab; ++id) {
  6016. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  6017. size_cache += cache_token_to_piece[id].size();
  6018. }
  6019. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  6020. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  6021. }
  6022. // Handle per token attributes
  6023. //NOTE: Each model customizes per token attributes.
  6024. //NOTE: Per token attributes are missing from the GGUF file.
  6025. //TODO: Extract attributes from GGUF file.
  6026. {
  6027. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  6028. for (auto substr : substrs) {
  6029. if (str.find(substr) < std::string::npos) {
  6030. return true;
  6031. }
  6032. }
  6033. return false;
  6034. };
  6035. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  6036. uint32_t current = vocab.id_to_token.at(id).attr;
  6037. current = value ? (current | attr) : (current & ~attr);
  6038. vocab.id_to_token[id].attr = (llama_token_attr) current;
  6039. };
  6040. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  6041. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  6042. };
  6043. std::string model_name;
  6044. std::string tokenizer_pre;
  6045. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  6046. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  6047. // model name to lowercase
  6048. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  6049. [] (const std::string::value_type x) {
  6050. return std::tolower(x);
  6051. }
  6052. );
  6053. // set attributes by model/tokenizer name
  6054. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  6055. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  6056. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  6057. for (auto id : vocab.cache_special_tokens) {
  6058. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6059. }
  6060. for (auto token : {"</s>"}) {
  6061. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  6062. }
  6063. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  6064. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  6065. }
  6066. }
  6067. }
  6068. }
  6069. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  6070. const auto & hparams = model.hparams;
  6071. const auto & vocab = model.vocab;
  6072. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  6073. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  6074. bool is_var = false;
  6075. std::vector<uint32_t> v;
  6076. for (uint32_t i = 0; i < n; ++i) {
  6077. v.push_back(f(i));
  6078. if (v[i] != v[0]) {
  6079. is_var = true;
  6080. }
  6081. }
  6082. std::stringstream ss;
  6083. if (is_var) {
  6084. ss << "[";
  6085. for (uint32_t i = 0; i < n; ++i) {
  6086. ss << v[i];
  6087. if (i < n - 1) {
  6088. ss << ", ";
  6089. }
  6090. }
  6091. ss << "]";
  6092. } else {
  6093. ss << v[0];
  6094. }
  6095. return ss.str();
  6096. };
  6097. // hparams
  6098. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  6099. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  6100. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  6101. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  6102. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  6103. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  6104. if (!hparams.vocab_only) {
  6105. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  6106. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  6107. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  6108. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  6109. 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());
  6110. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  6111. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  6112. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  6113. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  6114. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  6115. 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());
  6116. 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());
  6117. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  6118. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  6119. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  6120. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  6121. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  6122. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  6123. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  6124. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  6125. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  6126. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  6127. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  6128. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  6129. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  6130. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  6131. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  6132. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  6133. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  6134. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  6135. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  6136. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  6137. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  6138. }
  6139. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  6140. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  6141. if (ml.n_elements >= 1e12) {
  6142. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  6143. } else if (ml.n_elements >= 1e9) {
  6144. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  6145. } else if (ml.n_elements >= 1e6) {
  6146. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  6147. } else {
  6148. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  6149. }
  6150. if (ml.n_bytes < GiB) {
  6151. 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);
  6152. } else {
  6153. 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);
  6154. }
  6155. // general kv
  6156. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  6157. // special tokens
  6158. 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() ); }
  6159. 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() ); }
  6160. 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() ); }
  6161. 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() ); }
  6162. 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() ); }
  6163. 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() ); }
  6164. 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() ); }
  6165. 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() ); }
  6166. 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() ); }
  6167. 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() ); }
  6168. if (vocab.special_fim_pre_id != -1) { LLAMA_LOG_INFO( "%s: FIM PRE token = %d '%s'\n", __func__, vocab.special_fim_pre_id, vocab.id_to_token[vocab.special_fim_pre_id].text.c_str() ); }
  6169. if (vocab.special_fim_suf_id != -1) { LLAMA_LOG_INFO( "%s: FIM SUF token = %d '%s'\n", __func__, vocab.special_fim_suf_id, vocab.id_to_token[vocab.special_fim_suf_id].text.c_str() ); }
  6170. if (vocab.special_fim_mid_id != -1) { LLAMA_LOG_INFO( "%s: FIM MID token = %d '%s'\n", __func__, vocab.special_fim_mid_id, vocab.id_to_token[vocab.special_fim_mid_id].text.c_str() ); }
  6171. if (vocab.special_fim_pad_id != -1) { LLAMA_LOG_INFO( "%s: FIM PAD token = %d '%s'\n", __func__, vocab.special_fim_pad_id, vocab.id_to_token[vocab.special_fim_pad_id].text.c_str() ); }
  6172. if (vocab.special_fim_rep_id != -1) { LLAMA_LOG_INFO( "%s: FIM REP token = %d '%s'\n", __func__, vocab.special_fim_rep_id, vocab.id_to_token[vocab.special_fim_rep_id].text.c_str() ); }
  6173. if (vocab.special_fim_sep_id != -1) { LLAMA_LOG_INFO( "%s: FIM SEP token = %d '%s'\n", __func__, vocab.special_fim_sep_id, vocab.id_to_token[vocab.special_fim_sep_id].text.c_str() ); }
  6174. for (const auto & id : vocab.special_eog_ids) {
  6175. LLAMA_LOG_INFO( "%s: EOG token = %d '%s'\n", __func__, id, vocab.id_to_token[id].text.c_str() );
  6176. }
  6177. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  6178. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  6179. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  6180. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  6181. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  6182. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6183. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  6184. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  6185. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  6186. }
  6187. if (model.arch == LLM_ARCH_QWEN2MOE) {
  6188. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  6189. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  6190. }
  6191. if (model.arch == LLM_ARCH_GRANITE || model.arch == LLM_ARCH_GRANITE_MOE) {
  6192. LLAMA_LOG_INFO("%s: f_embedding_scale = %f\n", __func__, hparams.f_embedding_scale);
  6193. LLAMA_LOG_INFO("%s: f_residual_scale = %f\n", __func__, hparams.f_residual_scale);
  6194. LLAMA_LOG_INFO("%s: f_attention_scale = %f\n", __func__, hparams.f_attention_scale);
  6195. }
  6196. }
  6197. // Returns false if cancelled by progress_callback
  6198. static bool llm_load_tensors(
  6199. llama_model_loader & ml,
  6200. llama_model & model,
  6201. int n_gpu_layers,
  6202. enum llama_split_mode split_mode,
  6203. int main_gpu,
  6204. const float * tensor_split,
  6205. bool use_mlock,
  6206. llama_progress_callback progress_callback,
  6207. void * progress_callback_user_data) {
  6208. auto & hparams = model.hparams;
  6209. // check if the value of main_gpu is valid
  6210. if (llama_get_device_count(model) > 0 &&
  6211. split_mode != LLAMA_SPLIT_MODE_LAYER &&
  6212. (main_gpu < 0 || main_gpu >= llama_get_device_count(model))) {
  6213. throw std::runtime_error(format("invalid value for main_gpu: %d (available devices: %d)", main_gpu, llama_get_device_count(model)));
  6214. }
  6215. model.split_mode = split_mode;
  6216. model.main_gpu = main_gpu;
  6217. model.n_gpu_layers = n_gpu_layers;
  6218. const int n_layer = hparams.n_layer;
  6219. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  6220. bool use_mmap_buffer = true;
  6221. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  6222. model.buft_input = llama_default_buffer_type_cpu(model, true);
  6223. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  6224. model.buft_layer.resize(n_layer);
  6225. // assign cpu layers
  6226. for (int i = 0; i < i_gpu_start; ++i) {
  6227. #ifdef GGML_USE_AMX
  6228. model.buft_layer[i] = {
  6229. ggml_backend_amx_buffer_type(),
  6230. llama_default_buffer_type_cpu(model, true)
  6231. };
  6232. #else
  6233. model.buft_layer[i] = llama_default_buffer_type_cpu(model, true);
  6234. #endif
  6235. }
  6236. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  6237. // calculate the split points
  6238. int device_count = llama_get_device_count(model);
  6239. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  6240. std::vector<float> splits(device_count);
  6241. if (all_zero) {
  6242. // default split, by free memory
  6243. for (int i = 0; i < device_count; ++i) {
  6244. splits[i] = llama_get_device_memory(model, i);
  6245. }
  6246. } else {
  6247. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  6248. }
  6249. // sum and normalize the splits to get the split points
  6250. float split_sum = 0.0f;
  6251. for (int i = 0; i < device_count; ++i) {
  6252. split_sum += splits[i];
  6253. splits[i] = split_sum;
  6254. }
  6255. for (int i = 0; i < device_count; ++i) {
  6256. splits[i] /= split_sum;
  6257. }
  6258. // assign the repeating layers to the devices according to the splits
  6259. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  6260. for (int i = i_gpu_start; i < n_layer; ++i) {
  6261. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  6262. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  6263. }
  6264. // assign the output layer
  6265. if (n_gpu_layers > n_layer) {
  6266. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  6267. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  6268. } else {
  6269. model.buft_output = llama_default_buffer_type_cpu(model, true);
  6270. }
  6271. } else {
  6272. ggml_backend_buffer_type_t split_buft;
  6273. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  6274. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  6275. } else {
  6276. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  6277. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  6278. }
  6279. // assign the repeating layers
  6280. for (int i = i_gpu_start; i < n_layer; ++i) {
  6281. model.buft_layer[i] = {
  6282. split_buft,
  6283. llama_default_buffer_type_offload(model, main_gpu)
  6284. };
  6285. }
  6286. // assign the output layer
  6287. if (n_gpu_layers > n_layer) {
  6288. model.buft_output = {
  6289. split_buft,
  6290. llama_default_buffer_type_offload(model, main_gpu)
  6291. };
  6292. } else {
  6293. model.buft_output = llama_default_buffer_type_cpu(model, true);
  6294. }
  6295. }
  6296. // count used buffer types
  6297. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  6298. buft_layer_count[model.buft_input.buft]++;
  6299. buft_layer_count[model.buft_input.buft_matrix]++;
  6300. buft_layer_count[model.buft_output.buft]++;
  6301. buft_layer_count[model.buft_output.buft_matrix]++;
  6302. for (int i = 0; i < n_layer; ++i) {
  6303. buft_layer_count[model.buft_layer[i].buft]++;
  6304. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  6305. }
  6306. // create one context per buffer type
  6307. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  6308. // for moe merged tensors
  6309. ctx_size += ggml_tensor_overhead()*n_layer*3;
  6310. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  6311. for (auto & it : buft_layer_count) {
  6312. struct ggml_init_params params = {
  6313. /*.mem_size =*/ ctx_size,
  6314. /*.mem_buffer =*/ NULL,
  6315. /*.no_alloc =*/ true,
  6316. };
  6317. ggml_context * ctx = ggml_init(params);
  6318. if (!ctx) {
  6319. throw std::runtime_error(format("failed to create context"));
  6320. }
  6321. ctx_map[it.first] = ctx;
  6322. model.ctxs.push_back(ctx);
  6323. }
  6324. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  6325. // create tensors for the weights
  6326. {
  6327. // note: cast to int64_t since we will use these for the tensor dimensions
  6328. const int64_t n_head = hparams.n_head();
  6329. const int64_t n_head_kv = hparams.n_head_kv();
  6330. const int64_t n_embd = hparams.n_embd;
  6331. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6332. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6333. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6334. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  6335. const int64_t n_ff = hparams.n_ff();
  6336. const int64_t n_embd_gqa = n_embd_v_gqa;
  6337. const int64_t n_vocab = hparams.n_vocab;
  6338. const int64_t n_vocab_type = hparams.n_vocab_type;
  6339. const int64_t n_rot = hparams.n_rot;
  6340. const int64_t n_expert = hparams.n_expert;
  6341. const int64_t n_expert_used = hparams.n_expert_used;
  6342. const int64_t n_ctx_train = hparams.n_ctx_train;
  6343. if (n_expert > 0 && hparams.n_expert_used == 0) {
  6344. throw std::runtime_error("model has expert layers but no expert layers are used");
  6345. }
  6346. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  6347. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  6348. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  6349. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  6350. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  6351. model.layers.resize(n_layer);
  6352. const auto tn = LLM_TN(model.arch);
  6353. switch (model.arch) {
  6354. case LLM_ARCH_LLAMA:
  6355. case LLM_ARCH_REFACT:
  6356. case LLM_ARCH_MINICPM:
  6357. case LLM_ARCH_GRANITE:
  6358. case LLM_ARCH_GRANITE_MOE:
  6359. {
  6360. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6361. // output
  6362. {
  6363. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6364. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6365. // if output is NULL, init from the input tok embed
  6366. if (model.output == NULL) {
  6367. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6368. }
  6369. }
  6370. for (int i = 0; i < n_layer; ++i) {
  6371. ggml_context * ctx_layer = ctx_for_layer(i);
  6372. ggml_context * ctx_split = ctx_for_layer_split(i);
  6373. auto & layer = model.layers[i];
  6374. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6375. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6376. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6377. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6378. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6379. // optional bias tensors
  6380. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6381. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6382. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6383. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6384. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6385. 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));
  6386. if (n_expert == 0) {
  6387. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6388. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6389. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6390. // optional MLP bias
  6391. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6392. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6393. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6394. } else {
  6395. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6396. 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);
  6397. if (layer.ffn_gate_exps) {
  6398. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6399. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6400. } else {
  6401. // merge split expert into a single tensor for compatibility with older models
  6402. // requires disabling mmap
  6403. use_mmap_buffer = false;
  6404. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6405. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6406. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6407. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6408. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6409. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6410. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6411. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6412. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6413. for (uint32_t x = 0; x < n_expert; ++x) {
  6414. // the individual experts are loaded into a view of the merged tensor
  6415. 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);
  6416. 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);
  6417. 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);
  6418. }
  6419. }
  6420. }
  6421. }
  6422. } break;
  6423. case LLM_ARCH_MINICPM3:
  6424. {
  6425. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6426. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6427. const int64_t q_lora_rank = hparams.n_lora_q;
  6428. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6429. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6430. // output
  6431. {
  6432. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6433. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6434. // if output is NULL, init from the input tok embed
  6435. if (model.output == NULL) {
  6436. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6437. }
  6438. }
  6439. for (int i = 0; i < n_layer; ++i) {
  6440. ggml_context * ctx_layer = ctx_for_layer(i);
  6441. ggml_context * ctx_split = ctx_for_layer_split(i);
  6442. auto & layer = model.layers[i];
  6443. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6444. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6445. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6446. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6447. 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});
  6448. 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)});
  6449. 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)});
  6450. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6451. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6452. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6453. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6454. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6455. 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));
  6456. 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));
  6457. }
  6458. } break;
  6459. case LLM_ARCH_GROK:
  6460. {
  6461. if (n_expert == 0) {
  6462. throw std::runtime_error("Grok model cannot have zero experts");
  6463. }
  6464. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6465. // output
  6466. {
  6467. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6468. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6469. // if output is NULL, init from the input tok embed
  6470. if (model.output == NULL) {
  6471. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6472. }
  6473. }
  6474. for (int i = 0; i < n_layer; ++i) {
  6475. ggml_context * ctx_layer = ctx_for_layer(i);
  6476. ggml_context * ctx_split = ctx_for_layer_split(i);
  6477. auto & layer = model.layers[i];
  6478. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6479. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6480. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6481. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6482. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6483. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6484. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6485. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6486. 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);
  6487. if (layer.ffn_gate_exps) {
  6488. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6489. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6490. } else {
  6491. // merge split expert into a single tensor for compatibility with older models
  6492. // requires disabling mmap
  6493. use_mmap_buffer = false;
  6494. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6495. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6496. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6497. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6498. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6499. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6500. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6501. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6502. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6503. for (uint32_t x = 0; x < n_expert; ++x) {
  6504. // the individual experts are loaded into a view of the merged tensor
  6505. 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);
  6506. 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);
  6507. 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);
  6508. }
  6509. }
  6510. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6511. }
  6512. } break;
  6513. case LLM_ARCH_DBRX:
  6514. {
  6515. if (n_expert == 0) {
  6516. throw std::runtime_error("DBRX model cannot have zero experts");
  6517. }
  6518. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6519. // output
  6520. {
  6521. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6522. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6523. }
  6524. for (int i = 0; i < n_layer; ++i) {
  6525. ggml_context * ctx_layer = ctx_for_layer(i);
  6526. ggml_context * ctx_split = ctx_for_layer_split(i);
  6527. auto & layer = model.layers[i];
  6528. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6529. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6530. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6531. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6532. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6533. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6534. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  6535. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6536. }
  6537. } break;
  6538. case LLM_ARCH_BAICHUAN:
  6539. {
  6540. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6541. {
  6542. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6543. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6544. }
  6545. for (int i = 0; i < n_layer; ++i) {
  6546. ggml_context * ctx_layer = ctx_for_layer(i);
  6547. ggml_context * ctx_split = ctx_for_layer_split(i);
  6548. auto & layer = model.layers[i];
  6549. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6550. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6551. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6552. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6553. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6554. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6555. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6556. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6557. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6558. }
  6559. } break;
  6560. case LLM_ARCH_FALCON:
  6561. {
  6562. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6563. // output
  6564. {
  6565. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6566. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6567. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6568. if (!model.output) {
  6569. 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
  6570. }
  6571. }
  6572. for (int i = 0; i < n_layer; ++i) {
  6573. ggml_context * ctx_layer = ctx_for_layer(i);
  6574. ggml_context * ctx_split = ctx_for_layer_split(i);
  6575. auto & layer = model.layers[i];
  6576. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6577. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6578. 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);
  6579. 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);
  6580. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6581. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6582. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6583. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6584. }
  6585. } break;
  6586. case LLM_ARCH_STARCODER:
  6587. {
  6588. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6589. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6590. // output
  6591. {
  6592. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6593. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6594. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6595. if (!model.output) {
  6596. // needs to be on GPU
  6597. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6598. }
  6599. }
  6600. for (int i = 0; i < n_layer; ++i) {
  6601. ggml_context * ctx_layer = ctx_for_layer(i);
  6602. ggml_context * ctx_split = ctx_for_layer_split(i);
  6603. auto & layer = model.layers[i];
  6604. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6605. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6606. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6607. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6608. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6609. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6610. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6611. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6612. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6613. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6614. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6615. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6616. }
  6617. } break;
  6618. case LLM_ARCH_BERT:
  6619. case LLM_ARCH_NOMIC_BERT:
  6620. {
  6621. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6622. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  6623. if (model.arch == LLM_ARCH_BERT) {
  6624. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6625. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6626. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6627. model.cls_out = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6628. model.cls_out_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS_OUT, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6629. }
  6630. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6631. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  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. if (model.arch == LLM_ARCH_BERT) {
  6637. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6638. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6639. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6640. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6641. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6642. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6643. } else {
  6644. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6645. }
  6646. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6647. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6648. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6649. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6650. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6651. if (model.arch == LLM_ARCH_BERT) {
  6652. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6653. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6654. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6655. } else {
  6656. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6657. }
  6658. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6659. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6660. }
  6661. } break;
  6662. case LLM_ARCH_JINA_BERT_V2:
  6663. {
  6664. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  6665. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  6666. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  6667. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  6668. model.cls = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "weight"), {n_embd, 1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6669. model.cls_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_CLS, "bias"), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6670. for (int i = 0; i < n_layer; ++i) {
  6671. ggml_context * ctx_layer = ctx_for_layer(i);
  6672. ggml_context * ctx_split = ctx_for_layer_split(i);
  6673. auto & layer = model.layers[i]; // JinaBertLayer
  6674. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6675. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6676. 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);
  6677. 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);
  6678. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6679. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6680. 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);
  6681. 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);
  6682. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6683. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6684. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  6685. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  6686. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  6687. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6688. 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);
  6689. 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);
  6690. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6691. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6692. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6693. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6694. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6695. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6696. }
  6697. } break;
  6698. case LLM_ARCH_BLOOM:
  6699. {
  6700. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6701. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6702. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6703. // output
  6704. {
  6705. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6706. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6707. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6708. }
  6709. for (int i = 0; i < n_layer; ++i) {
  6710. ggml_context * ctx_layer = ctx_for_layer(i);
  6711. ggml_context * ctx_split = ctx_for_layer_split(i);
  6712. auto & layer = model.layers[i];
  6713. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6714. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6715. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6716. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6717. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6718. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6719. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6720. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6721. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6722. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6723. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6724. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6725. }
  6726. } break;
  6727. case LLM_ARCH_MPT:
  6728. {
  6729. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6730. 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);
  6731. // output
  6732. {
  6733. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6734. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6735. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6736. if (!model.output) {
  6737. 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
  6738. }
  6739. }
  6740. for (int i = 0; i < n_layer; ++i) {
  6741. ggml_context * ctx_layer = ctx_for_layer(i);
  6742. ggml_context * ctx_split = ctx_for_layer_split(i);
  6743. auto & layer = model.layers[i];
  6744. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6745. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6746. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6747. 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);
  6748. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6749. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6750. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6751. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6752. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6753. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6754. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6755. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6756. 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);
  6757. 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);
  6758. 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);
  6759. 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);
  6760. // AWQ ScaleActivation layer
  6761. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6762. }
  6763. } break;
  6764. case LLM_ARCH_STABLELM:
  6765. {
  6766. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6767. // output
  6768. {
  6769. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6770. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6771. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6772. }
  6773. for (int i = 0; i < n_layer; ++i) {
  6774. ggml_context * ctx_layer = ctx_for_layer(i);
  6775. ggml_context * ctx_split = ctx_for_layer_split(i);
  6776. auto & layer = model.layers[i];
  6777. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6778. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6779. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6780. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6781. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6782. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6783. // optional bias tensors, present in Stable LM 2 1.6B
  6784. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6785. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6786. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6787. // optional q and k layernorms, present in StableLM 2 12B
  6788. 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);
  6789. 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);
  6790. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  6791. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6792. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6793. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6794. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6795. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6796. }
  6797. } break;
  6798. case LLM_ARCH_QWEN:
  6799. {
  6800. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6801. // output
  6802. {
  6803. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6804. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6805. }
  6806. for (int i = 0; i < n_layer; ++i) {
  6807. ggml_context * ctx_layer = ctx_for_layer(i);
  6808. ggml_context * ctx_split = ctx_for_layer_split(i);
  6809. auto & layer = model.layers[i];
  6810. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6811. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  6812. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  6813. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6814. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6815. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  6816. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  6817. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  6818. }
  6819. } break;
  6820. case LLM_ARCH_QWEN2:
  6821. {
  6822. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6823. // output
  6824. {
  6825. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6826. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6827. // if output is NULL, init from the input tok embed
  6828. if (model.output == NULL) {
  6829. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6830. }
  6831. }
  6832. for (int i = 0; i < n_layer; ++i) {
  6833. ggml_context * ctx_layer = ctx_for_layer(i);
  6834. ggml_context * ctx_split = ctx_for_layer_split(i);
  6835. auto & layer = model.layers[i];
  6836. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6837. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6838. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6839. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6840. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6841. // optional bias tensors
  6842. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6843. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6844. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6845. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6846. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6847. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6848. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6849. }
  6850. } break;
  6851. case LLM_ARCH_QWEN2MOE:
  6852. {
  6853. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6854. // output
  6855. {
  6856. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6857. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6858. }
  6859. for (int i = 0; i < n_layer; ++i) {
  6860. ggml_context * ctx_layer = ctx_for_layer(i);
  6861. ggml_context * ctx_split = ctx_for_layer_split(i);
  6862. auto & layer = model.layers[i];
  6863. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6864. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6865. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6866. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6867. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6868. // optional bias tensors
  6869. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6870. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6871. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6872. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6873. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6874. GGML_ASSERT(n_expert > 0);
  6875. GGML_ASSERT(n_expert_used > 0);
  6876. // MoE branch
  6877. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  6878. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6879. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6880. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6881. // Shared expert branch
  6882. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  6883. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  6884. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  6885. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  6886. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  6887. }
  6888. } break;
  6889. case LLM_ARCH_PHI2:
  6890. {
  6891. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6892. // output
  6893. {
  6894. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6895. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6896. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6897. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  6898. }
  6899. for (int i = 0; i < n_layer; ++i) {
  6900. ggml_context * ctx_layer = ctx_for_layer(i);
  6901. ggml_context * ctx_split = ctx_for_layer_split(i);
  6902. auto & layer = model.layers[i];
  6903. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6904. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6905. 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);
  6906. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6907. if (layer.wqkv == nullptr) {
  6908. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6909. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6910. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6911. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6912. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6913. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6914. }
  6915. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6916. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6917. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6918. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6919. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6920. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6921. }
  6922. } break;
  6923. case LLM_ARCH_PHI3:
  6924. {
  6925. const int64_t n_embd_head = n_embd / n_head;
  6926. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  6927. // output
  6928. {
  6929. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  6930. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  6931. }
  6932. for (int i = 0; i < n_layer; ++i) {
  6933. ggml_context * ctx_layer = ctx_for_layer(i);
  6934. ggml_context * ctx_split = ctx_for_layer_split(i);
  6935. auto & layer = model.layers[i];
  6936. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  6937. layer.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);
  6938. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  6939. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  6940. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  6941. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  6942. 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));
  6943. 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));
  6944. }
  6945. } break;
  6946. case LLM_ARCH_PLAMO:
  6947. {
  6948. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6949. // output
  6950. {
  6951. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6952. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6953. }
  6954. for (int i = 0; i < n_layer; ++i) {
  6955. ggml_context * ctx_layer = ctx_for_layer(i);
  6956. ggml_context * ctx_split = ctx_for_layer_split(i);
  6957. auto & layer = model.layers[i];
  6958. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6959. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6960. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6961. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6962. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6963. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6964. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6965. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6966. }
  6967. } break;
  6968. case LLM_ARCH_GPT2:
  6969. {
  6970. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6971. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6972. // output
  6973. {
  6974. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6975. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6976. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6977. }
  6978. for (int i = 0; i < n_layer; ++i) {
  6979. ggml_context * ctx_layer = ctx_for_layer(i);
  6980. ggml_context * ctx_split = ctx_for_layer_split(i);
  6981. auto & layer = model.layers[i];
  6982. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6983. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6984. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6985. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6986. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6987. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6988. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6989. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6990. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6991. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6992. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6993. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6994. }
  6995. } break;
  6996. case LLM_ARCH_CODESHELL:
  6997. {
  6998. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6999. // output
  7000. {
  7001. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7002. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7003. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7004. }
  7005. for (int i = 0; i < n_layer; ++i) {
  7006. ggml_context * ctx_layer = ctx_for_layer(i);
  7007. ggml_context * ctx_split = ctx_for_layer_split(i);
  7008. auto & layer = model.layers[i];
  7009. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7010. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7011. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7012. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7013. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7014. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7015. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7016. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7017. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7018. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7019. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7020. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7021. }
  7022. } break;
  7023. case LLM_ARCH_ORION:
  7024. {
  7025. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7026. {
  7027. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7028. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7029. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7030. }
  7031. for (int i = 0; i < n_layer; ++i) {
  7032. ggml_context * ctx_layer = ctx_for_layer(i);
  7033. ggml_context * ctx_split = ctx_for_layer_split(i);
  7034. auto & layer = model.layers[i];
  7035. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7036. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7037. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7038. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7039. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7040. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7041. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7042. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7043. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7044. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7045. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7046. }
  7047. } break;
  7048. case LLM_ARCH_INTERNLM2:
  7049. {
  7050. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7051. // output
  7052. {
  7053. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7054. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7055. }
  7056. for (int i = 0; i < n_layer; ++i) {
  7057. ggml_context * ctx_layer = ctx_for_layer(i);
  7058. ggml_context * ctx_split = ctx_for_layer_split(i);
  7059. auto & layer = model.layers[i];
  7060. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7061. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7062. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7063. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7064. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7065. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7066. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7067. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7068. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7069. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7070. }
  7071. } break;
  7072. case LLM_ARCH_GEMMA:
  7073. {
  7074. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7075. // output
  7076. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7077. 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
  7078. for (int i = 0; i < n_layer; ++i) {
  7079. ggml_context * ctx_layer = ctx_for_layer(i);
  7080. ggml_context * ctx_split = ctx_for_layer_split(i);
  7081. auto & layer = model.layers[i];
  7082. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7083. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7084. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7085. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7086. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7087. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7088. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7089. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7090. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7091. }
  7092. } break;
  7093. case LLM_ARCH_GEMMA2:
  7094. {
  7095. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7096. // output
  7097. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7098. 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
  7099. for (int i = 0; i < n_layer; ++i) {
  7100. ggml_context * ctx_layer = ctx_for_layer(i);
  7101. ggml_context * ctx_split = ctx_for_layer_split(i);
  7102. auto & layer = model.layers[i];
  7103. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7104. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7105. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7106. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7107. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7108. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  7109. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7110. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7111. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7112. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7113. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  7114. }
  7115. } break;
  7116. case LLM_ARCH_STARCODER2:
  7117. {
  7118. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7119. // output
  7120. {
  7121. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7122. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7123. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7124. // if output is NULL, init from the input tok embed
  7125. if (model.output == NULL) {
  7126. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7127. }
  7128. }
  7129. for (int i = 0; i < n_layer; ++i) {
  7130. ggml_context * ctx_layer = ctx_for_layer(i);
  7131. ggml_context * ctx_split = ctx_for_layer_split(i);
  7132. auto & layer = model.layers[i];
  7133. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7134. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7135. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7136. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7137. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7138. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7139. // optional bias tensors
  7140. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  7141. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  7142. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  7143. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7144. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7145. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7146. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7147. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7148. // optional bias tensors
  7149. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7150. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  7151. }
  7152. } break;
  7153. case LLM_ARCH_MAMBA:
  7154. {
  7155. const int64_t d_conv = hparams.ssm_d_conv;
  7156. const int64_t d_inner = hparams.ssm_d_inner;
  7157. const int64_t d_state = hparams.ssm_d_state;
  7158. const int64_t dt_rank = hparams.ssm_dt_rank;
  7159. // only an expansion factor of 2 is supported for now
  7160. GGML_ASSERT(2 * n_embd == d_inner);
  7161. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7162. // output
  7163. {
  7164. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7165. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7166. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  7167. if (model.output == NULL) {
  7168. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7169. }
  7170. }
  7171. for (int i = 0; i < n_layer; ++i) {
  7172. ggml_context * ctx_layer = ctx_for_layer(i);
  7173. ggml_context * ctx_split = ctx_for_layer_split(i);
  7174. auto & layer = model.layers[i];
  7175. // norm
  7176. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7177. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  7178. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  7179. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  7180. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  7181. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  7182. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  7183. // no "weight" suffix for these
  7184. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  7185. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  7186. // out_proj
  7187. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  7188. }
  7189. } break;
  7190. case LLM_ARCH_XVERSE:
  7191. {
  7192. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7193. {
  7194. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7195. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7196. }
  7197. for (int i = 0; i < n_layer; ++i) {
  7198. ggml_context * ctx_layer = ctx_for_layer(i);
  7199. ggml_context * ctx_split = ctx_for_layer_split(i);
  7200. auto & layer = model.layers[i];
  7201. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7202. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7203. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7204. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7205. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7206. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7207. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7208. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7209. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7210. }
  7211. } break;
  7212. case LLM_ARCH_COMMAND_R:
  7213. {
  7214. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7215. // output
  7216. {
  7217. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7218. // init output from the input tok embed
  7219. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7220. }
  7221. for (int i = 0; i < n_layer; ++i) {
  7222. ggml_context * ctx_layer = ctx_for_layer(i);
  7223. ggml_context * ctx_split = ctx_for_layer_split(i);
  7224. auto & layer = model.layers[i];
  7225. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7226. if (n_layer >= 64){
  7227. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7228. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7229. }
  7230. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7231. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7232. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7233. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7234. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7235. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7236. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7237. }
  7238. } break;
  7239. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  7240. {
  7241. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7242. // output
  7243. {
  7244. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7245. // if output is NULL, init from the input tok embed
  7246. if (model.output == NULL) {
  7247. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7248. }
  7249. }
  7250. for (int i = 0; i < n_layer; ++i) {
  7251. ggml_context * ctx_split = ctx_for_layer_split(i);
  7252. auto & layer = model.layers[i];
  7253. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7254. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7255. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7256. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7257. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7258. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7259. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7260. }
  7261. } break;
  7262. case LLM_ARCH_OLMOE:
  7263. {
  7264. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7265. // output
  7266. {
  7267. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7268. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7269. }
  7270. for (int i = 0; i < n_layer; ++i) {
  7271. ggml_context * ctx_layer = ctx_for_layer(i);
  7272. ggml_context * ctx_split = ctx_for_layer_split(i);
  7273. auto & layer = model.layers[i];
  7274. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7275. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7276. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7277. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7278. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7279. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd});
  7280. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd});
  7281. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7282. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7283. GGML_ASSERT(n_expert > 0);
  7284. GGML_ASSERT(n_expert_used > 0);
  7285. // MoE branch
  7286. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7287. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  7288. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7289. }
  7290. } break;
  7291. case LLM_ARCH_OPENELM:
  7292. {
  7293. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7294. // output
  7295. {
  7296. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7297. // init output from the input tok embed
  7298. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7299. }
  7300. for (int i = 0; i < n_layer; ++i) {
  7301. const int64_t n_head = hparams.n_head(i);
  7302. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  7303. const int64_t n_ff = hparams.n_ff(i);
  7304. ggml_context * ctx_layer = ctx_for_layer(i);
  7305. ggml_context * ctx_split = ctx_for_layer_split(i);
  7306. auto & layer = model.layers[i];
  7307. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7308. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  7309. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  7310. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  7311. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  7312. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7313. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7314. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7315. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7316. }
  7317. } break;
  7318. case LLM_ARCH_GPTNEOX:
  7319. {
  7320. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7321. // output
  7322. {
  7323. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7324. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7325. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7326. }
  7327. for (int i = 0; i < n_layer; ++i) {
  7328. ggml_context * ctx_layer = ctx_for_layer(i);
  7329. ggml_context * ctx_split = ctx_for_layer_split(i);
  7330. auto & layer = model.layers[i];
  7331. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7332. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7333. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7334. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7335. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7336. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7337. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7338. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7339. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7340. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7341. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7342. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7343. }
  7344. } break;
  7345. case LLM_ARCH_ARCTIC:
  7346. {
  7347. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7348. // output
  7349. {
  7350. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7351. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7352. // if output is NULL, init from the input tok embed
  7353. if (model.output == NULL) {
  7354. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7355. }
  7356. }
  7357. for (int i = 0; i < n_layer; ++i) {
  7358. ggml_context * ctx_layer = ctx_for_layer(i);
  7359. ggml_context * ctx_split = ctx_for_layer_split(i);
  7360. auto & layer = model.layers[i];
  7361. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7362. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7363. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7364. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7365. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7366. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7367. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  7368. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  7369. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  7370. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7371. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  7372. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  7373. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  7374. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  7375. }
  7376. } break;
  7377. case LLM_ARCH_DEEPSEEK2:
  7378. {
  7379. const bool is_lite = (hparams.n_layer == 27);
  7380. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  7381. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  7382. const int64_t q_lora_rank = hparams.n_lora_q;
  7383. const int64_t kv_lora_rank = hparams.n_lora_kv;
  7384. const int64_t n_ff_exp = hparams.n_ff_exp;
  7385. const int64_t n_expert_shared = hparams.n_expert_shared;
  7386. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7387. // output
  7388. {
  7389. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7390. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7391. }
  7392. for (int i = 0; i < n_layer; ++i) {
  7393. ggml_context * ctx_layer = ctx_for_layer(i);
  7394. ggml_context * ctx_split = ctx_for_layer_split(i);
  7395. auto & layer = model.layers[i];
  7396. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7397. if (!is_lite) {
  7398. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  7399. }
  7400. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  7401. if (!is_lite) {
  7402. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  7403. 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});
  7404. } else {
  7405. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7406. }
  7407. 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)});
  7408. 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)});
  7409. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  7410. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7411. if (i < (int) hparams.n_layer_dense_lead) {
  7412. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7413. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7414. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7415. } else {
  7416. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  7417. GGML_ASSERT(n_expert > 0);
  7418. GGML_ASSERT(n_expert_used > 0);
  7419. // MoE branch
  7420. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7421. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  7422. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  7423. // Shared expert branch
  7424. 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});
  7425. 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});
  7426. 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});
  7427. }
  7428. }
  7429. } break;
  7430. case LLM_ARCH_BITNET:
  7431. {
  7432. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7433. // output
  7434. {
  7435. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7436. }
  7437. for (int i = 0; i < n_layer; ++i) {
  7438. ggml_context * ctx_layer = ctx_for_layer(i);
  7439. ggml_context * ctx_split = ctx_for_layer_split(i);
  7440. auto & layer = model.layers[i];
  7441. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7442. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  7443. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7444. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7445. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7446. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7447. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7448. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7449. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7450. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7451. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7452. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  7453. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7454. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7455. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7456. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7457. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7458. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7459. }
  7460. } break;
  7461. case LLM_ARCH_T5:
  7462. {
  7463. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7464. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7465. // output
  7466. {
  7467. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7468. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  7469. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7470. // if output is NULL, init from the input tok embed
  7471. if (model.output == NULL) {
  7472. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7473. }
  7474. }
  7475. for (int i = 0; i < n_layer; ++i) {
  7476. ggml_context * ctx_layer = ctx_for_layer(i);
  7477. ggml_context * ctx_split = ctx_for_layer_split(i);
  7478. auto & layer = model.layers[i];
  7479. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7480. 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);
  7481. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7482. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7483. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7484. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7485. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7486. 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);
  7487. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7488. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7489. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  7490. 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);
  7491. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7492. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7493. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7494. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7495. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  7496. // this tensor seems to be unused in HF transformers implementation
  7497. 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);
  7498. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7499. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7500. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7501. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7502. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  7503. 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);
  7504. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7505. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  7506. }
  7507. } break;
  7508. case LLM_ARCH_T5ENCODER:
  7509. {
  7510. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  7511. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7512. // output
  7513. {
  7514. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  7515. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7516. // if output is NULL, init from the input tok embed
  7517. if (model.output == NULL) {
  7518. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7519. }
  7520. }
  7521. for (int i = 0; i < n_layer; ++i) {
  7522. ggml_context * ctx_layer = ctx_for_layer(i);
  7523. ggml_context * ctx_split = ctx_for_layer_split(i);
  7524. auto & layer = model.layers[i];
  7525. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  7526. 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);
  7527. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  7528. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7529. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7530. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7531. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7532. 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);
  7533. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7534. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7535. }
  7536. } break;
  7537. case LLM_ARCH_JAIS:
  7538. {
  7539. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7540. // Output
  7541. {
  7542. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7543. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7544. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7545. }
  7546. for (int i = 0; i < n_layer; ++i) {
  7547. ggml_context * ctx_layer = ctx_for_layer(i);
  7548. ggml_context * ctx_split = ctx_for_layer_split(i);
  7549. auto & layer = model.layers[i];
  7550. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7551. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7552. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7553. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7554. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7555. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7556. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7557. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7558. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7559. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7560. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7561. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  7562. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7563. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7564. }
  7565. } break;
  7566. case LLM_ARCH_CHATGLM:
  7567. {
  7568. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7569. // output
  7570. {
  7571. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7572. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7573. }
  7574. for (int i = 0; i < n_layer; ++i) {
  7575. ggml_context * ctx_layer = ctx_for_layer(i);
  7576. ggml_context * ctx_split = ctx_for_layer_split(i);
  7577. auto & layer = model.layers[i];
  7578. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7579. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7580. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7581. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7582. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7583. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  7584. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7585. }
  7586. } break;
  7587. case LLM_ARCH_NEMOTRON:
  7588. {
  7589. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7590. // output
  7591. {
  7592. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7593. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7594. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7595. }
  7596. for (int i = 0; i < n_layer; ++i) {
  7597. ggml_context * ctx_layer = ctx_for_layer(i);
  7598. ggml_context * ctx_split = ctx_for_layer_split(i);
  7599. auto & layer = model.layers[i];
  7600. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7601. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7602. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7603. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7604. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7605. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7606. // optional bias tensors
  7607. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7608. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7609. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7610. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7611. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7612. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7613. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7614. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7615. // optional MLP bias
  7616. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7617. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7618. }
  7619. } break;
  7620. case LLM_ARCH_EXAONE:
  7621. {
  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 = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7626. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7627. }
  7628. for (int i = 0; i < n_layer; ++i) {
  7629. ggml_context * ctx_layer = ctx_for_layer(i);
  7630. ggml_context * ctx_split = ctx_for_layer_split(i);
  7631. auto & layer = model.layers[i];
  7632. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7633. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7634. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7635. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7636. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7637. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7638. 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));
  7639. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7640. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7641. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7642. }
  7643. } break;
  7644. case LLM_ARCH_RWKV6:
  7645. {
  7646. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7647. // Block 0, LN0
  7648. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  7649. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  7650. // output
  7651. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7652. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7653. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7654. const int time_mix_extra_dim = hparams.time_mix_extra_dim;
  7655. const int time_decay_extra_dim = hparams.time_decay_extra_dim;
  7656. const int head_size = hparams.wkv_head_size;
  7657. const int attn_hidden_size = n_embd;
  7658. const int ffn_size = hparams.n_ff_arr[0];
  7659. for (int i = 0; i < n_layer; ++i) {
  7660. ggml_context * ctx_layer = ctx_for_layer(i);
  7661. auto & layer = model.layers[i];
  7662. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7663. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7664. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  7665. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  7666. layer.time_mix_w1 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W1, "weight", i), {n_embd, time_mix_extra_dim * 5});
  7667. layer.time_mix_w2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_W2, "weight", i), {time_mix_extra_dim, n_embd, 5});
  7668. layer.time_mix_lerp_x = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_X, "weight", i), {n_embd, 1, 1});
  7669. layer.time_mix_lerp_w = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_W, "weight", i), {n_embd, 1, 1});
  7670. layer.time_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7671. layer.time_mix_lerp_v = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_V, "weight", i), {n_embd, 1, 1});
  7672. layer.time_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7673. layer.time_mix_lerp_g = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LERP_G, "weight", i), {n_embd, 1, 1});
  7674. layer.time_mix_first = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size});
  7675. layer.time_mix_decay = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd});
  7676. 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});
  7677. 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});
  7678. layer.time_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_KEY, "weight", i), {attn_hidden_size, n_embd});
  7679. layer.time_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_VALUE, "weight", i), {attn_hidden_size, n_embd});
  7680. layer.time_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_RECEPTANCE, "weight", i), {attn_hidden_size, n_embd});
  7681. layer.time_mix_gate = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_GATE, "weight", i), {attn_hidden_size, n_embd});
  7682. layer.time_mix_ln = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "weight", i), {n_embd});
  7683. layer.time_mix_ln_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_LN, "bias", i), {n_embd});
  7684. layer.time_mix_output = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_TIME_MIX_OUTPUT, "weight", i), {n_embd, attn_hidden_size});
  7685. layer.channel_mix_lerp_k = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_K, "weight", i), {n_embd, 1, 1});
  7686. layer.channel_mix_lerp_r = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_LERP_R, "weight", i), {n_embd, 1, 1});
  7687. layer.channel_mix_key = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_KEY, "weight", i), {n_embd, ffn_size});
  7688. layer.channel_mix_value = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_VALUE, "weight", i), {ffn_size, n_embd});
  7689. layer.channel_mix_receptance = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_CHANNEL_MIX_RECEPTANCE, "weight", i), {n_embd, n_embd});
  7690. }
  7691. } break;
  7692. case LLM_ARCH_CHAMELEON:
  7693. {
  7694. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7695. // output
  7696. {
  7697. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7698. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7699. // if output is NULL, init from the input tok embed
  7700. if (model.output == NULL) {
  7701. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  7702. }
  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_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  7710. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  7711. 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);
  7712. 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);
  7713. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7714. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7715. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7716. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7717. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", 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_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7720. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7721. }
  7722. } break;
  7723. default:
  7724. throw std::runtime_error("unknown architecture");
  7725. }
  7726. }
  7727. ml.done_getting_tensors();
  7728. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  7729. model.mappings.reserve(ml.mappings.size());
  7730. // create the backend buffers
  7731. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  7732. ctx_bufs.reserve(ctx_map.size());
  7733. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  7734. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  7735. model.bufs.reserve(n_max_backend_buffer);
  7736. for (auto & it : ctx_map) {
  7737. ggml_backend_buffer_type_t buft = it.first;
  7738. ggml_context * ctx = it.second;
  7739. llama_buf_map bufs;
  7740. bufs.reserve(n_max_backend_buffer);
  7741. // check if this backend device supports buffer_from_host_ptr
  7742. // when using a host buffer as the CPU bakcend buffer, use the CPU device to prioritize using buffer_from_host_ptr over the host buffer
  7743. ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft == llama_default_buffer_type_cpu(model, true) ? ggml_backend_cpu_buffer_type() : buft);
  7744. bool buffer_from_host_ptr_supported = false;
  7745. if (dev) {
  7746. ggml_backend_dev_props props;
  7747. ggml_backend_dev_get_props(dev, &props);
  7748. buffer_from_host_ptr_supported = props.caps.buffer_from_host_ptr;
  7749. }
  7750. if (ml.use_mmap && use_mmap_buffer && buffer_from_host_ptr_supported) {
  7751. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7752. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  7753. // 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
  7754. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  7755. void * addr = nullptr;
  7756. size_t first, last; // NOLINT
  7757. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7758. if (first >= last) {
  7759. continue;
  7760. }
  7761. const size_t max_size = ggml_get_max_tensor_size(ctx);
  7762. ggml_backend_buffer_t buf = ggml_backend_dev_buffer_from_host_ptr(dev, (char *) addr + first, last - first, max_size);
  7763. if (buf == nullptr) {
  7764. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  7765. }
  7766. model.bufs.push_back(buf);
  7767. bufs.emplace(idx, buf);
  7768. }
  7769. }
  7770. else {
  7771. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  7772. if (buf == nullptr) {
  7773. throw std::runtime_error(format("unable to allocate %s buffer", ggml_backend_buft_name(buft)));
  7774. }
  7775. model.bufs.push_back(buf);
  7776. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  7777. model.mlock_bufs.emplace_back(new llama_mlock);
  7778. auto & mlock_buf = model.mlock_bufs.back();
  7779. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  7780. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  7781. }
  7782. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7783. bufs.emplace(idx, buf);
  7784. }
  7785. }
  7786. if (bufs.empty()) {
  7787. throw std::runtime_error("failed to allocate buffer");
  7788. }
  7789. for (auto & buf : bufs) {
  7790. // indicate that this buffer contains weights
  7791. // 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
  7792. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  7793. }
  7794. ctx_bufs.emplace_back(ctx, bufs);
  7795. }
  7796. if (llama_supports_gpu_offload()) {
  7797. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  7798. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  7799. if (n_gpu_layers > (int) hparams.n_layer) {
  7800. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  7801. }
  7802. const int max_backend_supported_layers = hparams.n_layer + 1;
  7803. const int max_offloadable_layers = hparams.n_layer + 1;
  7804. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  7805. }
  7806. // print memory requirements
  7807. for (ggml_backend_buffer_t buf : model.bufs) {
  7808. 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);
  7809. }
  7810. // populate tensors_by_name
  7811. for (ggml_context * ctx : model.ctxs) {
  7812. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  7813. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  7814. }
  7815. }
  7816. // load tensor data
  7817. for (auto & it : ctx_bufs) {
  7818. ggml_context * ctx = it.first;
  7819. auto & bufs = it.second;
  7820. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  7821. return false;
  7822. }
  7823. }
  7824. if (use_mmap_buffer) {
  7825. for (auto & mapping : ml.mappings) {
  7826. model.mappings.emplace_back(std::move(mapping));
  7827. }
  7828. }
  7829. return true;
  7830. }
  7831. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  7832. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  7833. model.t_start_us = ggml_time_us();
  7834. try {
  7835. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  7836. model.hparams.vocab_only = params.vocab_only;
  7837. try {
  7838. llm_load_arch(ml, model);
  7839. } catch(const std::exception & e) {
  7840. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  7841. }
  7842. try {
  7843. llm_load_hparams(ml, model);
  7844. } catch(const std::exception & e) {
  7845. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  7846. }
  7847. try {
  7848. llm_load_vocab(ml, model);
  7849. } catch(const std::exception & e) {
  7850. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  7851. }
  7852. llm_load_print_meta(ml, model);
  7853. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  7854. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  7855. throw std::runtime_error("vocab size mismatch");
  7856. }
  7857. if (params.vocab_only) {
  7858. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  7859. return 0;
  7860. }
  7861. #ifdef GGML_USE_KOMPUTE
  7862. if (params.n_gpu_layers > 0 && (
  7863. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  7864. || !(
  7865. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  7866. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  7867. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  7868. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  7869. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  7870. )
  7871. )) {
  7872. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  7873. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  7874. params.n_gpu_layers = 0;
  7875. }
  7876. #endif
  7877. if (!llm_load_tensors(
  7878. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  7879. params.progress_callback, params.progress_callback_user_data
  7880. )) {
  7881. return -2;
  7882. }
  7883. } catch (const std::exception & err) {
  7884. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  7885. return -1;
  7886. }
  7887. // loading time will be recalculate after the first eval, so
  7888. // we take page faults deferred by mmap() into consideration
  7889. model.t_load_us = ggml_time_us() - model.t_start_us;
  7890. return 0;
  7891. }
  7892. //
  7893. // llm_build
  7894. //
  7895. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  7896. enum llm_ffn_op_type {
  7897. LLM_FFN_SILU,
  7898. LLM_FFN_GELU,
  7899. LLM_FFN_RELU,
  7900. LLM_FFN_RELU_SQR,
  7901. LLM_FFN_SWIGLU,
  7902. };
  7903. enum llm_ffn_gate_type {
  7904. LLM_FFN_SEQ,
  7905. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  7906. };
  7907. enum llm_norm_type {
  7908. LLM_NORM,
  7909. LLM_NORM_RMS,
  7910. };
  7911. static struct ggml_tensor * llm_build_inp_embd(
  7912. struct ggml_context * ctx,
  7913. struct llama_context & lctx,
  7914. const llama_hparams & hparams,
  7915. const llama_ubatch & batch,
  7916. struct ggml_tensor * tok_embd,
  7917. const llm_build_cb & cb) {
  7918. const int64_t n_embd = hparams.n_embd;
  7919. struct ggml_tensor * inpL;
  7920. if (batch.token) {
  7921. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  7922. cb(lctx.inp_tokens, "inp_tokens", -1);
  7923. ggml_set_input(lctx.inp_tokens);
  7924. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  7925. } else {
  7926. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  7927. inpL = lctx.inp_embd;
  7928. ggml_set_input(lctx.inp_embd);
  7929. }
  7930. // For Granite architecture
  7931. if (hparams.f_embedding_scale != 0.0f) {
  7932. inpL = ggml_scale(ctx, inpL, hparams.f_embedding_scale);
  7933. }
  7934. cb(inpL, "inp_embd", -1);
  7935. return inpL;
  7936. }
  7937. static void llm_build_kv_store(
  7938. struct ggml_context * ctx,
  7939. const llama_hparams & hparams,
  7940. const llama_cparams & cparams,
  7941. const llama_kv_cache & kv,
  7942. struct ggml_cgraph * graph,
  7943. struct ggml_tensor * k_cur,
  7944. struct ggml_tensor * v_cur,
  7945. int32_t n_tokens,
  7946. int32_t kv_head,
  7947. const llm_build_cb & cb,
  7948. int64_t il) {
  7949. const int64_t n_ctx = cparams.n_ctx;
  7950. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7951. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7952. GGML_ASSERT(kv.size == n_ctx);
  7953. 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);
  7954. cb(k_cache_view, "k_cache_view", il);
  7955. // note: storing RoPE-ed version of K in the KV cache
  7956. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  7957. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  7958. struct ggml_tensor * v_cache_view = nullptr;
  7959. if (cparams.flash_attn) {
  7960. 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);
  7961. } else {
  7962. // note: the V cache is transposed when not using flash attention
  7963. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  7964. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  7965. (kv_head)*ggml_element_size(kv.v_l[il]));
  7966. v_cur = ggml_transpose(ctx, v_cur);
  7967. }
  7968. cb(v_cache_view, "v_cache_view", il);
  7969. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  7970. }
  7971. // do mat_mul, while optionally apply lora
  7972. static struct ggml_tensor * llm_build_lora_mm(
  7973. struct llama_context & lctx,
  7974. struct ggml_context * ctx0,
  7975. struct ggml_tensor * w,
  7976. struct ggml_tensor * cur) {
  7977. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  7978. for (auto & it : lctx.lora_adapters) {
  7979. struct llama_lora_weight * lora = it.first->get_weight(w);
  7980. if (lora == nullptr) {
  7981. continue;
  7982. }
  7983. const float alpha = it.first->alpha;
  7984. const float rank = (float) lora->b->ne[0];
  7985. const float scale = alpha ? it.second * alpha / rank : it.second;
  7986. struct ggml_tensor * ab_cur = ggml_mul_mat(
  7987. ctx0, lora->b,
  7988. ggml_mul_mat(ctx0, lora->a, cur)
  7989. );
  7990. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  7991. res = ggml_add(ctx0, res, ab_cur);
  7992. }
  7993. return res;
  7994. }
  7995. // do mat_mul_id, while optionally apply lora
  7996. static struct ggml_tensor * llm_build_lora_mm_id(
  7997. struct llama_context & lctx,
  7998. struct ggml_context * ctx0,
  7999. struct ggml_tensor * w, // struct ggml_tensor * as
  8000. struct ggml_tensor * cur, // struct ggml_tensor * b
  8001. struct ggml_tensor * ids) {
  8002. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  8003. for (auto & it : lctx.lora_adapters) {
  8004. struct llama_lora_weight * lora = it.first->get_weight(w);
  8005. if (lora == nullptr) {
  8006. continue;
  8007. }
  8008. const float alpha = it.first->alpha;
  8009. const float rank = (float) lora->b->ne[0];
  8010. const float scale = alpha ? it.second * alpha / rank : it.second;
  8011. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  8012. ctx0, lora->b,
  8013. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  8014. ids
  8015. );
  8016. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  8017. res = ggml_add(ctx0, res, ab_cur);
  8018. }
  8019. return res;
  8020. }
  8021. static struct ggml_tensor * llm_build_norm(
  8022. struct ggml_context * ctx,
  8023. struct ggml_tensor * cur,
  8024. const llama_hparams & hparams,
  8025. struct ggml_tensor * mw,
  8026. struct ggml_tensor * mb,
  8027. llm_norm_type type,
  8028. const llm_build_cb & cb,
  8029. int il) {
  8030. switch (type) {
  8031. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  8032. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  8033. }
  8034. if (mw || mb) {
  8035. cb(cur, "norm", il);
  8036. }
  8037. if (mw) {
  8038. cur = ggml_mul(ctx, cur, mw);
  8039. if (mb) {
  8040. cb(cur, "norm_w", il);
  8041. }
  8042. }
  8043. if (mb) {
  8044. cur = ggml_add(ctx, cur, mb);
  8045. }
  8046. return cur;
  8047. }
  8048. static struct ggml_tensor * llm_build_ffn(
  8049. struct ggml_context * ctx,
  8050. struct llama_context & lctx,
  8051. struct ggml_tensor * cur,
  8052. struct ggml_tensor * up,
  8053. struct ggml_tensor * up_b,
  8054. struct ggml_tensor * up_s,
  8055. struct ggml_tensor * gate,
  8056. struct ggml_tensor * gate_b,
  8057. struct ggml_tensor * gate_s,
  8058. struct ggml_tensor * down,
  8059. struct ggml_tensor * down_b,
  8060. struct ggml_tensor * down_s,
  8061. struct ggml_tensor * act_scales,
  8062. llm_ffn_op_type type_op,
  8063. llm_ffn_gate_type type_gate,
  8064. const llm_build_cb & cb,
  8065. int il) {
  8066. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  8067. cb(tmp, "ffn_up", il);
  8068. if (up_b) {
  8069. tmp = ggml_add(ctx, tmp, up_b);
  8070. cb(tmp, "ffn_up_b", il);
  8071. }
  8072. if (up_s) {
  8073. tmp = ggml_mul(ctx, tmp, up_s);
  8074. cb(tmp, "ffn_up_s", il);
  8075. }
  8076. if (gate) {
  8077. switch (type_gate) {
  8078. case LLM_FFN_SEQ:
  8079. {
  8080. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  8081. cb(cur, "ffn_gate", il);
  8082. } break;
  8083. case LLM_FFN_PAR:
  8084. {
  8085. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  8086. cb(cur, "ffn_gate", il);
  8087. } break;
  8088. }
  8089. if (gate_b) {
  8090. cur = ggml_add(ctx, cur, gate_b);
  8091. cb(cur, "ffn_gate_b", il);
  8092. }
  8093. if (gate_s) {
  8094. cur = ggml_mul(ctx, cur, gate_s);
  8095. cb(cur, "ffn_gate_s", il);
  8096. }
  8097. } else {
  8098. cur = tmp;
  8099. }
  8100. switch (type_op) {
  8101. case LLM_FFN_SILU:
  8102. {
  8103. cur = ggml_silu(ctx, cur);
  8104. cb(cur, "ffn_silu", il);
  8105. } break;
  8106. case LLM_FFN_GELU:
  8107. {
  8108. cur = ggml_gelu(ctx, cur);
  8109. cb(cur, "ffn_gelu", il);
  8110. if (act_scales != NULL) {
  8111. cur = ggml_div(ctx, cur, act_scales);
  8112. cb(cur, "ffn_act", il);
  8113. }
  8114. } break;
  8115. case LLM_FFN_RELU:
  8116. {
  8117. cur = ggml_relu(ctx, cur);
  8118. cb(cur, "ffn_relu", il);
  8119. } break;
  8120. case LLM_FFN_RELU_SQR:
  8121. {
  8122. cur = ggml_relu(ctx, cur);
  8123. cb(cur, "ffn_relu", il);
  8124. cur = ggml_sqr(ctx, cur);
  8125. cb(cur, "ffn_sqr(relu)", il);
  8126. } break;
  8127. case LLM_FFN_SWIGLU:
  8128. {
  8129. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  8130. int64_t split_point = cur->ne[0] / 2;
  8131. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  8132. 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)));
  8133. x0 = ggml_silu(ctx, x0);
  8134. cb(cur, "ffn_silu", il);
  8135. cur = ggml_mul(ctx, x0, x1);
  8136. cb(cur, "ffn_mul", il);
  8137. } break;
  8138. }
  8139. if (type_gate == LLM_FFN_PAR) {
  8140. cur = ggml_mul(ctx, cur, tmp);
  8141. cb(cur, "ffn_gate_par", il);
  8142. }
  8143. if (down) {
  8144. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  8145. }
  8146. if (down_b) {
  8147. cb(cur, "ffn_down", il);
  8148. }
  8149. if (down_b) {
  8150. cur = ggml_add(ctx, cur, down_b);
  8151. }
  8152. if (down_s) {
  8153. cur = ggml_mul(ctx, cur, down_s);
  8154. cb(cur, "ffn_down_s", il);
  8155. }
  8156. return cur;
  8157. }
  8158. static struct ggml_tensor * llm_build_moe_ffn(
  8159. struct ggml_context * ctx,
  8160. struct llama_context & lctx,
  8161. struct ggml_tensor * cur,
  8162. struct ggml_tensor * gate_inp,
  8163. struct ggml_tensor * up_exps,
  8164. struct ggml_tensor * gate_exps,
  8165. struct ggml_tensor * down_exps,
  8166. int64_t n_expert,
  8167. int64_t n_expert_used,
  8168. llm_ffn_op_type type_op,
  8169. bool norm_w,
  8170. bool scale_w,
  8171. float w_scale,
  8172. const llm_build_cb & cb,
  8173. int il) {
  8174. int64_t n_embd = cur->ne[0];
  8175. int64_t n_tokens = cur->ne[1];
  8176. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  8177. cb(logits, "ffn_moe_logits", il);
  8178. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  8179. cb(probs, "ffn_moe_probs", il);
  8180. // select experts
  8181. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  8182. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  8183. cb(selected_experts, "ffn_moe_topk", il);
  8184. ggml_tensor * weights = ggml_get_rows(ctx,
  8185. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  8186. cb(weights, "ffn_moe_weights", il);
  8187. if (norm_w) {
  8188. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  8189. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  8190. cb(weights_sum, "ffn_moe_weights_sum", il);
  8191. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  8192. cb(weights, "ffn_moe_weights_norm", il);
  8193. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  8194. }
  8195. if (scale_w) {
  8196. weights = ggml_scale(ctx, weights, w_scale);
  8197. cb(weights, "ffn_moe_weights_scaled", il);
  8198. }
  8199. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  8200. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8201. cb(up, "ffn_moe_up", il);
  8202. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  8203. cb(gate, "ffn_moe_gate", il);
  8204. switch (type_op) {
  8205. case LLM_FFN_SILU:
  8206. {
  8207. gate = ggml_silu(ctx, gate);
  8208. cb(gate, "ffn_moe_silu", il);
  8209. } break;
  8210. case LLM_FFN_GELU:
  8211. {
  8212. gate = ggml_gelu(ctx, gate);
  8213. cb(gate, "ffn_moe_gelu", il);
  8214. } break;
  8215. default:
  8216. GGML_ABORT("fatal error");
  8217. }
  8218. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  8219. cb(par, "ffn_moe_gate_par", il);
  8220. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  8221. cb(experts, "ffn_moe_down", il);
  8222. experts = ggml_mul(ctx, experts, weights);
  8223. // aggregate experts
  8224. ggml_tensor * moe_out = nullptr;
  8225. for (int i = 0; i < n_expert_used; ++i) {
  8226. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  8227. experts->nb[2], i*experts->nb[1]);
  8228. if (i == 0) {
  8229. moe_out = cur_expert;
  8230. } else {
  8231. moe_out = ggml_add(ctx, moe_out, cur_expert);
  8232. }
  8233. }
  8234. if (n_expert_used == 1) {
  8235. // avoid returning a non-contiguous tensor
  8236. moe_out = ggml_cont(ctx, moe_out);
  8237. }
  8238. return moe_out;
  8239. }
  8240. static struct ggml_tensor * llm_build_kqv(
  8241. struct ggml_context * ctx,
  8242. struct llama_context & lctx,
  8243. const llama_kv_cache & kv,
  8244. struct ggml_cgraph * graph,
  8245. struct ggml_tensor * wo,
  8246. struct ggml_tensor * wo_b,
  8247. struct ggml_tensor * q_cur,
  8248. struct ggml_tensor * kq_mask,
  8249. int32_t n_tokens,
  8250. int32_t n_kv,
  8251. float kq_scale,
  8252. const llm_build_cb & cb,
  8253. int il) {
  8254. const llama_model & model = lctx.model;
  8255. const llama_hparams & hparams = lctx.model.hparams;
  8256. const llama_cparams & cparams = lctx.cparams;
  8257. const int64_t n_ctx = cparams.n_ctx;
  8258. const int64_t n_head = hparams.n_head(il);
  8259. const int64_t n_head_kv = hparams.n_head_kv(il);
  8260. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8261. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8262. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  8263. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8264. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  8265. cb(q, "q", il);
  8266. struct ggml_tensor * k =
  8267. ggml_view_3d(ctx, kv.k_l[il],
  8268. n_embd_head_k, n_kv, n_head_kv,
  8269. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  8270. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  8271. 0);
  8272. cb(k, "k", il);
  8273. struct ggml_tensor * cur;
  8274. if (cparams.flash_attn) {
  8275. GGML_UNUSED(model);
  8276. GGML_UNUSED(n_ctx);
  8277. // split cached v into n_head heads (not transposed)
  8278. struct ggml_tensor * v =
  8279. ggml_view_3d(ctx, kv.v_l[il],
  8280. n_embd_head_v, n_kv, n_head_kv,
  8281. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  8282. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  8283. 0);
  8284. cb(v, "v", il);
  8285. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  8286. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  8287. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_GEMMA2) {
  8288. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  8289. }
  8290. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  8291. } else {
  8292. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  8293. cb(kq, "kq", il);
  8294. 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) {
  8295. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  8296. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  8297. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8298. }
  8299. if (model.arch == LLM_ARCH_GROK) {
  8300. // need to do the following:
  8301. // multiply by attn_output_multiplyer of 0.08838834764831845
  8302. // and then :
  8303. // kq = 30 * tanh(kq / 30)
  8304. // before the softmax below
  8305. //try from phi2
  8306. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  8307. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  8308. kq = ggml_scale(ctx, kq, 30);
  8309. }
  8310. if (hparams.attn_soft_cap) {
  8311. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  8312. kq = ggml_tanh(ctx, kq);
  8313. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  8314. }
  8315. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  8316. cb(kq, "kq_soft_max_ext", il);
  8317. GGML_ASSERT(kv.size == n_ctx);
  8318. // split cached v into n_head heads
  8319. struct ggml_tensor * v =
  8320. ggml_view_3d(ctx, kv.v_l[il],
  8321. n_kv, n_embd_head_v, n_head_kv,
  8322. ggml_element_size(kv.v_l[il])*n_ctx,
  8323. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  8324. 0);
  8325. cb(v, "v", il);
  8326. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  8327. cb(kqv, "kqv", il);
  8328. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  8329. cb(kqv_merged, "kqv_merged", il);
  8330. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  8331. cb(cur, "kqv_merged_cont", il);
  8332. }
  8333. ggml_build_forward_expand(graph, cur);
  8334. if (wo) {
  8335. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  8336. }
  8337. if (wo_b) {
  8338. cb(cur, "kqv_wo", il);
  8339. }
  8340. if (wo_b) {
  8341. cur = ggml_add(ctx, cur, wo_b);
  8342. }
  8343. return cur;
  8344. }
  8345. static struct ggml_tensor * llm_build_kv(
  8346. struct ggml_context * ctx,
  8347. struct llama_context & lctx,
  8348. const llama_kv_cache & kv,
  8349. struct ggml_cgraph * graph,
  8350. struct ggml_tensor * wo,
  8351. struct ggml_tensor * wo_b,
  8352. struct ggml_tensor * k_cur,
  8353. struct ggml_tensor * v_cur,
  8354. struct ggml_tensor * q_cur,
  8355. struct ggml_tensor * kq_mask,
  8356. int32_t n_tokens,
  8357. int32_t kv_head,
  8358. int32_t n_kv,
  8359. float kq_scale,
  8360. const llm_build_cb & cb,
  8361. int il) {
  8362. const llama_hparams & hparams = lctx.model.hparams;
  8363. const llama_cparams & cparams = lctx.cparams;
  8364. // these nodes are added to the graph together so that they are not reordered
  8365. // by doing so, the number of splits in the graph is reduced
  8366. ggml_build_forward_expand(graph, q_cur);
  8367. ggml_build_forward_expand(graph, k_cur);
  8368. ggml_build_forward_expand(graph, v_cur);
  8369. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  8370. struct ggml_tensor * cur;
  8371. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b, q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  8372. cb(cur, "kqv_out", il);
  8373. return cur;
  8374. }
  8375. static struct ggml_tensor * llm_build_copy_mask_state(
  8376. struct ggml_context * ctx,
  8377. struct ggml_cgraph * graph,
  8378. struct ggml_tensor * s,
  8379. struct ggml_tensor * state_copy,
  8380. struct ggml_tensor * state_mask,
  8381. int32_t n_state,
  8382. int32_t kv_size,
  8383. int32_t kv_head,
  8384. int32_t n_kv,
  8385. int32_t n_seqs) {
  8386. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  8387. // copy states
  8388. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  8389. // this shrinks the tensors's ne[1] to n_kv
  8390. states = ggml_get_rows(ctx, states, state_copy);
  8391. // clear states of sequences which are starting at the beginning of this batch
  8392. // FIXME: zero-out NANs?
  8393. states = ggml_mul(ctx, states, state_mask);
  8394. // copy states which won't be changed further (between n_seqs and n_kv)
  8395. ggml_build_forward_expand(graph,
  8396. ggml_cpy(ctx,
  8397. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  8398. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  8399. // the part of the states that will be used and modified
  8400. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  8401. }
  8402. // TODO: split
  8403. static struct ggml_tensor * llm_build_mamba(
  8404. struct ggml_context * ctx,
  8405. struct llama_context & lctx,
  8406. const llama_ubatch & batch,
  8407. struct ggml_cgraph * graph,
  8408. struct ggml_tensor * cur,
  8409. struct ggml_tensor * state_copy,
  8410. struct ggml_tensor * state_mask,
  8411. int32_t kv_head,
  8412. int32_t n_kv,
  8413. const llm_build_cb & cb,
  8414. int il) {
  8415. const llama_model & model = lctx.model;
  8416. const llama_hparams & hparams = model.hparams;
  8417. const llama_kv_cache & kv = lctx.kv_self;
  8418. const int64_t d_conv = hparams.ssm_d_conv;
  8419. const int64_t d_inner = hparams.ssm_d_inner;
  8420. const int64_t d_state = hparams.ssm_d_state;
  8421. const int64_t dt_rank = hparams.ssm_dt_rank;
  8422. const int64_t n_seqs = batch.n_seqs;
  8423. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  8424. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  8425. // Use the same RMS norm as the final layer norm
  8426. const float norm_rms_eps = hparams.f_norm_rms_eps;
  8427. const int64_t n_seq_tokens = batch.n_seq_tokens;
  8428. GGML_ASSERT(n_seqs != 0);
  8429. GGML_ASSERT(batch.equal_seqs);
  8430. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  8431. struct ggml_tensor * conv_states_all = kv.k_l[il];
  8432. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  8433. // (ab)using the KV cache to store the states
  8434. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  8435. graph, conv_states_all, state_copy, state_mask,
  8436. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  8437. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  8438. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  8439. graph, ssm_states_all, state_copy, state_mask,
  8440. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  8441. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  8442. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  8443. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  8444. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  8445. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  8446. // split the above in two
  8447. // => {d_inner, n_seq_tokens, n_seqs}
  8448. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  8449. 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));
  8450. // conv
  8451. {
  8452. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  8453. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  8454. // copy last (d_conv - 1) columns back into the state cache
  8455. 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]));
  8456. ggml_build_forward_expand(graph,
  8457. ggml_cpy(ctx, last_conv,
  8458. ggml_view_1d(ctx, conv_states_all,
  8459. (d_conv - 1)*(d_inner)*(n_seqs),
  8460. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  8461. // 1D convolution
  8462. // The equivalent is to make a self-overlapping view of conv_x
  8463. // over d_conv columns at each stride in the 3rd dimension,
  8464. // then element-wise multiply that with the conv1d weight,
  8465. // then sum the elements of each row,
  8466. // (the last two steps are a dot product over rows (also doable with mul_mat))
  8467. // then permute away the ne[0] dimension,
  8468. // and then you're left with the resulting x tensor.
  8469. // For simultaneous sequences, all sequences need to have the same length.
  8470. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  8471. // bias
  8472. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  8473. x = ggml_silu(ctx, x);
  8474. }
  8475. // ssm
  8476. {
  8477. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  8478. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  8479. // split
  8480. 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);
  8481. 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);
  8482. 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));
  8483. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  8484. if (ssm_dt_b_c_rms) {
  8485. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  8486. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  8487. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  8488. }
  8489. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  8490. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  8491. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  8492. // Custom operator to optimize the parallel associative scan
  8493. // as described in the Annex D of the Mamba paper.
  8494. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  8495. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  8496. // store last states
  8497. ggml_build_forward_expand(graph,
  8498. ggml_cpy(ctx,
  8499. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  8500. 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))));
  8501. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  8502. // TODO: skip computing output earlier for unused tokens
  8503. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  8504. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  8505. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  8506. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  8507. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  8508. }
  8509. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  8510. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  8511. cb(cur, "mamba_out", il);
  8512. return cur;
  8513. }
  8514. static struct ggml_tensor * llm_build_rwkv6_time_mix(
  8515. struct llama_context & lctx,
  8516. struct ggml_context * ctx,
  8517. const struct llama_layer * layer,
  8518. struct ggml_tensor * cur,
  8519. struct ggml_tensor * x_prev,
  8520. struct ggml_tensor ** wkv_state) {
  8521. size_t n_embd = cur->ne[0];
  8522. size_t n_seq_tokens = cur->ne[1];
  8523. size_t n_seqs = cur->ne[2];
  8524. size_t head_size = layer->time_mix_first->ne[0];
  8525. size_t head_count = layer->time_mix_first->ne[1];
  8526. size_t n_tokens = n_seqs * n_seq_tokens;
  8527. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8528. sx = ggml_reshape_2d(ctx, sx, n_embd, n_tokens);
  8529. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8530. struct ggml_tensor * xxx = ggml_add(ctx, ggml_mul(ctx, sx, layer->time_mix_lerp_x), cur);
  8531. xxx = ggml_reshape_4d(
  8532. ctx,
  8533. ggml_tanh(
  8534. ctx,
  8535. ggml_mul_mat(ctx, layer->time_mix_w1, xxx)
  8536. ),
  8537. layer->time_mix_w1->ne[1] / 5, 1, 5, n_tokens
  8538. );
  8539. xxx = ggml_cont(ctx, ggml_permute(ctx, xxx, 0, 1, 3, 2));
  8540. xxx = ggml_mul_mat(
  8541. ctx,
  8542. ggml_reshape_4d(
  8543. ctx,
  8544. layer->time_mix_w2,
  8545. layer->time_mix_w2->ne[0], layer->time_mix_w2->ne[1], 1, 5
  8546. ),
  8547. xxx
  8548. );
  8549. struct ggml_tensor *mw = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], 0);
  8550. struct ggml_tensor *mk = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * sizeof(float));
  8551. struct ggml_tensor *mv = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 2 * sizeof(float));
  8552. struct ggml_tensor *mr = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 3 * sizeof(float));
  8553. struct ggml_tensor *mg = ggml_view_2d(ctx, xxx, n_embd, n_tokens, xxx->nb[1], n_embd * n_tokens * 4 * sizeof(float));
  8554. struct ggml_tensor * xw = ggml_add(
  8555. ctx,
  8556. ggml_mul(
  8557. ctx,
  8558. ggml_add(ctx, mw, layer->time_mix_lerp_w),
  8559. sx
  8560. ),
  8561. cur
  8562. );
  8563. struct ggml_tensor * xk = ggml_add(
  8564. ctx,
  8565. ggml_mul(
  8566. ctx,
  8567. ggml_add(ctx, mk, layer->time_mix_lerp_k),
  8568. sx
  8569. ),
  8570. cur
  8571. );
  8572. struct ggml_tensor * xv = ggml_add(
  8573. ctx,
  8574. ggml_mul(
  8575. ctx,
  8576. ggml_add(ctx, mv, layer->time_mix_lerp_v),
  8577. sx
  8578. ),
  8579. cur
  8580. );
  8581. struct ggml_tensor * xr = ggml_add(
  8582. ctx,
  8583. ggml_mul(
  8584. ctx,
  8585. ggml_add(ctx, mr, layer->time_mix_lerp_r),
  8586. sx
  8587. ),
  8588. cur
  8589. );
  8590. struct ggml_tensor * xg = ggml_add(
  8591. ctx,
  8592. ggml_mul(
  8593. ctx,
  8594. ggml_add(ctx, mg, layer->time_mix_lerp_g),
  8595. sx
  8596. ),
  8597. cur
  8598. );
  8599. 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);
  8600. 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);
  8601. 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);
  8602. struct ggml_tensor * g = ggml_silu(
  8603. ctx,
  8604. llm_build_lora_mm(lctx, ctx, layer->time_mix_gate, xg)
  8605. );
  8606. struct ggml_tensor * w = ggml_mul_mat(
  8607. ctx,
  8608. layer->time_mix_decay_w2,
  8609. ggml_tanh(
  8610. ctx,
  8611. ggml_mul_mat(ctx, layer->time_mix_decay_w1, xw)
  8612. )
  8613. );
  8614. w = ggml_add(ctx, w, ggml_reshape_1d(ctx, layer->time_mix_decay, n_embd));
  8615. w = ggml_exp(ctx, ggml_neg(ctx, ggml_exp(ctx, w)));
  8616. w = ggml_reshape_4d(ctx, w, 1, head_size, head_count, n_tokens);
  8617. k = ggml_transpose(ctx, k);
  8618. v = ggml_transpose(ctx, v);
  8619. r = ggml_transpose(ctx, r);
  8620. struct ggml_tensor * wkv_output = ggml_rwkv_wkv(ctx, k, v, r, layer->time_mix_first, w, *wkv_state);
  8621. cur = ggml_view_1d(ctx, wkv_output, n_embd * n_tokens, 0);
  8622. *wkv_state = ggml_view_1d(ctx, wkv_output, n_embd * head_size * n_seqs, n_embd * n_tokens * sizeof(float));
  8623. // group norm with head_count groups
  8624. cur = ggml_reshape_3d(ctx, cur, n_embd / head_count, head_count, n_tokens);
  8625. cur = ggml_norm(ctx, cur, 64e-5f);
  8626. // Convert back to regular vectors.
  8627. cur = ggml_reshape_2d(ctx, cur, n_embd, n_tokens);
  8628. cur = ggml_add(ctx, ggml_mul(ctx, cur, layer->time_mix_ln), layer->time_mix_ln_b);
  8629. cur = ggml_mul(ctx, cur, g);
  8630. cur = llm_build_lora_mm(lctx, ctx, layer->time_mix_output, cur);
  8631. return ggml_reshape_3d(ctx, cur, n_embd, n_seq_tokens, n_seqs);
  8632. }
  8633. static struct ggml_tensor * llm_build_rwkv6_channel_mix(
  8634. struct llama_context & lctx,
  8635. struct ggml_context * ctx,
  8636. const struct llama_layer * layer,
  8637. struct ggml_tensor * cur,
  8638. struct ggml_tensor * x_prev) {
  8639. struct ggml_tensor * sx = ggml_sub(ctx, x_prev, cur);
  8640. struct ggml_tensor * xk = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_k), cur);
  8641. struct ggml_tensor * xr = ggml_add(ctx, ggml_mul(ctx, sx, layer->channel_mix_lerp_r), cur);
  8642. struct ggml_tensor * r = ggml_sigmoid(ctx, llm_build_lora_mm(lctx, ctx, layer->channel_mix_receptance, xr));
  8643. struct ggml_tensor * k = ggml_sqr(
  8644. ctx,
  8645. ggml_relu(
  8646. ctx,
  8647. llm_build_lora_mm(lctx, ctx, layer->channel_mix_key, xk)
  8648. )
  8649. );
  8650. return ggml_mul(ctx, r, llm_build_lora_mm(lctx, ctx, layer->channel_mix_value, k));
  8651. }
  8652. struct llm_build_context {
  8653. const llama_model & model;
  8654. llama_context & lctx;
  8655. const llama_hparams & hparams;
  8656. const llama_cparams & cparams;
  8657. const llama_ubatch & batch;
  8658. const llama_kv_cache & kv_self;
  8659. const int64_t n_embd;
  8660. const int64_t n_layer;
  8661. const int64_t n_rot;
  8662. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  8663. const int64_t n_head;
  8664. const int64_t n_head_kv;
  8665. const int64_t n_embd_head_k;
  8666. const int64_t n_embd_k_gqa;
  8667. const int64_t n_embd_head_v;
  8668. const int64_t n_embd_v_gqa;
  8669. const int64_t n_expert;
  8670. const int64_t n_expert_used;
  8671. const float freq_base;
  8672. const float freq_scale;
  8673. const float ext_factor;
  8674. const float attn_factor;
  8675. const float beta_fast;
  8676. const float beta_slow;
  8677. const float norm_eps;
  8678. const float norm_rms_eps;
  8679. const int32_t n_tokens;
  8680. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  8681. const int32_t n_outputs;
  8682. const int32_t n_outputs_enc;
  8683. const int32_t kv_head; // index of where we store new KV data in the cache
  8684. const int32_t n_ctx_orig;
  8685. const bool flash_attn;
  8686. const enum llama_pooling_type pooling_type;
  8687. const enum llama_rope_type rope_type;
  8688. const llm_build_cb & cb;
  8689. std::vector<uint8_t> & buf_compute_meta;
  8690. struct ggml_context * ctx0 = nullptr;
  8691. // TODO: consider making the entire interface noexcept
  8692. llm_build_context(
  8693. llama_context & lctx,
  8694. const llama_ubatch & batch,
  8695. const llm_build_cb & cb,
  8696. bool worst_case) :
  8697. model (lctx.model),
  8698. lctx (lctx),
  8699. hparams (model.hparams),
  8700. cparams (lctx.cparams),
  8701. batch (batch),
  8702. kv_self (lctx.kv_self),
  8703. n_embd (hparams.n_embd),
  8704. n_layer (hparams.n_layer),
  8705. n_rot (hparams.n_rot),
  8706. n_ctx (cparams.n_ctx),
  8707. n_head (hparams.n_head()),
  8708. n_head_kv (hparams.n_head_kv()),
  8709. n_embd_head_k (hparams.n_embd_head_k),
  8710. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  8711. n_embd_head_v (hparams.n_embd_head_v),
  8712. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  8713. n_expert (hparams.n_expert),
  8714. n_expert_used (hparams.n_expert_used),
  8715. freq_base (cparams.rope_freq_base),
  8716. freq_scale (cparams.rope_freq_scale),
  8717. ext_factor (cparams.yarn_ext_factor),
  8718. attn_factor (cparams.yarn_attn_factor),
  8719. beta_fast (cparams.yarn_beta_fast),
  8720. beta_slow (cparams.yarn_beta_slow),
  8721. norm_eps (hparams.f_norm_eps),
  8722. norm_rms_eps (hparams.f_norm_rms_eps),
  8723. n_tokens (batch.n_tokens),
  8724. n_kv (worst_case ? kv_self.size : kv_self.n),
  8725. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  8726. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  8727. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  8728. n_ctx_orig (cparams.n_ctx_orig_yarn),
  8729. flash_attn (cparams.flash_attn),
  8730. pooling_type (cparams.pooling_type),
  8731. rope_type (hparams.rope_type),
  8732. cb (cb),
  8733. buf_compute_meta (lctx.buf_compute_meta) {
  8734. // all initializations should be done in init()
  8735. }
  8736. void init() {
  8737. struct ggml_init_params params = {
  8738. /*.mem_size =*/ buf_compute_meta.size(),
  8739. /*.mem_buffer =*/ buf_compute_meta.data(),
  8740. /*.no_alloc =*/ true,
  8741. };
  8742. ctx0 = ggml_init(params);
  8743. lctx.inp_tokens = nullptr;
  8744. lctx.inp_embd = nullptr;
  8745. lctx.inp_pos = nullptr;
  8746. lctx.inp_out_ids = nullptr;
  8747. lctx.inp_KQ_mask = nullptr;
  8748. lctx.inp_KQ_mask_swa = nullptr;
  8749. lctx.inp_K_shift = nullptr;
  8750. lctx.inp_mean = nullptr;
  8751. lctx.inp_cls = nullptr;
  8752. lctx.inp_s_copy = nullptr;
  8753. lctx.inp_s_mask = nullptr;
  8754. lctx.inp_s_seq = nullptr;
  8755. lctx.inp_pos_bucket = nullptr;
  8756. lctx.inp_embd_enc = nullptr;
  8757. lctx.inp_KQ_mask_cross = nullptr;
  8758. }
  8759. void free() {
  8760. if (ctx0) {
  8761. ggml_free(ctx0);
  8762. ctx0 = nullptr;
  8763. }
  8764. }
  8765. struct ggml_cgraph * build_k_shift() {
  8766. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8767. GGML_ASSERT(kv_self.size == n_ctx);
  8768. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  8769. cb(lctx.inp_K_shift, "K_shift", -1);
  8770. ggml_set_input(lctx.inp_K_shift);
  8771. for (int il = 0; il < n_layer; ++il) {
  8772. const int64_t n_head_kv = hparams.n_head_kv(il);
  8773. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8774. struct ggml_tensor * rope_factors = build_rope_factors(il);
  8775. struct ggml_tensor * k =
  8776. ggml_view_3d(ctx0, kv_self.k_l[il],
  8777. n_embd_head_k, n_head_kv, n_ctx,
  8778. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  8779. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8780. 0);
  8781. struct ggml_tensor * tmp;
  8782. if (ggml_is_quantized(k->type)) {
  8783. // dequantize to f32 -> RoPE -> quantize back
  8784. tmp = ggml_cast(ctx0, k, GGML_TYPE_F32);
  8785. cb(tmp, "K_f32", il);
  8786. for (auto * backend : lctx.backends) {
  8787. // Figure out which backend KV cache belongs to
  8788. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft)) {
  8789. ggml_backend_sched_set_tensor_backend(lctx.sched, tmp, backend);
  8790. break;
  8791. }
  8792. }
  8793. tmp = ggml_rope_ext_inplace(ctx0, tmp,
  8794. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8795. ext_factor, attn_factor, beta_fast, beta_slow);
  8796. cb(tmp, "K_shifted_f32", il);
  8797. tmp = ggml_cpy(ctx0, tmp, k);
  8798. } else {
  8799. // we rotate only the first n_rot dimensions
  8800. tmp = ggml_rope_ext_inplace(ctx0, k,
  8801. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8802. ext_factor, attn_factor, beta_fast, beta_slow);
  8803. }
  8804. cb(tmp, "K_shifted", il);
  8805. ggml_build_forward_expand(gf, tmp);
  8806. }
  8807. return gf;
  8808. }
  8809. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  8810. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8811. for (uint32_t i = 0; i < ids.size(); ++i) {
  8812. const uint32_t id = ids[i];
  8813. if (i == id || id == ids.size()) {
  8814. continue;
  8815. }
  8816. uint32_t nm = 1;
  8817. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  8818. nm++;
  8819. }
  8820. for (int il = 0; il < n_layer; ++il) {
  8821. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8822. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8823. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  8824. n_embd_k_gqa, nm,
  8825. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8826. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  8827. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  8828. n_embd_k_gqa, nm,
  8829. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8830. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  8831. ggml_tensor * view_v_src;
  8832. ggml_tensor * view_v_dst;
  8833. if (flash_attn) {
  8834. // NOTE: the V cache is not transposed when using flash attention
  8835. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  8836. n_embd_v_gqa, nm,
  8837. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  8838. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  8839. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  8840. n_embd_v_gqa, nm,
  8841. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  8842. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  8843. } else {
  8844. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  8845. nm, n_embd_v_gqa,
  8846. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  8847. ggml_row_size(kv_self.v_l[il]->type, i));
  8848. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  8849. nm, n_embd_v_gqa,
  8850. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  8851. ggml_row_size(kv_self.v_l[il]->type, id));
  8852. }
  8853. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  8854. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  8855. }
  8856. i += nm - 1;
  8857. }
  8858. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  8859. return gf;
  8860. }
  8861. struct ggml_tensor * build_inp_pos() {
  8862. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  8863. cb(lctx.inp_pos, "inp_pos", -1);
  8864. ggml_set_input(lctx.inp_pos);
  8865. return lctx.inp_pos;
  8866. }
  8867. struct ggml_tensor * build_rope_factors(int il) {
  8868. // choose long/short freq factors based on the context size
  8869. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  8870. if (model.layers[il].rope_freqs != nullptr) {
  8871. return model.layers[il].rope_freqs;
  8872. }
  8873. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  8874. return model.layers[il].rope_long;
  8875. }
  8876. return model.layers[il].rope_short;
  8877. }
  8878. struct ggml_tensor * build_inp_out_ids() {
  8879. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  8880. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  8881. ggml_set_input(lctx.inp_out_ids);
  8882. return lctx.inp_out_ids;
  8883. }
  8884. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  8885. lctx.inp_KQ_mask = causal
  8886. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  8887. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  8888. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  8889. ggml_set_input(lctx.inp_KQ_mask);
  8890. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  8891. }
  8892. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  8893. GGML_ASSERT(hparams.n_swa > 0);
  8894. lctx.inp_KQ_mask_swa = causal
  8895. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  8896. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  8897. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  8898. ggml_set_input(lctx.inp_KQ_mask_swa);
  8899. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  8900. }
  8901. struct ggml_tensor * build_inp_mean() {
  8902. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  8903. cb(lctx.inp_mean, "inp_mean", -1);
  8904. ggml_set_input(lctx.inp_mean);
  8905. return lctx.inp_mean;
  8906. }
  8907. struct ggml_tensor * build_inp_cls() {
  8908. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  8909. cb(lctx.inp_cls, "inp_cls", -1);
  8910. ggml_set_input(lctx.inp_cls);
  8911. return lctx.inp_cls;
  8912. }
  8913. struct ggml_tensor * build_inp_s_copy() {
  8914. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  8915. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  8916. ggml_set_input(lctx.inp_s_copy);
  8917. return lctx.inp_s_copy;
  8918. }
  8919. struct ggml_tensor * build_inp_s_mask() {
  8920. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  8921. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  8922. ggml_set_input(lctx.inp_s_mask);
  8923. return lctx.inp_s_mask;
  8924. }
  8925. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  8926. // find result_norm tensor for input
  8927. struct ggml_tensor * inp = nullptr;
  8928. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  8929. inp = ggml_graph_node(gf, i);
  8930. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  8931. break;
  8932. } else {
  8933. inp = nullptr;
  8934. }
  8935. }
  8936. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  8937. struct ggml_tensor * cur;
  8938. switch (pooling_type) {
  8939. case LLAMA_POOLING_TYPE_NONE:
  8940. {
  8941. cur = inp;
  8942. } break;
  8943. case LLAMA_POOLING_TYPE_MEAN:
  8944. {
  8945. struct ggml_tensor * inp_mean = build_inp_mean();
  8946. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  8947. } break;
  8948. case LLAMA_POOLING_TYPE_CLS:
  8949. case LLAMA_POOLING_TYPE_LAST:
  8950. {
  8951. struct ggml_tensor * inp_cls = build_inp_cls();
  8952. cur = ggml_get_rows(ctx0, inp, inp_cls);
  8953. } break;
  8954. case LLAMA_POOLING_TYPE_RANK:
  8955. {
  8956. struct ggml_tensor * inp_cls = build_inp_cls();
  8957. inp = ggml_get_rows(ctx0, inp, inp_cls);
  8958. // classification head
  8959. // https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
  8960. GGML_ASSERT(model.cls != nullptr);
  8961. GGML_ASSERT(model.cls_b != nullptr);
  8962. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls, inp), model.cls_b);
  8963. cur = ggml_tanh(ctx0, cur);
  8964. // some models don't have `cls_out`, for example: https://huggingface.co/jinaai/jina-reranker-v1-tiny-en
  8965. // https://huggingface.co/jinaai/jina-reranker-v1-tiny-en/blob/cb5347e43979c3084a890e3f99491952603ae1b7/modeling_bert.py#L884-L896
  8966. if (model.cls_out) {
  8967. GGML_ASSERT(model.cls_out_b != nullptr);
  8968. cur = ggml_add (ctx0, ggml_mul_mat(ctx0, model.cls_out, cur), model.cls_out_b);
  8969. }
  8970. } break;
  8971. default:
  8972. {
  8973. GGML_ABORT("unknown pooling type");
  8974. }
  8975. }
  8976. cb(cur, "result_embd_pooled", -1);
  8977. ggml_build_forward_expand(gf, cur);
  8978. return gf;
  8979. }
  8980. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  8981. if (causal) {
  8982. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  8983. } else {
  8984. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  8985. }
  8986. ggml_set_input(lctx.inp_pos_bucket);
  8987. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  8988. return lctx.inp_pos_bucket;
  8989. }
  8990. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  8991. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  8992. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  8993. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  8994. cb(pos_bias, "pos_bias", -1);
  8995. 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);
  8996. cb(pos_bias, "pos_bias", -1);
  8997. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  8998. cb(pos_bias, "pos_bias", -1);
  8999. pos_bias = ggml_cont(ctx0, pos_bias);
  9000. cb(pos_bias, "pos_bias", -1);
  9001. return pos_bias;
  9002. }
  9003. struct ggml_tensor * llm_build_inp_embd_enc() {
  9004. const int64_t n_embd = hparams.n_embd;
  9005. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  9006. ggml_set_input(lctx.inp_embd_enc);
  9007. cb(lctx.inp_embd_enc, "embd_enc", -1);
  9008. return lctx.inp_embd_enc;
  9009. }
  9010. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  9011. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  9012. ggml_set_input(lctx.inp_KQ_mask_cross);
  9013. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  9014. return lctx.inp_KQ_mask_cross;
  9015. }
  9016. struct ggml_cgraph * build_llama() {
  9017. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9018. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9019. int32_t n_tokens = this->n_tokens;
  9020. const int64_t n_embd_head = hparams.n_embd_head_v;
  9021. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9022. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9023. struct ggml_tensor * cur;
  9024. struct ggml_tensor * inpL;
  9025. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9026. // inp_pos - contains the positions
  9027. struct ggml_tensor * inp_pos = build_inp_pos();
  9028. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9029. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9030. const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f/sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
  9031. for (int il = 0; il < n_layer; ++il) {
  9032. struct ggml_tensor * inpSA = inpL;
  9033. // norm
  9034. cur = llm_build_norm(ctx0, inpL, hparams,
  9035. model.layers[il].attn_norm, NULL,
  9036. LLM_NORM_RMS, cb, il);
  9037. cb(cur, "attn_norm", il);
  9038. // self-attention
  9039. {
  9040. // rope freq factors for llama3; may return nullptr for llama2 and other models
  9041. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9042. // compute Q and K and RoPE them
  9043. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9044. cb(Qcur, "Qcur", il);
  9045. if (model.layers[il].bq) {
  9046. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9047. cb(Qcur, "Qcur", il);
  9048. }
  9049. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9050. cb(Kcur, "Kcur", il);
  9051. if (model.layers[il].bk) {
  9052. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9053. cb(Kcur, "Kcur", il);
  9054. }
  9055. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9056. cb(Vcur, "Vcur", il);
  9057. if (model.layers[il].bv) {
  9058. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9059. cb(Vcur, "Vcur", il);
  9060. }
  9061. Qcur = ggml_rope_ext(
  9062. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  9063. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9064. ext_factor, attn_factor, beta_fast, beta_slow
  9065. );
  9066. cb(Qcur, "Qcur", il);
  9067. Kcur = ggml_rope_ext(
  9068. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  9069. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9070. ext_factor, attn_factor, beta_fast, beta_slow
  9071. );
  9072. cb(Kcur, "Kcur", il);
  9073. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9074. model.layers[il].wo, model.layers[il].bo,
  9075. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9076. }
  9077. if (il == n_layer - 1) {
  9078. // skip computing output for unused tokens
  9079. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9080. n_tokens = n_outputs;
  9081. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9082. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9083. }
  9084. // For Granite architecture
  9085. if (hparams.f_residual_scale) {
  9086. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9087. }
  9088. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9089. cb(ffn_inp, "ffn_inp", il);
  9090. // feed-forward network
  9091. if (model.layers[il].ffn_gate_inp == nullptr) {
  9092. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9093. model.layers[il].ffn_norm, NULL,
  9094. LLM_NORM_RMS, cb, il);
  9095. cb(cur, "ffn_norm", il);
  9096. cur = llm_build_ffn(ctx0, lctx, cur,
  9097. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9098. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  9099. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9100. NULL,
  9101. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9102. cb(cur, "ffn_out", il);
  9103. } else {
  9104. // MoE branch
  9105. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9106. model.layers[il].ffn_norm, NULL,
  9107. LLM_NORM_RMS, cb, il);
  9108. cb(cur, "ffn_norm", il);
  9109. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9110. model.layers[il].ffn_gate_inp,
  9111. model.layers[il].ffn_up_exps,
  9112. model.layers[il].ffn_gate_exps,
  9113. model.layers[il].ffn_down_exps,
  9114. n_expert, n_expert_used,
  9115. LLM_FFN_SILU, true,
  9116. false, 0.0,
  9117. cb, il);
  9118. cb(cur, "ffn_moe_out", il);
  9119. }
  9120. // For Granite architecture
  9121. if (hparams.f_residual_scale) {
  9122. cur = ggml_scale(ctx0, cur, hparams.f_residual_scale);
  9123. }
  9124. cur = ggml_add(ctx0, cur, ffn_inp);
  9125. cb(cur, "ffn_out", il);
  9126. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9127. cb(cur, "l_out", il);
  9128. // input for next layer
  9129. inpL = cur;
  9130. }
  9131. cur = inpL;
  9132. cur = llm_build_norm(ctx0, cur, hparams,
  9133. model.output_norm, NULL,
  9134. LLM_NORM_RMS, cb, -1);
  9135. cb(cur, "result_norm", -1);
  9136. // lm_head
  9137. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9138. // For Granite architecture
  9139. if (hparams.f_logit_scale) {
  9140. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_logit_scale);
  9141. }
  9142. cb(cur, "result_output", -1);
  9143. ggml_build_forward_expand(gf, cur);
  9144. return gf;
  9145. }
  9146. struct ggml_cgraph * build_baichuan() {
  9147. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9148. const int64_t n_embd_head = hparams.n_embd_head_v;
  9149. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9150. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9151. struct ggml_tensor * cur;
  9152. struct ggml_tensor * inpL;
  9153. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9154. // inp_pos - contains the positions
  9155. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  9156. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9157. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9158. for (int il = 0; il < n_layer; ++il) {
  9159. struct ggml_tensor * inpSA = inpL;
  9160. cur = llm_build_norm(ctx0, inpL, hparams,
  9161. model.layers[il].attn_norm, NULL,
  9162. LLM_NORM_RMS, cb, il);
  9163. cb(cur, "attn_norm", il);
  9164. // self-attention
  9165. {
  9166. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9167. cb(Qcur, "Qcur", il);
  9168. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9169. cb(Kcur, "Kcur", il);
  9170. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9171. cb(Vcur, "Vcur", il);
  9172. switch (model.type) {
  9173. case MODEL_7B:
  9174. Qcur = ggml_rope_ext(
  9175. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9176. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9177. ext_factor, attn_factor, beta_fast, beta_slow
  9178. );
  9179. Kcur = ggml_rope_ext(
  9180. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9181. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9182. ext_factor, attn_factor, beta_fast, beta_slow
  9183. );
  9184. break;
  9185. case MODEL_13B:
  9186. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  9187. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  9188. break;
  9189. default:
  9190. GGML_ABORT("fatal error");
  9191. }
  9192. cb(Qcur, "Qcur", il);
  9193. cb(Kcur, "Kcur", il);
  9194. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9195. model.layers[il].wo, NULL,
  9196. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9197. }
  9198. if (il == n_layer - 1) {
  9199. // skip computing output for unused tokens
  9200. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9201. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9202. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9203. }
  9204. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9205. cb(ffn_inp, "ffn_inp", il);
  9206. // feed-forward network
  9207. {
  9208. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9209. model.layers[il].ffn_norm, NULL,
  9210. LLM_NORM_RMS, cb, il);
  9211. cb(cur, "ffn_norm", il);
  9212. cur = llm_build_ffn(ctx0, lctx, cur,
  9213. model.layers[il].ffn_up, NULL, NULL,
  9214. model.layers[il].ffn_gate, NULL, NULL,
  9215. model.layers[il].ffn_down, NULL, NULL,
  9216. NULL,
  9217. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9218. cb(cur, "ffn_out", il);
  9219. }
  9220. cur = ggml_add(ctx0, cur, ffn_inp);
  9221. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9222. cb(cur, "l_out", il);
  9223. // input for next layer
  9224. inpL = cur;
  9225. }
  9226. cur = inpL;
  9227. cur = llm_build_norm(ctx0, cur, hparams,
  9228. model.output_norm, NULL,
  9229. LLM_NORM_RMS, cb, -1);
  9230. cb(cur, "result_norm", -1);
  9231. // lm_head
  9232. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9233. cb(cur, "result_output", -1);
  9234. ggml_build_forward_expand(gf, cur);
  9235. return gf;
  9236. }
  9237. struct ggml_cgraph * build_xverse() {
  9238. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9239. const int64_t n_embd_head = hparams.n_embd_head_v;
  9240. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9241. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9242. struct ggml_tensor * cur;
  9243. struct ggml_tensor * inpL;
  9244. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9245. // inp_pos - contains the positions
  9246. struct ggml_tensor * inp_pos = build_inp_pos();
  9247. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9248. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9249. for (int il = 0; il < n_layer; ++il) {
  9250. struct ggml_tensor * inpSA = inpL;
  9251. cur = llm_build_norm(ctx0, inpL, hparams,
  9252. model.layers[il].attn_norm, NULL,
  9253. LLM_NORM_RMS, cb, il);
  9254. cb(cur, "attn_norm", il);
  9255. // self-attention
  9256. {
  9257. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9258. cb(Qcur, "Qcur", il);
  9259. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9260. cb(Kcur, "Kcur", il);
  9261. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9262. cb(Vcur, "Vcur", il);
  9263. Qcur = ggml_rope_ext(
  9264. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9265. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9266. ext_factor, attn_factor, beta_fast, beta_slow
  9267. );
  9268. cb(Qcur, "Qcur", il);
  9269. Kcur = ggml_rope_ext(
  9270. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9271. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9272. ext_factor, attn_factor, beta_fast, beta_slow
  9273. );
  9274. cb(Kcur, "Kcur", il);
  9275. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9276. model.layers[il].wo, NULL,
  9277. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9278. }
  9279. if (il == n_layer - 1) {
  9280. // skip computing output for unused tokens
  9281. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9282. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9283. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9284. }
  9285. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9286. cb(ffn_inp, "ffn_inp", il);
  9287. // feed-forward network
  9288. {
  9289. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9290. model.layers[il].ffn_norm, NULL,
  9291. LLM_NORM_RMS, cb, il);
  9292. cb(cur, "ffn_norm", il);
  9293. cur = llm_build_ffn(ctx0, lctx, cur,
  9294. model.layers[il].ffn_up, NULL, NULL,
  9295. model.layers[il].ffn_gate, NULL, NULL,
  9296. model.layers[il].ffn_down, NULL, NULL,
  9297. NULL,
  9298. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9299. cb(cur, "ffn_out", il);
  9300. }
  9301. cur = ggml_add(ctx0, cur, ffn_inp);
  9302. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9303. cb(cur, "l_out", il);
  9304. // input for next layer
  9305. inpL = cur;
  9306. }
  9307. cur = inpL;
  9308. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  9309. cb(cur, "result_norm", -1);
  9310. // lm_head
  9311. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9312. cb(cur, "result_output", -1);
  9313. ggml_build_forward_expand(gf, cur);
  9314. return gf;
  9315. }
  9316. struct ggml_cgraph * build_falcon() {
  9317. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9318. const int64_t n_embd_head = hparams.n_embd_head_v;
  9319. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9320. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9321. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9322. struct ggml_tensor * cur;
  9323. struct ggml_tensor * inpL;
  9324. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9325. // inp_pos - contains the positions
  9326. struct ggml_tensor * inp_pos = build_inp_pos();
  9327. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9328. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9329. for (int il = 0; il < n_layer; ++il) {
  9330. struct ggml_tensor * attn_norm;
  9331. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  9332. model.layers[il].attn_norm,
  9333. model.layers[il].attn_norm_b,
  9334. LLM_NORM, cb, il);
  9335. cb(attn_norm, "attn_norm", il);
  9336. // self-attention
  9337. {
  9338. if (model.layers[il].attn_norm_2) {
  9339. // Falcon-40B
  9340. cur = llm_build_norm(ctx0, inpL, hparams,
  9341. model.layers[il].attn_norm_2,
  9342. model.layers[il].attn_norm_2_b,
  9343. LLM_NORM, cb, il);
  9344. cb(cur, "attn_norm_2", il);
  9345. } else {
  9346. cur = attn_norm;
  9347. }
  9348. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9349. cb(cur, "wqkv", il);
  9350. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9351. 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)));
  9352. 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)));
  9353. cb(Qcur, "Qcur", il);
  9354. cb(Kcur, "Kcur", il);
  9355. cb(Vcur, "Vcur", il);
  9356. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9357. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9358. // using mode = 2 for neox mode
  9359. Qcur = ggml_rope_ext(
  9360. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9361. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9362. );
  9363. cb(Qcur, "Qcur", il);
  9364. Kcur = ggml_rope_ext(
  9365. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9366. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9367. );
  9368. cb(Kcur, "Kcur", il);
  9369. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9370. model.layers[il].wo, NULL,
  9371. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9372. }
  9373. if (il == n_layer - 1) {
  9374. // skip computing output for unused tokens
  9375. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9376. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9377. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9378. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  9379. }
  9380. struct ggml_tensor * ffn_inp = cur;
  9381. // feed forward
  9382. {
  9383. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  9384. model.layers[il].ffn_up, NULL, NULL,
  9385. NULL, NULL, NULL,
  9386. model.layers[il].ffn_down, NULL, NULL,
  9387. NULL,
  9388. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9389. cb(cur, "ffn_out", il);
  9390. }
  9391. cur = ggml_add(ctx0, cur, ffn_inp);
  9392. cur = ggml_add(ctx0, cur, inpL);
  9393. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9394. cb(cur, "l_out", il);
  9395. // input for next layer
  9396. inpL = cur;
  9397. }
  9398. cur = inpL;
  9399. // norm
  9400. cur = llm_build_norm(ctx0, cur, hparams,
  9401. model.output_norm,
  9402. model.output_norm_b,
  9403. LLM_NORM, cb, -1);
  9404. cb(cur, "result_norm", -1);
  9405. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9406. cb(cur, "result_output", -1);
  9407. ggml_build_forward_expand(gf, cur);
  9408. return gf;
  9409. }
  9410. struct ggml_cgraph * build_grok() {
  9411. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9412. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9413. int32_t n_tokens = this->n_tokens;
  9414. const int64_t n_embd_head = hparams.n_embd_head_v;
  9415. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9416. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9417. struct ggml_tensor * cur;
  9418. struct ggml_tensor * inpL;
  9419. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9420. // multiply by embedding_multiplier_scale of 78.38367176906169
  9421. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  9422. // inp_pos - contains the positions
  9423. struct ggml_tensor * inp_pos = build_inp_pos();
  9424. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9425. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9426. for (int il = 0; il < n_layer; ++il) {
  9427. struct ggml_tensor * inpSA = inpL;
  9428. // norm
  9429. cur = llm_build_norm(ctx0, inpL, hparams,
  9430. model.layers[il].attn_norm, NULL,
  9431. LLM_NORM_RMS, cb, il);
  9432. cb(cur, "attn_norm", il);
  9433. // self-attention
  9434. {
  9435. // compute Q and K and RoPE them
  9436. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9437. cb(Qcur, "Qcur", il);
  9438. if (model.layers[il].bq) {
  9439. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9440. cb(Qcur, "Qcur", il);
  9441. }
  9442. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9443. cb(Kcur, "Kcur", il);
  9444. if (model.layers[il].bk) {
  9445. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9446. cb(Kcur, "Kcur", il);
  9447. }
  9448. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9449. cb(Vcur, "Vcur", il);
  9450. if (model.layers[il].bv) {
  9451. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9452. cb(Vcur, "Vcur", il);
  9453. }
  9454. Qcur = ggml_rope_ext(
  9455. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9456. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9457. ext_factor, attn_factor, beta_fast, beta_slow
  9458. );
  9459. cb(Qcur, "Qcur", il);
  9460. Kcur = ggml_rope_ext(
  9461. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9462. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9463. ext_factor, attn_factor, beta_fast, beta_slow
  9464. );
  9465. cb(Kcur, "Kcur", il);
  9466. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9467. model.layers[il].wo, model.layers[il].bo,
  9468. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9469. }
  9470. if (il == n_layer - 1) {
  9471. // skip computing output for unused tokens
  9472. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9473. n_tokens = n_outputs;
  9474. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9475. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9476. }
  9477. // Grok
  9478. // if attn_out_norm is present then apply it before adding the input
  9479. if (model.layers[il].attn_out_norm) {
  9480. cur = llm_build_norm(ctx0, cur, hparams,
  9481. model.layers[il].attn_out_norm, NULL,
  9482. LLM_NORM_RMS, cb, il);
  9483. cb(cur, "attn_out_norm", il);
  9484. }
  9485. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9486. cb(ffn_inp, "ffn_inp", il);
  9487. // feed-forward network
  9488. // MoE branch
  9489. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9490. model.layers[il].ffn_norm, NULL,
  9491. LLM_NORM_RMS, cb, il);
  9492. cb(cur, "ffn_norm", il);
  9493. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9494. model.layers[il].ffn_gate_inp,
  9495. model.layers[il].ffn_up_exps,
  9496. model.layers[il].ffn_gate_exps,
  9497. model.layers[il].ffn_down_exps,
  9498. n_expert, n_expert_used,
  9499. LLM_FFN_GELU, true,
  9500. false, 0.0,
  9501. cb, il);
  9502. cb(cur, "ffn_moe_out", il);
  9503. // Grok
  9504. // if layer_out_norm is present then apply it before adding the input
  9505. // Idea: maybe ffn_out_norm is a better name
  9506. if (model.layers[il].layer_out_norm) {
  9507. cur = llm_build_norm(ctx0, cur, hparams,
  9508. model.layers[il].layer_out_norm, NULL,
  9509. LLM_NORM_RMS, cb, il);
  9510. cb(cur, "layer_out_norm", il);
  9511. }
  9512. cur = ggml_add(ctx0, cur, ffn_inp);
  9513. cb(cur, "ffn_out", il);
  9514. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9515. cb(cur, "l_out", il);
  9516. // input for next layer
  9517. inpL = cur;
  9518. }
  9519. cur = inpL;
  9520. cur = llm_build_norm(ctx0, cur, hparams,
  9521. model.output_norm, NULL,
  9522. LLM_NORM_RMS, cb, -1);
  9523. cb(cur, "result_norm", -1);
  9524. // lm_head
  9525. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9526. // Grok
  9527. // multiply logits by output_multiplier_scale of 0.5773502691896257
  9528. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  9529. cb(cur, "result_output", -1);
  9530. ggml_build_forward_expand(gf, cur);
  9531. return gf;
  9532. }
  9533. struct ggml_cgraph * build_dbrx() {
  9534. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9535. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9536. int32_t n_tokens = this->n_tokens;
  9537. const int64_t n_embd_head = hparams.n_embd_head_v;
  9538. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9539. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9540. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9541. struct ggml_tensor * cur;
  9542. struct ggml_tensor * inpL;
  9543. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9544. // inp_pos - contains the positions
  9545. struct ggml_tensor * inp_pos = build_inp_pos();
  9546. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9547. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9548. for (int il = 0; il < n_layer; ++il) {
  9549. struct ggml_tensor * inpSA = inpL;
  9550. // norm
  9551. cur = llm_build_norm(ctx0, inpL, hparams,
  9552. model.layers[il].attn_norm, NULL,
  9553. LLM_NORM, cb, il);
  9554. cb(cur, "attn_norm", il);
  9555. // self-attention
  9556. {
  9557. struct ggml_tensor * Qcur = nullptr;
  9558. struct ggml_tensor * Kcur = nullptr;
  9559. struct ggml_tensor * Vcur = nullptr;
  9560. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9561. cb(cur, "wqkv", il);
  9562. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  9563. cb(cur, "wqkv_clamped", il);
  9564. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9565. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9566. 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)));
  9567. cb(Qcur, "Qcur", il);
  9568. cb(Kcur, "Kcur", il);
  9569. cb(Vcur, "Vcur", il);
  9570. Qcur = ggml_rope_ext(
  9571. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9572. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9573. ext_factor, attn_factor, beta_fast, beta_slow
  9574. );
  9575. cb(Qcur, "Qcur", il);
  9576. Kcur = ggml_rope_ext(
  9577. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9578. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9579. ext_factor, attn_factor, beta_fast, beta_slow
  9580. );
  9581. cb(Kcur, "Kcur", il);
  9582. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9583. model.layers[il].wo, NULL,
  9584. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9585. }
  9586. if (il == n_layer - 1) {
  9587. // skip computing output for unused tokens
  9588. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9589. n_tokens = n_outputs;
  9590. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9591. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9592. }
  9593. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9594. cb(ffn_inp, "ffn_inp", il);
  9595. // feed-forward network
  9596. // MoE branch
  9597. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9598. model.layers[il].attn_out_norm, NULL,
  9599. LLM_NORM, cb, il);
  9600. cb(cur, "attn_out_norm", il);
  9601. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  9602. model.layers[il].ffn_gate_inp,
  9603. model.layers[il].ffn_up_exps,
  9604. model.layers[il].ffn_gate_exps,
  9605. model.layers[il].ffn_down_exps,
  9606. n_expert, n_expert_used,
  9607. LLM_FFN_SILU, true,
  9608. false, 0.0,
  9609. cb, il);
  9610. cb(cur, "ffn_moe_out", il);
  9611. cur = ggml_add(ctx0, cur, ffn_inp);
  9612. cb(cur, "ffn_out", il);
  9613. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9614. cb(cur, "l_out", il);
  9615. // input for next layer
  9616. inpL = cur;
  9617. }
  9618. cur = inpL;
  9619. cur = llm_build_norm(ctx0, cur, hparams,
  9620. model.output_norm, NULL,
  9621. LLM_NORM, cb, -1);
  9622. cb(cur, "result_norm", -1);
  9623. // lm_head
  9624. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9625. cb(cur, "result_output", -1);
  9626. ggml_build_forward_expand(gf, cur);
  9627. return gf;
  9628. }
  9629. struct ggml_cgraph * build_starcoder() {
  9630. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9631. const int64_t n_embd_head = hparams.n_embd_head_v;
  9632. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9633. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9634. struct ggml_tensor * cur;
  9635. struct ggml_tensor * inpL;
  9636. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9637. // inp_pos - contains the positions
  9638. struct ggml_tensor * inp_pos = build_inp_pos();
  9639. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9640. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9641. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  9642. cb(pos, "pos_embd", -1);
  9643. inpL = ggml_add(ctx0, inpL, pos);
  9644. cb(inpL, "inpL", -1);
  9645. for (int il = 0; il < n_layer; ++il) {
  9646. cur = llm_build_norm(ctx0, inpL, hparams,
  9647. model.layers[il].attn_norm,
  9648. model.layers[il].attn_norm_b,
  9649. LLM_NORM, cb, il);
  9650. cb(cur, "attn_norm", il);
  9651. // self-attention
  9652. {
  9653. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9654. cb(cur, "wqkv", il);
  9655. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9656. cb(cur, "bqkv", il);
  9657. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9658. 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)));
  9659. 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)));
  9660. cb(Qcur, "Qcur", il);
  9661. cb(Kcur, "Kcur", il);
  9662. cb(Vcur, "Vcur", il);
  9663. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9664. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9665. model.layers[il].wo, model.layers[il].bo,
  9666. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9667. }
  9668. if (il == n_layer - 1) {
  9669. // skip computing output for unused tokens
  9670. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9671. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9672. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9673. }
  9674. // add the input
  9675. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9676. cb(ffn_inp, "ffn_inp", il);
  9677. // FF
  9678. {
  9679. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9680. model.layers[il].ffn_norm,
  9681. model.layers[il].ffn_norm_b,
  9682. LLM_NORM, cb, il);
  9683. cb(cur, "ffn_norm", il);
  9684. cur = llm_build_ffn(ctx0, lctx, cur,
  9685. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9686. NULL, NULL, NULL,
  9687. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9688. NULL,
  9689. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9690. cb(cur, "ffn_out", il);
  9691. }
  9692. cur = ggml_add(ctx0, cur, ffn_inp);
  9693. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9694. cb(cur, "l_out", il);
  9695. // input for next layer
  9696. inpL = cur;
  9697. }
  9698. cur = llm_build_norm(ctx0, inpL, hparams,
  9699. model.output_norm,
  9700. model.output_norm_b,
  9701. LLM_NORM, cb, -1);
  9702. cb(cur, "result_norm", -1);
  9703. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9704. cb(cur, "result_output", -1);
  9705. ggml_build_forward_expand(gf, cur);
  9706. return gf;
  9707. }
  9708. struct ggml_cgraph * build_refact() {
  9709. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9710. const int64_t n_embd_head = hparams.n_embd_head_v;
  9711. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9712. struct ggml_tensor * cur;
  9713. struct ggml_tensor * inpL;
  9714. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9715. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9716. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9717. for (int il = 0; il < n_layer; ++il) {
  9718. struct ggml_tensor * inpSA = inpL;
  9719. cur = llm_build_norm(ctx0, inpL, hparams,
  9720. model.layers[il].attn_norm, NULL,
  9721. LLM_NORM_RMS, cb, il);
  9722. cb(cur, "attn_norm", il);
  9723. // self-attention
  9724. {
  9725. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9726. cb(Qcur, "Qcur", il);
  9727. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9728. cb(Kcur, "Kcur", il);
  9729. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9730. cb(Vcur, "Vcur", il);
  9731. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9732. cb(Kcur, "Kcur", il);
  9733. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9734. cb(Qcur, "Qcur", il);
  9735. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9736. model.layers[il].wo, NULL,
  9737. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9738. }
  9739. if (il == n_layer - 1) {
  9740. // skip computing output for unused tokens
  9741. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9742. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9743. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9744. }
  9745. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9746. cb(ffn_inp, "ffn_inp", il);
  9747. // feed-forward network
  9748. {
  9749. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9750. model.layers[il].ffn_norm, NULL,
  9751. LLM_NORM_RMS, cb, il);
  9752. cb(cur, "ffn_norm", il);
  9753. cur = llm_build_ffn(ctx0, lctx, cur,
  9754. model.layers[il].ffn_up, NULL, NULL,
  9755. model.layers[il].ffn_gate, NULL, NULL,
  9756. model.layers[il].ffn_down, NULL, NULL,
  9757. NULL,
  9758. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9759. cb(cur, "ffn_out", il);
  9760. }
  9761. cur = ggml_add(ctx0, cur, ffn_inp);
  9762. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9763. cb(cur, "l_out", il);
  9764. // input for next layer
  9765. inpL = cur;
  9766. }
  9767. cur = inpL;
  9768. cur = llm_build_norm(ctx0, cur, hparams,
  9769. model.output_norm, NULL,
  9770. LLM_NORM_RMS, cb, -1);
  9771. cb(cur, "result_norm", -1);
  9772. // lm_head
  9773. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9774. cb(cur, "result_output", -1);
  9775. ggml_build_forward_expand(gf, cur);
  9776. return gf;
  9777. }
  9778. struct ggml_cgraph * build_bert() {
  9779. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9780. const int64_t n_embd_head = hparams.n_embd_head_v;
  9781. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9782. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9783. struct ggml_tensor * cur;
  9784. struct ggml_tensor * inpL;
  9785. struct ggml_tensor * inp_pos = nullptr;
  9786. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  9787. inp_pos = build_inp_pos();
  9788. }
  9789. // construct input embeddings (token, type, position)
  9790. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9791. // token types are hardcoded to zero ("Sentence A")
  9792. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  9793. inpL = ggml_add(ctx0, inpL, type_row0);
  9794. if (model.arch == LLM_ARCH_BERT) {
  9795. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  9796. }
  9797. cb(inpL, "inp_embd", -1);
  9798. // embed layer norm
  9799. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  9800. cb(inpL, "inp_norm", -1);
  9801. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9802. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  9803. // iterate layers
  9804. for (int il = 0; il < n_layer; ++il) {
  9805. struct ggml_tensor * cur = inpL;
  9806. struct ggml_tensor * Qcur;
  9807. struct ggml_tensor * Kcur;
  9808. struct ggml_tensor * Vcur;
  9809. // self-attention
  9810. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  9811. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  9812. cb(Qcur, "Qcur", il);
  9813. if (model.layers[il].attn_q_norm) {
  9814. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  9815. model.layers[il].attn_q_norm,
  9816. model.layers[il].attn_q_norm_b,
  9817. LLM_NORM, cb, il);
  9818. }
  9819. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  9820. cb(Kcur, "Kcur", il);
  9821. if (model.layers[il].attn_k_norm) {
  9822. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  9823. model.layers[il].attn_k_norm,
  9824. model.layers[il].attn_k_norm_b,
  9825. LLM_NORM, cb, il);
  9826. }
  9827. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  9828. cb(Vcur, "Vcur", il);
  9829. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9830. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9831. } else {
  9832. // compute Q and K and RoPE them
  9833. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9834. cb(cur, "wqkv", il);
  9835. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9836. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9837. 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)));
  9838. cb(Qcur, "Qcur", il);
  9839. cb(Kcur, "Kcur", il);
  9840. cb(Vcur, "Vcur", il);
  9841. Qcur = ggml_rope_ext(
  9842. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9843. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9844. ext_factor, attn_factor, beta_fast, beta_slow
  9845. );
  9846. cb(Qcur, "Qcur", il);
  9847. Kcur = ggml_rope_ext(
  9848. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9849. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9850. ext_factor, attn_factor, beta_fast, beta_slow
  9851. );
  9852. cb(Kcur, "Kcur", il);
  9853. }
  9854. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  9855. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9856. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  9857. cb(kq, "kq", il);
  9858. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  9859. cb(kq, "kq_soft_max_ext", il);
  9860. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  9861. cb(v, "v", il);
  9862. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  9863. cb(kqv, "kqv", il);
  9864. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9865. cb(kqv_merged, "kqv_merged", il);
  9866. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  9867. cb(cur, "kqv_merged_cont", il);
  9868. ggml_build_forward_expand(gf, cur);
  9869. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  9870. if (model.layers[il].bo) {
  9871. cb(cur, "kqv_wo", il);
  9872. }
  9873. if (model.layers[il].bo) {
  9874. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  9875. }
  9876. cb(cur, "kqv_out", il);
  9877. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  9878. // skip computing output for unused tokens
  9879. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9880. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9881. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9882. }
  9883. // re-add the layer input
  9884. cur = ggml_add(ctx0, cur, inpL);
  9885. // attention layer norm
  9886. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  9887. if (model.layers[il].attn_norm_2 != nullptr) {
  9888. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  9889. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  9890. }
  9891. struct ggml_tensor * ffn_inp = cur;
  9892. cb(ffn_inp, "ffn_inp", il);
  9893. // feed-forward network
  9894. if (model.arch == LLM_ARCH_BERT) {
  9895. cur = llm_build_ffn(ctx0, lctx, cur,
  9896. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9897. NULL, NULL, NULL,
  9898. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9899. NULL,
  9900. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9901. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  9902. cur = llm_build_ffn(ctx0, lctx, cur,
  9903. model.layers[il].ffn_up, NULL, NULL,
  9904. model.layers[il].ffn_gate, NULL, NULL,
  9905. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9906. NULL,
  9907. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9908. } else {
  9909. cur = llm_build_ffn(ctx0, lctx, cur,
  9910. model.layers[il].ffn_up, NULL, NULL,
  9911. model.layers[il].ffn_gate, NULL, NULL,
  9912. model.layers[il].ffn_down, NULL, NULL,
  9913. NULL,
  9914. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9915. }
  9916. cb(cur, "ffn_out", il);
  9917. // attentions bypass the intermediate layer
  9918. cur = ggml_add(ctx0, cur, ffn_inp);
  9919. // output layer norm
  9920. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  9921. // input for next layer
  9922. inpL = cur;
  9923. }
  9924. cur = inpL;
  9925. cb(cur, "result_embd", -1);
  9926. ggml_build_forward_expand(gf, cur);
  9927. return gf;
  9928. }
  9929. struct ggml_cgraph * build_bloom() {
  9930. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9931. const int64_t n_embd_head = hparams.n_embd_head_v;
  9932. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9933. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9934. struct ggml_tensor * cur;
  9935. struct ggml_tensor * inpL;
  9936. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9937. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9938. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9939. inpL = llm_build_norm(ctx0, inpL, hparams,
  9940. model.tok_norm,
  9941. model.tok_norm_b,
  9942. LLM_NORM, cb, -1);
  9943. cb(inpL, "inp_norm", -1);
  9944. for (int il = 0; il < n_layer; ++il) {
  9945. cur = llm_build_norm(ctx0, inpL, hparams,
  9946. model.layers[il].attn_norm,
  9947. model.layers[il].attn_norm_b,
  9948. LLM_NORM, cb, il);
  9949. cb(cur, "attn_norm", il);
  9950. // self-attention
  9951. {
  9952. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9953. cb(cur, "wqkv", il);
  9954. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9955. cb(cur, "bqkv", il);
  9956. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9957. 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)));
  9958. 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)));
  9959. cb(Qcur, "Qcur", il);
  9960. cb(Kcur, "Kcur", il);
  9961. cb(Vcur, "Vcur", il);
  9962. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9963. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9964. model.layers[il].wo, model.layers[il].bo,
  9965. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9966. }
  9967. if (il == n_layer - 1) {
  9968. // skip computing output for unused tokens
  9969. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9970. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9971. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9972. }
  9973. // Add the input
  9974. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9975. cb(ffn_inp, "ffn_inp", il);
  9976. // FF
  9977. {
  9978. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9979. model.layers[il].ffn_norm,
  9980. model.layers[il].ffn_norm_b,
  9981. LLM_NORM, cb, il);
  9982. cb(cur, "ffn_norm", il);
  9983. cur = llm_build_ffn(ctx0, lctx, cur,
  9984. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9985. NULL, NULL, NULL,
  9986. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9987. NULL,
  9988. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9989. cb(cur, "ffn_out", il);
  9990. }
  9991. cur = ggml_add(ctx0, cur, ffn_inp);
  9992. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9993. cb(cur, "l_out", il);
  9994. // input for next layer
  9995. inpL = cur;
  9996. }
  9997. cur = llm_build_norm(ctx0, inpL, hparams,
  9998. model.output_norm,
  9999. model.output_norm_b,
  10000. LLM_NORM, cb, -1);
  10001. cb(cur, "result_norm", -1);
  10002. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10003. cb(cur, "result_output", -1);
  10004. ggml_build_forward_expand(gf, cur);
  10005. return gf;
  10006. }
  10007. struct ggml_cgraph * build_mpt() {
  10008. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10009. const int64_t n_embd_head = hparams.n_embd_head_v;
  10010. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10011. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10012. struct ggml_tensor * cur;
  10013. struct ggml_tensor * pos;
  10014. struct ggml_tensor * inpL;
  10015. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10016. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10017. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10018. if (model.pos_embd) {
  10019. // inp_pos - contains the positions
  10020. struct ggml_tensor * inp_pos = build_inp_pos();
  10021. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10022. cb(pos, "pos_embd", -1);
  10023. inpL = ggml_add(ctx0, inpL, pos);
  10024. cb(inpL, "inpL", -1);
  10025. }
  10026. for (int il = 0; il < n_layer; ++il) {
  10027. struct ggml_tensor * attn_norm;
  10028. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  10029. model.layers[il].attn_norm,
  10030. model.layers[il].attn_norm_b,
  10031. LLM_NORM, cb, il);
  10032. cb(attn_norm, "attn_norm", il);
  10033. // self-attention
  10034. {
  10035. cur = attn_norm;
  10036. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10037. cb(cur, "wqkv", il);
  10038. if (model.layers[il].bqkv){
  10039. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10040. cb(cur, "bqkv", il);
  10041. }
  10042. if (hparams.f_clamp_kqv > 0.0f) {
  10043. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10044. cb(cur, "wqkv_clamped", il);
  10045. }
  10046. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10047. 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)));
  10048. 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)));
  10049. cb(Qcur, "Qcur", il);
  10050. cb(Kcur, "Kcur", il);
  10051. cb(Vcur, "Vcur", il);
  10052. // Q/K Layernorm
  10053. if (model.layers[il].attn_q_norm) {
  10054. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10055. model.layers[il].attn_q_norm,
  10056. model.layers[il].attn_q_norm_b,
  10057. LLM_NORM, cb, il);
  10058. cb(Qcur, "Qcur", il);
  10059. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10060. model.layers[il].attn_k_norm,
  10061. model.layers[il].attn_k_norm_b,
  10062. LLM_NORM, cb, il);
  10063. cb(Kcur, "Kcur", il);
  10064. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10065. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10066. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10067. model.layers[il].wo, model.layers[il].bo,
  10068. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10069. } else {
  10070. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10071. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10072. model.layers[il].wo, model.layers[il].bo,
  10073. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10074. }
  10075. }
  10076. if (il == n_layer - 1) {
  10077. // skip computing output for unused tokens
  10078. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10079. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10080. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10081. }
  10082. // Add the input
  10083. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10084. cb(ffn_inp, "ffn_inp", il);
  10085. // feed forward
  10086. {
  10087. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10088. model.layers[il].ffn_norm,
  10089. model.layers[il].ffn_norm_b,
  10090. LLM_NORM, cb, il);
  10091. cb(cur, "ffn_norm", il);
  10092. cur = llm_build_ffn(ctx0, lctx, cur,
  10093. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10094. NULL, NULL, NULL,
  10095. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10096. model.layers[il].ffn_act,
  10097. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10098. cb(cur, "ffn_out", il);
  10099. }
  10100. cur = ggml_add(ctx0, cur, ffn_inp);
  10101. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10102. cb(cur, "l_out", il);
  10103. // input for next layer
  10104. inpL = cur;
  10105. }
  10106. cur = inpL;
  10107. cur = llm_build_norm(ctx0, cur, hparams,
  10108. model.output_norm,
  10109. model.output_norm_b,
  10110. LLM_NORM, cb, -1);
  10111. cb(cur, "result_norm", -1);
  10112. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10113. cb(cur, "result_output", -1);
  10114. ggml_build_forward_expand(gf, cur);
  10115. return gf;
  10116. }
  10117. struct ggml_cgraph * build_stablelm() {
  10118. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10119. const int64_t n_embd_head = hparams.n_embd_head_v;
  10120. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10121. struct ggml_tensor * cur;
  10122. struct ggml_tensor * inpL;
  10123. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10124. // inp_pos - contains the positions
  10125. struct ggml_tensor * inp_pos = build_inp_pos();
  10126. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10127. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10128. for (int il = 0; il < n_layer; ++il) {
  10129. // norm
  10130. cur = llm_build_norm(ctx0, inpL, hparams,
  10131. model.layers[il].attn_norm,
  10132. model.layers[il].attn_norm_b,
  10133. LLM_NORM, cb, il);
  10134. cb(cur, "attn_norm", il);
  10135. struct ggml_tensor * inpSA = cur;
  10136. // self-attention
  10137. {
  10138. // compute Q and K and RoPE them
  10139. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10140. cb(Qcur, "Qcur", il);
  10141. if (model.layers[il].bq) {
  10142. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10143. cb(Qcur, "Qcur", il);
  10144. }
  10145. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10146. cb(Kcur, "Kcur", il);
  10147. if (model.layers[il].bk) {
  10148. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10149. cb(Kcur, "Kcur", il);
  10150. }
  10151. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10152. cb(Vcur, "Vcur", il);
  10153. if (model.layers[il].bv) {
  10154. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10155. cb(Vcur, "Vcur", il);
  10156. }
  10157. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10158. cb(Qcur, "Qcur", il);
  10159. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10160. cb(Kcur, "Kcur", il);
  10161. if (model.layers[il].attn_q_norm) {
  10162. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10163. model.layers[il].attn_q_norm,
  10164. NULL,
  10165. LLM_NORM, cb, il);
  10166. cb(Qcur, "Qcur", il);
  10167. }
  10168. if (model.layers[il].attn_k_norm) {
  10169. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10170. model.layers[il].attn_k_norm,
  10171. NULL,
  10172. LLM_NORM, cb, il);
  10173. cb(Kcur, "Kcur", il);
  10174. }
  10175. Qcur = ggml_rope_ext(
  10176. ctx0, Qcur, inp_pos, nullptr,
  10177. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10178. ext_factor, attn_factor, beta_fast, beta_slow
  10179. );
  10180. cb(Qcur, "Qcur", il);
  10181. Kcur = ggml_rope_ext(
  10182. ctx0, Kcur, inp_pos, nullptr,
  10183. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10184. ext_factor, attn_factor, beta_fast, beta_slow
  10185. );
  10186. cb(Kcur, "Kcur", il);
  10187. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10188. model.layers[il].wo, NULL,
  10189. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10190. }
  10191. if (il == n_layer - 1) {
  10192. // skip computing output for unused tokens
  10193. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10194. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10195. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10196. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10197. }
  10198. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10199. cb(ffn_inp, "ffn_inp", il);
  10200. // feed-forward network
  10201. {
  10202. if (model.layers[il].ffn_norm) {
  10203. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10204. model.layers[il].ffn_norm,
  10205. model.layers[il].ffn_norm_b,
  10206. LLM_NORM, cb, il);
  10207. cb(cur, "ffn_norm", il);
  10208. } else {
  10209. // parallel residual
  10210. cur = inpSA;
  10211. }
  10212. cur = llm_build_ffn(ctx0, lctx, cur,
  10213. model.layers[il].ffn_up, NULL, NULL,
  10214. model.layers[il].ffn_gate, NULL, NULL,
  10215. model.layers[il].ffn_down, NULL, NULL,
  10216. NULL,
  10217. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10218. cb(cur, "ffn_out", il);
  10219. }
  10220. cur = ggml_add(ctx0, cur, ffn_inp);
  10221. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10222. cb(cur, "l_out", il);
  10223. // input for next layer
  10224. inpL = cur;
  10225. }
  10226. cur = inpL;
  10227. cur = llm_build_norm(ctx0, cur, hparams,
  10228. model.output_norm,
  10229. model.output_norm_b,
  10230. LLM_NORM, cb, -1);
  10231. cb(cur, "result_norm", -1);
  10232. // lm_head
  10233. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10234. cb(cur, "result_output", -1);
  10235. ggml_build_forward_expand(gf, cur);
  10236. return gf;
  10237. }
  10238. struct ggml_cgraph * build_qwen() {
  10239. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10240. const int64_t n_embd_head = hparams.n_embd_head_v;
  10241. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10242. struct ggml_tensor * cur;
  10243. struct ggml_tensor * inpL;
  10244. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10245. // inp_pos - contains the positions
  10246. struct ggml_tensor * inp_pos = build_inp_pos();
  10247. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10248. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10249. for (int il = 0; il < n_layer; ++il) {
  10250. struct ggml_tensor * inpSA = inpL;
  10251. cur = llm_build_norm(ctx0, inpL, hparams,
  10252. model.layers[il].attn_norm, NULL,
  10253. LLM_NORM_RMS, cb, il);
  10254. cb(cur, "attn_norm", il);
  10255. // self-attention
  10256. {
  10257. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10258. cb(cur, "wqkv", il);
  10259. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10260. cb(cur, "bqkv", il);
  10261. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10262. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10263. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  10264. cb(Qcur, "Qcur", il);
  10265. cb(Kcur, "Kcur", il);
  10266. cb(Vcur, "Vcur", il);
  10267. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10268. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10269. // using mode = 2 for neox mode
  10270. Qcur = ggml_rope_ext(
  10271. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10272. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10273. );
  10274. cb(Qcur, "Qcur", il);
  10275. Kcur = ggml_rope_ext(
  10276. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10277. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10278. );
  10279. cb(Kcur, "Kcur", il);
  10280. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10281. model.layers[il].wo, NULL,
  10282. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10283. }
  10284. if (il == n_layer - 1) {
  10285. // skip computing output for unused tokens
  10286. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10287. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10288. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10289. }
  10290. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10291. cb(ffn_inp, "ffn_inp", il);
  10292. // feed-forward forward
  10293. {
  10294. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10295. model.layers[il].ffn_norm, NULL,
  10296. LLM_NORM_RMS, cb, il);
  10297. cb(cur, "ffn_norm", il);
  10298. cur = llm_build_ffn(ctx0, lctx, cur,
  10299. model.layers[il].ffn_up, NULL, NULL,
  10300. model.layers[il].ffn_gate, NULL, NULL,
  10301. model.layers[il].ffn_down, NULL, NULL,
  10302. NULL,
  10303. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10304. cb(cur, "ffn_out", il);
  10305. }
  10306. cur = ggml_add(ctx0, cur, ffn_inp);
  10307. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10308. cb(cur, "l_out", il);
  10309. // input for next layer
  10310. inpL = cur;
  10311. }
  10312. cur = inpL;
  10313. cur = llm_build_norm(ctx0, cur, hparams,
  10314. model.output_norm, NULL,
  10315. LLM_NORM_RMS, cb, -1);
  10316. cb(cur, "result_norm", -1);
  10317. // lm_head
  10318. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10319. cb(cur, "result_output", -1);
  10320. ggml_build_forward_expand(gf, cur);
  10321. return gf;
  10322. }
  10323. struct ggml_cgraph * build_qwen2() {
  10324. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10325. const int64_t n_embd_head = hparams.n_embd_head_v;
  10326. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10327. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10328. struct ggml_tensor * cur;
  10329. struct ggml_tensor * inpL;
  10330. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10331. // inp_pos - contains the positions
  10332. struct ggml_tensor * inp_pos = build_inp_pos();
  10333. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10334. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10335. for (int il = 0; il < n_layer; ++il) {
  10336. struct ggml_tensor * inpSA = inpL;
  10337. // norm
  10338. cur = llm_build_norm(ctx0, inpL, hparams,
  10339. model.layers[il].attn_norm, NULL,
  10340. LLM_NORM_RMS, cb, il);
  10341. cb(cur, "attn_norm", il);
  10342. // self-attention
  10343. {
  10344. // compute Q and K and RoPE them
  10345. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10346. cb(Qcur, "Qcur", il);
  10347. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10348. cb(Qcur, "Qcur", il);
  10349. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10350. cb(Kcur, "Kcur", il);
  10351. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10352. cb(Kcur, "Kcur", il);
  10353. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10354. cb(Vcur, "Vcur", il);
  10355. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10356. cb(Vcur, "Vcur", il);
  10357. Qcur = ggml_rope_ext(
  10358. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10359. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10360. ext_factor, attn_factor, beta_fast, beta_slow
  10361. );
  10362. cb(Qcur, "Qcur", il);
  10363. Kcur = ggml_rope_ext(
  10364. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10365. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10366. ext_factor, attn_factor, beta_fast, beta_slow
  10367. );
  10368. cb(Kcur, "Kcur", il);
  10369. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10370. model.layers[il].wo, model.layers[il].bo,
  10371. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10372. }
  10373. if (il == n_layer - 1) {
  10374. // skip computing output for unused tokens
  10375. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10376. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10377. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10378. }
  10379. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10380. cb(ffn_inp, "ffn_inp", il);
  10381. // feed-forward network
  10382. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10383. model.layers[il].ffn_norm, NULL,
  10384. LLM_NORM_RMS, cb, il);
  10385. cb(cur, "ffn_norm", il);
  10386. cur = llm_build_ffn(ctx0, lctx, cur,
  10387. model.layers[il].ffn_up, NULL, NULL,
  10388. model.layers[il].ffn_gate, NULL, NULL,
  10389. model.layers[il].ffn_down, NULL, NULL,
  10390. NULL,
  10391. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10392. cb(cur, "ffn_out", il);
  10393. cur = ggml_add(ctx0, cur, ffn_inp);
  10394. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10395. cb(cur, "l_out", il);
  10396. // input for next layer
  10397. inpL = cur;
  10398. }
  10399. cur = inpL;
  10400. cur = llm_build_norm(ctx0, cur, hparams,
  10401. model.output_norm, NULL,
  10402. LLM_NORM_RMS, cb, -1);
  10403. cb(cur, "result_norm", -1);
  10404. // lm_head
  10405. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10406. cb(cur, "result_output", -1);
  10407. ggml_build_forward_expand(gf, cur);
  10408. return gf;
  10409. }
  10410. struct ggml_cgraph * build_qwen2moe() {
  10411. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10412. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10413. int32_t n_tokens = this->n_tokens;
  10414. const int64_t n_embd_head = hparams.n_embd_head_v;
  10415. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10416. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10417. struct ggml_tensor * cur;
  10418. struct ggml_tensor * inpL;
  10419. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10420. // inp_pos - contains the positions
  10421. struct ggml_tensor * inp_pos = build_inp_pos();
  10422. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10423. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10424. for (int il = 0; il < n_layer; ++il) {
  10425. struct ggml_tensor * inpSA = inpL;
  10426. // norm
  10427. cur = llm_build_norm(ctx0, inpL, hparams,
  10428. model.layers[il].attn_norm, NULL,
  10429. LLM_NORM_RMS, cb, il);
  10430. cb(cur, "attn_norm", il);
  10431. // self_attention
  10432. {
  10433. // compute Q and K and RoPE them
  10434. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10435. cb(Qcur, "Qcur", il);
  10436. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10437. cb(Qcur, "Qcur", il);
  10438. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10439. cb(Kcur, "Kcur", il);
  10440. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10441. cb(Kcur, "Kcur", il);
  10442. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10443. cb(Vcur, "Vcur", il);
  10444. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10445. cb(Vcur, "Vcur", il);
  10446. Qcur = ggml_rope_ext(
  10447. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10448. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10449. ext_factor, attn_factor, beta_fast, beta_slow
  10450. );
  10451. cb(Qcur, "Qcur", il);
  10452. Kcur = ggml_rope_ext(
  10453. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10454. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10455. ext_factor, attn_factor, beta_fast, beta_slow
  10456. );
  10457. cb(Kcur, "Kcur", il);
  10458. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10459. model.layers[il].wo, model.layers[il].bo,
  10460. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  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. n_tokens = n_outputs;
  10466. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10467. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10468. }
  10469. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10470. cb(ffn_inp, "ffn_inp", il);
  10471. // MoE branch
  10472. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10473. model.layers[il].ffn_norm, NULL,
  10474. LLM_NORM_RMS, cb, il);
  10475. cb(cur, "ffn_norm", il);
  10476. ggml_tensor * moe_out =
  10477. llm_build_moe_ffn(ctx0, lctx, cur,
  10478. model.layers[il].ffn_gate_inp,
  10479. model.layers[il].ffn_up_exps,
  10480. model.layers[il].ffn_gate_exps,
  10481. model.layers[il].ffn_down_exps,
  10482. n_expert, n_expert_used,
  10483. LLM_FFN_SILU, false,
  10484. false, 0.0,
  10485. cb, il);
  10486. cb(cur, "ffn_moe_out", il);
  10487. // FFN shared expert
  10488. {
  10489. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  10490. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  10491. // sigmoid
  10492. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  10493. cb(cur_gate, "ffn_shexp_gate", il);
  10494. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  10495. model.layers[il].ffn_up_shexp, NULL, NULL,
  10496. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10497. model.layers[il].ffn_down_shexp, NULL, NULL,
  10498. NULL,
  10499. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10500. cb(cur_ffn, "ffn_shexp", il);
  10501. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  10502. cb(ffn_shexp_out, "ffn_shexp_out", il);
  10503. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  10504. cb(moe_out, "ffn_out", il);
  10505. cur = moe_out;
  10506. }
  10507. cur = ggml_add(ctx0, cur, ffn_inp);
  10508. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10509. cb(cur, "l_out", il);
  10510. // input for next layer
  10511. inpL = cur;
  10512. }
  10513. cur = inpL;
  10514. cur = llm_build_norm(ctx0, cur, hparams,
  10515. model.output_norm, NULL,
  10516. LLM_NORM_RMS, cb, -1);
  10517. cb(cur, "result_norm", -1);
  10518. // lm_head
  10519. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10520. cb(cur, "result_output", -1);
  10521. ggml_build_forward_expand(gf, cur);
  10522. return gf;
  10523. }
  10524. struct ggml_cgraph * build_phi2() {
  10525. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10526. const int64_t n_embd_head = hparams.n_embd_head_v;
  10527. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10528. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10529. struct ggml_tensor * cur;
  10530. struct ggml_tensor * attn_norm_output;
  10531. struct ggml_tensor * ffn_output;
  10532. struct ggml_tensor * inpL;
  10533. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10534. // inp_pos - contains the positions
  10535. struct ggml_tensor * inp_pos = build_inp_pos();
  10536. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10537. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10538. for (int il = 0; il < n_layer; ++il) {
  10539. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  10540. model.layers[il].attn_norm,
  10541. model.layers[il].attn_norm_b,
  10542. LLM_NORM, cb, il);
  10543. cb(attn_norm_output, "attn_norm", il);
  10544. // self-attention
  10545. {
  10546. struct ggml_tensor * Qcur = nullptr;
  10547. struct ggml_tensor * Kcur = nullptr;
  10548. struct ggml_tensor * Vcur = nullptr;
  10549. if (model.layers[il].wqkv) {
  10550. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  10551. cb(cur, "wqkv", il);
  10552. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10553. cb(cur, "bqkv", il);
  10554. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10555. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10556. 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)));
  10557. } else {
  10558. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  10559. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  10560. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  10561. }
  10562. cb(Qcur, "Qcur", il);
  10563. cb(Kcur, "Kcur", il);
  10564. cb(Vcur, "Vcur", il);
  10565. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10566. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10567. Qcur = ggml_rope_ext(
  10568. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10569. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10570. );
  10571. cb(Qcur, "Qcur", il);
  10572. // with phi2, we scale the Q to avoid precision issues
  10573. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  10574. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  10575. cb(Qcur, "Qcur", il);
  10576. Kcur = ggml_rope_ext(
  10577. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  10578. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10579. );
  10580. cb(Kcur, "Kcur", il);
  10581. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10582. model.layers[il].wo, model.layers[il].bo,
  10583. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10584. }
  10585. if (il == n_layer - 1) {
  10586. // skip computing output for unused tokens
  10587. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10588. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10589. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10590. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  10591. }
  10592. // FF
  10593. {
  10594. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  10595. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10596. NULL, NULL, NULL,
  10597. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10598. NULL,
  10599. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10600. cb(ffn_output, "ffn_out", il);
  10601. }
  10602. cur = ggml_add(ctx0, cur, ffn_output);
  10603. cur = ggml_add(ctx0, cur, inpL);
  10604. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10605. cb(cur, "l_out", il);
  10606. // input for next layer
  10607. inpL = cur;
  10608. }
  10609. cur = llm_build_norm(ctx0, inpL, hparams,
  10610. model.output_norm,
  10611. model.output_norm_b,
  10612. LLM_NORM, cb, -1);
  10613. cb(cur, "result_norm", -1);
  10614. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10615. cb(cur, "result_output_no_bias", -1);
  10616. cur = ggml_add(ctx0, cur, model.output_b);
  10617. cb(cur, "result_output", -1);
  10618. ggml_build_forward_expand(gf, cur);
  10619. return gf;
  10620. }
  10621. struct ggml_cgraph * build_phi3() {
  10622. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10623. const int64_t n_embd_head = hparams.n_embd_head_v;
  10624. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10625. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10626. struct ggml_tensor * cur;
  10627. struct ggml_tensor * inpL;
  10628. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10629. // inp_pos - contains the positions
  10630. struct ggml_tensor * inp_pos = build_inp_pos();
  10631. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10632. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  10633. for (int il = 0; il < n_layer; ++il) {
  10634. auto residual = inpL;
  10635. // self-attention
  10636. {
  10637. // rope freq factors for 128k context
  10638. struct ggml_tensor * rope_factors = build_rope_factors(il);
  10639. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  10640. model.layers[il].attn_norm,
  10641. NULL,
  10642. LLM_NORM_RMS, cb, il);
  10643. cb(attn_norm_output, "attn_norm", il);
  10644. struct ggml_tensor * Qcur = nullptr;
  10645. struct ggml_tensor * Kcur = nullptr;
  10646. struct ggml_tensor * Vcur = nullptr;
  10647. if (model.layers[il].wqkv) {
  10648. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  10649. cb(cur, "wqkv", il);
  10650. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  10651. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  10652. 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)));
  10653. }
  10654. else {
  10655. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  10656. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  10657. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  10658. }
  10659. cb(Qcur, "Qcur", il);
  10660. cb(Kcur, "Kcur", il);
  10661. cb(Vcur, "Vcur", il);
  10662. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10663. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10664. Qcur = ggml_rope_ext(
  10665. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  10666. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10667. );
  10668. cb(Qcur, "Qcur", il);
  10669. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  10670. cb(Qcur, "Qcur", il);
  10671. Kcur = ggml_rope_ext(
  10672. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  10673. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10674. );
  10675. cb(Kcur, "Kcur", il);
  10676. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10677. model.layers[il].wo, model.layers[il].bo,
  10678. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10679. }
  10680. if (il == n_layer - 1) {
  10681. // skip computing output for unused tokens
  10682. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  10683. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10684. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  10685. }
  10686. cur = ggml_add(ctx0, cur, residual);
  10687. residual = cur;
  10688. cur = llm_build_norm(ctx0, cur, hparams,
  10689. model.layers[il].ffn_norm, NULL,
  10690. LLM_NORM_RMS, cb, il);
  10691. cb(cur, "ffn_norm", il);
  10692. // FF
  10693. // special-case: the up and gate tensors are merged into a single tensor
  10694. // TOOD: support into llm_build_ffn
  10695. {
  10696. cur = llm_build_ffn(ctx0, lctx, cur,
  10697. model.layers[il].ffn_up, NULL, NULL,
  10698. NULL, NULL, NULL,
  10699. model.layers[il].ffn_down, NULL, NULL,
  10700. NULL,
  10701. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  10702. cb(cur, "ffn_out", il);
  10703. }
  10704. cur = ggml_add(ctx0, residual, cur);
  10705. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10706. cb(cur, "l_out", il);
  10707. // input for next layer
  10708. inpL = cur;
  10709. }
  10710. cur = llm_build_norm(ctx0, inpL, hparams,
  10711. model.output_norm,
  10712. NULL,
  10713. LLM_NORM_RMS, cb, -1);
  10714. cb(cur, "result_norm", -1);
  10715. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10716. cb(cur, "result_output", -1);
  10717. ggml_build_forward_expand(gf, cur);
  10718. return gf;
  10719. }
  10720. struct ggml_cgraph * build_plamo() {
  10721. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  10722. const int64_t n_embd_head = hparams.n_embd_head_v;
  10723. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10724. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10725. struct ggml_tensor * cur;
  10726. struct ggml_tensor * inpL;
  10727. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10728. // inp_pos - contains the positions
  10729. struct ggml_tensor * inp_pos = build_inp_pos();
  10730. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10731. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10732. for (int il = 0; il < n_layer; ++il) {
  10733. // norm
  10734. cur = llm_build_norm(ctx0, inpL, hparams,
  10735. model.layers[il].attn_norm, NULL,
  10736. LLM_NORM_RMS, cb, il);
  10737. cb(cur, "attn_norm", il);
  10738. struct ggml_tensor * attention_norm = cur;
  10739. // self-attention
  10740. {
  10741. // compute Q and K and RoPE them
  10742. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10743. cb(Qcur, "Qcur", il);
  10744. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10745. cb(Kcur, "Kcur", il);
  10746. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10747. cb(Vcur, "Vcur", il);
  10748. Qcur = ggml_rope_ext(
  10749. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  10750. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  10751. ext_factor, attn_factor, beta_fast, beta_slow);
  10752. cb(Qcur, "Qcur", il);
  10753. Kcur = ggml_rope_ext(
  10754. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  10755. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  10756. ext_factor, attn_factor, beta_fast, beta_slow);
  10757. cb(Kcur, "Kcur", il);
  10758. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10759. model.layers[il].wo, NULL,
  10760. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10761. }
  10762. struct ggml_tensor * sa_out = cur;
  10763. cur = attention_norm;
  10764. if (il == n_layer - 1) {
  10765. // skip computing output for unused tokens
  10766. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10767. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10768. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  10769. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10770. }
  10771. // feed-forward network
  10772. {
  10773. cur = llm_build_ffn(ctx0, lctx, cur,
  10774. model.layers[il].ffn_up, NULL, NULL,
  10775. model.layers[il].ffn_gate, NULL, NULL,
  10776. model.layers[il].ffn_down, NULL, NULL,
  10777. NULL,
  10778. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10779. cb(cur, "ffn_out", il);
  10780. }
  10781. cur = ggml_add(ctx0, cur, sa_out);
  10782. cur = ggml_add(ctx0, cur, inpL);
  10783. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10784. cb(cur, "l_out", il);
  10785. // input for next layer
  10786. inpL = cur;
  10787. }
  10788. cur = inpL;
  10789. cur = llm_build_norm(ctx0, cur, hparams,
  10790. model.output_norm, NULL,
  10791. LLM_NORM_RMS, cb, -1);
  10792. cb(cur, "result_norm", -1);
  10793. // lm_head
  10794. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10795. cb(cur, "result_output", -1);
  10796. ggml_build_forward_expand(gf, cur);
  10797. return gf;
  10798. }
  10799. struct ggml_cgraph * build_gpt2() {
  10800. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10801. const int64_t n_embd_head = hparams.n_embd_head_v;
  10802. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10803. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10804. struct ggml_tensor * cur;
  10805. struct ggml_tensor * pos;
  10806. struct ggml_tensor * inpL;
  10807. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10808. // inp_pos - contains the positions
  10809. struct ggml_tensor * inp_pos = build_inp_pos();
  10810. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10811. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10812. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10813. cb(pos, "pos_embd", -1);
  10814. inpL = ggml_add(ctx0, inpL, pos);
  10815. cb(inpL, "inpL", -1);
  10816. for (int il = 0; il < n_layer; ++il) {
  10817. cur = llm_build_norm(ctx0, inpL, hparams,
  10818. model.layers[il].attn_norm,
  10819. model.layers[il].attn_norm_b,
  10820. LLM_NORM, cb, il);
  10821. cb(cur, "attn_norm", il);
  10822. // self-attention
  10823. {
  10824. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10825. cb(cur, "wqkv", il);
  10826. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10827. cb(cur, "bqkv", il);
  10828. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10829. 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)));
  10830. 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)));
  10831. cb(Qcur, "Qcur", il);
  10832. cb(Kcur, "Kcur", il);
  10833. cb(Vcur, "Vcur", il);
  10834. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10835. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10836. model.layers[il].wo, model.layers[il].bo,
  10837. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10838. }
  10839. if (il == n_layer - 1) {
  10840. // skip computing output for unused tokens
  10841. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10842. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10843. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10844. }
  10845. // add the input
  10846. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10847. cb(ffn_inp, "ffn_inp", il);
  10848. // FF
  10849. {
  10850. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10851. model.layers[il].ffn_norm,
  10852. model.layers[il].ffn_norm_b,
  10853. LLM_NORM, cb, il);
  10854. cb(cur, "ffn_norm", il);
  10855. cur = llm_build_ffn(ctx0, lctx, cur,
  10856. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10857. NULL, NULL, NULL,
  10858. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10859. NULL,
  10860. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10861. cb(cur, "ffn_out", il);
  10862. }
  10863. cur = ggml_add(ctx0, cur, ffn_inp);
  10864. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10865. cb(cur, "l_out", il);
  10866. // input for next layer
  10867. inpL = cur;
  10868. }
  10869. cur = llm_build_norm(ctx0, inpL, hparams,
  10870. model.output_norm,
  10871. model.output_norm_b,
  10872. LLM_NORM, cb, -1);
  10873. cb(cur, "result_norm", -1);
  10874. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10875. cb(cur, "result_output", -1);
  10876. ggml_build_forward_expand(gf, cur);
  10877. return gf;
  10878. }
  10879. struct ggml_cgraph * build_codeshell() {
  10880. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10881. const int64_t n_embd_head = hparams.n_embd_head_v;
  10882. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10883. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10884. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10885. struct ggml_tensor * cur;
  10886. struct ggml_tensor * inpL;
  10887. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10888. // inp_pos - contains the positions
  10889. struct ggml_tensor * inp_pos = build_inp_pos();
  10890. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10891. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10892. for (int il = 0; il < n_layer; ++il) {
  10893. cur = llm_build_norm(ctx0, inpL, hparams,
  10894. model.layers[il].attn_norm,
  10895. model.layers[il].attn_norm_b,
  10896. LLM_NORM, cb, il);
  10897. cb(cur, "attn_norm", il);
  10898. // self-attention
  10899. {
  10900. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10901. cb(cur, "wqkv", il);
  10902. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10903. cb(cur, "bqkv", il);
  10904. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10905. 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)));
  10906. 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)));
  10907. cb(tmpq, "tmpq", il);
  10908. cb(tmpk, "tmpk", il);
  10909. cb(Vcur, "Vcur", il);
  10910. struct ggml_tensor * Qcur = ggml_rope_ext(
  10911. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10912. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10913. ext_factor, attn_factor, beta_fast, beta_slow
  10914. );
  10915. cb(Qcur, "Qcur", il);
  10916. struct ggml_tensor * Kcur = ggml_rope_ext(
  10917. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10918. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10919. ext_factor, attn_factor, beta_fast, beta_slow
  10920. );
  10921. cb(Kcur, "Kcur", il);
  10922. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10923. model.layers[il].wo, model.layers[il].bo,
  10924. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10925. }
  10926. if (il == n_layer - 1) {
  10927. // skip computing output for unused tokens
  10928. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10929. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10930. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10931. }
  10932. // add the input
  10933. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10934. cb(ffn_inp, "ffn_inp", il);
  10935. // FF
  10936. {
  10937. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10938. model.layers[il].ffn_norm,
  10939. model.layers[il].ffn_norm_b,
  10940. LLM_NORM, cb, il);
  10941. cb(cur, "ffn_norm", il);
  10942. cur = llm_build_ffn(ctx0, lctx, cur,
  10943. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10944. NULL, NULL, NULL,
  10945. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10946. NULL,
  10947. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10948. cb(cur, "ffn_out", il);
  10949. }
  10950. cur = ggml_add(ctx0, cur, ffn_inp);
  10951. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10952. cb(cur, "l_out", il);
  10953. // input for next layer
  10954. inpL = cur;
  10955. }
  10956. cur = llm_build_norm(ctx0, inpL, hparams,
  10957. model.output_norm,
  10958. model.output_norm_b,
  10959. LLM_NORM, cb, -1);
  10960. cb(cur, "result_norm", -1);
  10961. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10962. cb(cur, "result_output", -1);
  10963. ggml_build_forward_expand(gf, cur);
  10964. return gf;
  10965. }
  10966. struct ggml_cgraph * build_orion() {
  10967. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10968. const int64_t n_embd_head = hparams.n_embd_head_v;
  10969. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10970. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10971. struct ggml_tensor * cur;
  10972. struct ggml_tensor * inpL;
  10973. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10974. // inp_pos - contains the positions
  10975. struct ggml_tensor * inp_pos = build_inp_pos();
  10976. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10977. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10978. for (int il = 0; il < n_layer; ++il) {
  10979. struct ggml_tensor * inpSA = inpL;
  10980. // norm
  10981. cur = llm_build_norm(ctx0, inpL, hparams,
  10982. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  10983. LLM_NORM, cb, il);
  10984. cb(cur, "attn_norm", il);
  10985. // self-attention
  10986. {
  10987. // compute Q and K and RoPE them
  10988. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10989. cb(Qcur, "Qcur", il);
  10990. // if (model.layers[il].bq) {
  10991. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10992. // cb(Qcur, "Qcur", il);
  10993. // }
  10994. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10995. cb(Kcur, "Kcur", il);
  10996. // if (model.layers[il].bk) {
  10997. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10998. // cb(Kcur, "Kcur", il);
  10999. // }
  11000. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11001. cb(Vcur, "Vcur", il);
  11002. // if (model.layers[il].bv) {
  11003. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11004. // cb(Vcur, "Vcur", il);
  11005. // }
  11006. Qcur = ggml_rope_ext(
  11007. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11008. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11009. ext_factor, attn_factor, beta_fast, beta_slow
  11010. );
  11011. cb(Qcur, "Qcur", il);
  11012. Kcur = ggml_rope_ext(
  11013. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11014. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11015. ext_factor, attn_factor, beta_fast, beta_slow
  11016. );
  11017. cb(Kcur, "Kcur", il);
  11018. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11019. model.layers[il].wo, NULL,
  11020. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11021. }
  11022. if (il == n_layer - 1) {
  11023. // skip computing output for unused tokens
  11024. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11025. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11026. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11027. }
  11028. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11029. cb(ffn_inp, "ffn_inp", il);
  11030. // feed-forward network
  11031. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11032. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11033. LLM_NORM, cb, il);
  11034. cb(cur, "ffn_norm", il);
  11035. cur = llm_build_ffn(ctx0, lctx, cur,
  11036. model.layers[il].ffn_up, NULL, NULL,
  11037. model.layers[il].ffn_gate, NULL, NULL,
  11038. model.layers[il].ffn_down, NULL, NULL,
  11039. NULL,
  11040. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11041. cb(cur, "ffn_out", il);
  11042. cur = ggml_add(ctx0, cur, ffn_inp);
  11043. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11044. cb(cur, "l_out", il);
  11045. // input for next layer
  11046. inpL = cur;
  11047. }
  11048. cur = inpL;
  11049. cur = llm_build_norm(ctx0, cur, hparams,
  11050. model.output_norm, model.output_norm_b,
  11051. LLM_NORM, cb, -1);
  11052. cb(cur, "result_norm", -1);
  11053. // lm_head
  11054. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11055. cb(cur, "result_output", -1);
  11056. ggml_build_forward_expand(gf, cur);
  11057. return gf;
  11058. }
  11059. struct ggml_cgraph * build_internlm2() {
  11060. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11061. const int64_t n_embd_head = hparams.n_embd_head_v;
  11062. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11063. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11064. struct ggml_tensor * cur;
  11065. struct ggml_tensor * inpL;
  11066. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11067. // inp_pos - contains the positions
  11068. struct ggml_tensor * inp_pos = build_inp_pos();
  11069. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11070. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11071. for (int il = 0; il < n_layer; ++il) {
  11072. struct ggml_tensor * inpSA = inpL;
  11073. // norm
  11074. cur = llm_build_norm(ctx0, inpL, hparams,
  11075. model.layers[il].attn_norm, NULL,
  11076. LLM_NORM_RMS, cb, il);
  11077. cb(cur, "attn_norm", il);
  11078. // self-attention
  11079. {
  11080. // compute Q and K and RoPE them
  11081. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11082. cb(Qcur, "Qcur", il);
  11083. if (model.layers[il].bq) {
  11084. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11085. cb(Qcur, "Qcur", il);
  11086. }
  11087. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11088. cb(Kcur, "Kcur", il);
  11089. if (model.layers[il].bk) {
  11090. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11091. cb(Kcur, "Kcur", il);
  11092. }
  11093. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11094. cb(Vcur, "Vcur", il);
  11095. if (model.layers[il].bv) {
  11096. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11097. cb(Vcur, "Vcur", il);
  11098. }
  11099. Qcur = ggml_rope_ext(
  11100. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11101. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11102. ext_factor, attn_factor, beta_fast, beta_slow
  11103. );
  11104. cb(Qcur, "Qcur", il);
  11105. Kcur = ggml_rope_ext(
  11106. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11107. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11108. ext_factor, attn_factor, beta_fast, beta_slow
  11109. );
  11110. cb(Kcur, "Kcur", il);
  11111. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11112. model.layers[il].wo, model.layers[il].bo,
  11113. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11114. }
  11115. if (il == n_layer - 1) {
  11116. // skip computing output for unused tokens
  11117. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11118. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11119. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11120. }
  11121. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11122. cb(ffn_inp, "ffn_inp", il);
  11123. // feed-forward network
  11124. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11125. model.layers[il].ffn_norm, NULL,
  11126. LLM_NORM_RMS, cb, il);
  11127. cb(cur, "ffn_norm", il);
  11128. cur = llm_build_ffn(ctx0, lctx, cur,
  11129. model.layers[il].ffn_up, NULL, NULL,
  11130. model.layers[il].ffn_gate, NULL, NULL,
  11131. model.layers[il].ffn_down, NULL, NULL,
  11132. NULL,
  11133. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11134. cb(cur, "ffn_out", il);
  11135. cur = ggml_add(ctx0, cur, ffn_inp);
  11136. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11137. cb(cur, "l_out", il);
  11138. // input for next layer
  11139. inpL = cur;
  11140. }
  11141. cur = inpL;
  11142. cur = llm_build_norm(ctx0, cur, hparams,
  11143. model.output_norm, NULL,
  11144. LLM_NORM_RMS, cb, -1);
  11145. cb(cur, "result_norm", -1);
  11146. // lm_head
  11147. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11148. cb(cur, "result_output", -1);
  11149. ggml_build_forward_expand(gf, cur);
  11150. return gf;
  11151. }
  11152. // ref: https://arxiv.org/abs/2203.03466
  11153. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  11154. // based on the original build_llama() function
  11155. struct ggml_cgraph * build_minicpm() {
  11156. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11157. const int64_t n_embd_head = hparams.n_embd_head_v;
  11158. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11159. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11160. const int64_t n_embd = hparams.n_embd;
  11161. //TODO: if the model varies, these parameters need to be read from the model
  11162. const int64_t n_embd_base = 256;
  11163. const float scale_embd = 12.0f;
  11164. const float scale_depth = 1.4f;
  11165. struct ggml_tensor * cur;
  11166. struct ggml_tensor * inpL;
  11167. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11168. // scale the input embeddings
  11169. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11170. cb(inpL, "inp_scaled", -1);
  11171. // inp_pos - contains the positions
  11172. struct ggml_tensor * inp_pos = build_inp_pos();
  11173. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11174. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11175. for (int il = 0; il < n_layer; ++il) {
  11176. struct ggml_tensor * inpSA = inpL;
  11177. // norm
  11178. cur = llm_build_norm(ctx0, inpL, hparams,
  11179. model.layers[il].attn_norm, NULL,
  11180. LLM_NORM_RMS, cb, il);
  11181. cb(cur, "attn_norm", il);
  11182. // self-attention
  11183. {
  11184. // compute Q and K and RoPE them
  11185. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11186. cb(Qcur, "Qcur", il);
  11187. if (model.layers[il].bq) {
  11188. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11189. cb(Qcur, "Qcur", il);
  11190. }
  11191. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11192. cb(Kcur, "Kcur", il);
  11193. if (model.layers[il].bk) {
  11194. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11195. cb(Kcur, "Kcur", il);
  11196. }
  11197. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11198. cb(Vcur, "Vcur", il);
  11199. if (model.layers[il].bv) {
  11200. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11201. cb(Vcur, "Vcur", il);
  11202. }
  11203. Qcur = ggml_rope_ext(
  11204. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11205. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11206. ext_factor, attn_factor, beta_fast, beta_slow
  11207. );
  11208. cb(Qcur, "Qcur", il);
  11209. Kcur = ggml_rope_ext(
  11210. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11211. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11212. ext_factor, attn_factor, beta_fast, beta_slow
  11213. );
  11214. cb(Kcur, "Kcur", il);
  11215. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11216. model.layers[il].wo, model.layers[il].bo,
  11217. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11218. }
  11219. if (il == n_layer - 1) {
  11220. // skip computing output for unused tokens
  11221. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11222. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11223. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11224. }
  11225. // scale_res - scale the hidden states for residual connection
  11226. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11227. cur = ggml_scale(ctx0, cur, scale_res);
  11228. cb(cur, "hidden_scaled", -1);
  11229. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11230. cb(ffn_inp, "ffn_inp", il);
  11231. // feed-forward network
  11232. {
  11233. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11234. model.layers[il].ffn_norm, NULL,
  11235. LLM_NORM_RMS, cb, il);
  11236. cb(cur, "ffn_norm", il);
  11237. cur = llm_build_ffn(ctx0, lctx, cur,
  11238. model.layers[il].ffn_up, NULL, NULL,
  11239. model.layers[il].ffn_gate, NULL, NULL,
  11240. model.layers[il].ffn_down, NULL, NULL,
  11241. NULL,
  11242. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11243. cb(cur, "ffn_out", il);
  11244. }
  11245. // scale the hidden states for residual connection
  11246. cur = ggml_scale(ctx0, cur, scale_res);
  11247. cb(cur, "hidden_scaled_ffn", -1);
  11248. cur = ggml_add(ctx0, cur, ffn_inp);
  11249. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11250. cb(cur, "l_out", il);
  11251. // input for next layer
  11252. inpL = cur;
  11253. }
  11254. cur = inpL;
  11255. cur = llm_build_norm(ctx0, cur, hparams,
  11256. model.output_norm, NULL,
  11257. LLM_NORM_RMS, cb, -1);
  11258. cb(cur, "result_norm", -1);
  11259. // lm_head scaling
  11260. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11261. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11262. cb(cur, "lmhead_scaling", -1);
  11263. // lm_head
  11264. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11265. cb(cur, "result_output", -1);
  11266. ggml_build_forward_expand(gf, cur);
  11267. return gf;
  11268. }
  11269. struct ggml_cgraph * build_minicpm3() {
  11270. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11271. //TODO: if the model varies, these parameters need to be read from the model
  11272. const int64_t n_embd_base = 256;
  11273. const float scale_embd = 12.0f;
  11274. const float scale_depth = 1.4f;
  11275. const float kq_scale = 1.0f / sqrtf(float(hparams.n_embd_head_k));
  11276. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  11277. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  11278. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  11279. struct ggml_tensor * cur;
  11280. struct ggml_tensor * inpL;
  11281. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11282. // scale the input embeddings
  11283. inpL = ggml_scale(ctx0, inpL, scale_embd);
  11284. cb(inpL, "inp_scaled", -1);
  11285. // inp_pos - contains the positions
  11286. struct ggml_tensor * inp_pos = build_inp_pos();
  11287. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11288. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11289. for (int il = 0; il < n_layer; ++il) {
  11290. struct ggml_tensor * inpSA = inpL;
  11291. struct ggml_tensor * rope_factors = build_rope_factors(il);
  11292. // norm
  11293. cur = llm_build_norm(ctx0, inpL, hparams,
  11294. model.layers[il].attn_norm, NULL,
  11295. LLM_NORM_RMS, cb, il);
  11296. cb(cur, "attn_norm", il);
  11297. // self_attention
  11298. {
  11299. struct ggml_tensor * q = NULL;
  11300. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  11301. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  11302. cb(q, "q", il);
  11303. q = llm_build_norm(ctx0, q, hparams,
  11304. model.layers[il].attn_q_a_norm, NULL,
  11305. LLM_NORM_RMS, cb, il);
  11306. cb(q, "q", il);
  11307. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  11308. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  11309. cb(q, "q", il);
  11310. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11311. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  11312. ggml_row_size(q->type, hparams.n_embd_head_k),
  11313. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11314. 0);
  11315. cb(q_nope, "q_nope", il);
  11316. // and {n_head * n_embd_head_qk_rope, n_tokens}
  11317. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  11318. ggml_row_size(q->type, hparams.n_embd_head_k),
  11319. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11320. ggml_row_size(q->type, n_embd_head_qk_nope));
  11321. cb(q_pe, "q_pe", il);
  11322. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  11323. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  11324. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  11325. // split into {kv_lora_rank, n_tokens}
  11326. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  11327. kv_pe_compresseed->nb[1],
  11328. 0);
  11329. cb(kv_compressed, "kv_compressed", il);
  11330. // and {n_embd_head_qk_rope, n_tokens}
  11331. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  11332. kv_pe_compresseed->nb[1],
  11333. kv_pe_compresseed->nb[1],
  11334. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  11335. cb(k_pe, "k_pe", il);
  11336. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  11337. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  11338. model.layers[il].attn_kv_a_norm, NULL,
  11339. LLM_NORM_RMS, cb, il);
  11340. cb(kv_compressed, "kv_compressed", il);
  11341. // {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}
  11342. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  11343. cb(kv, "kv", il);
  11344. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11345. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  11346. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  11347. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11348. 0);
  11349. cb(k_nope, "k_nope", il);
  11350. // and {n_head * n_embd_head_v, n_tokens}
  11351. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  11352. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11353. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  11354. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  11355. cb(v_states, "v_states", il);
  11356. v_states = ggml_cont(ctx0, v_states);
  11357. cb(v_states, "v_states", il);
  11358. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  11359. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  11360. 0);
  11361. cb(v_states, "v_states", il);
  11362. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11363. q_pe = ggml_rope_ext(
  11364. ctx0, q_pe, inp_pos, rope_factors,
  11365. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11366. ext_factor, attn_factor, beta_fast, beta_slow
  11367. );
  11368. cb(q_pe, "q_pe", il);
  11369. // shared RoPE key
  11370. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11371. k_pe = ggml_rope_ext(
  11372. ctx0, k_pe, inp_pos, rope_factors,
  11373. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11374. ext_factor, attn_factor, beta_fast, beta_slow
  11375. );
  11376. cb(k_pe, "k_pe", il);
  11377. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  11378. cb(q_states, "q_states", il);
  11379. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  11380. cb(k_states, "k_states", il);
  11381. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11382. model.layers[il].wo, NULL,
  11383. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  11384. }
  11385. if (il == n_layer - 1) {
  11386. // skip computing output for unused tokens
  11387. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11388. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11389. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11390. }
  11391. // scale_res - scale the hidden states for residual connection
  11392. const float scale_res = scale_depth/sqrtf(float(n_layer));
  11393. cur = ggml_scale(ctx0, cur, scale_res);
  11394. cb(cur, "hidden_scaled", il);
  11395. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11396. cb(ffn_inp, "ffn_inp", il);
  11397. // feed-forward network
  11398. {
  11399. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11400. model.layers[il].ffn_norm, NULL,
  11401. LLM_NORM_RMS, cb, il);
  11402. cb(cur, "ffn_norm", il);
  11403. cur = llm_build_ffn(ctx0, lctx, cur,
  11404. model.layers[il].ffn_up, NULL, NULL,
  11405. model.layers[il].ffn_gate, NULL, NULL,
  11406. model.layers[il].ffn_down, NULL, NULL,
  11407. NULL,
  11408. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11409. cb(cur, "ffn_out", il);
  11410. }
  11411. // scale the hidden states for residual connection
  11412. cur = ggml_scale(ctx0, cur, scale_res);
  11413. cb(cur, "hidden_scaled_ffn", il);
  11414. cur = ggml_add(ctx0, cur, ffn_inp);
  11415. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11416. cb(cur, "l_out", il);
  11417. // input for next layer
  11418. inpL = cur;
  11419. }
  11420. cur = inpL;
  11421. cur = llm_build_norm(ctx0, cur, hparams,
  11422. model.output_norm, NULL,
  11423. LLM_NORM_RMS, cb, -1);
  11424. cb(cur, "result_norm", -1);
  11425. // lm_head scaling
  11426. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  11427. cur = ggml_scale(ctx0, cur, scale_lmhead);
  11428. cb(cur, "lmhead_scaling", -1);
  11429. // lm_head
  11430. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11431. cb(cur, "result_output", -1);
  11432. ggml_build_forward_expand(gf, cur);
  11433. return gf;
  11434. }
  11435. struct ggml_cgraph * build_gemma() {
  11436. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11437. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11438. struct ggml_tensor * cur;
  11439. struct ggml_tensor * inpL;
  11440. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11441. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11442. cb(inpL, "inp_scaled", -1);
  11443. // inp_pos - contains the positions
  11444. struct ggml_tensor * inp_pos = build_inp_pos();
  11445. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11446. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11447. for (int il = 0; il < n_layer; ++il) {
  11448. // norm
  11449. cur = llm_build_norm(ctx0, inpL, hparams,
  11450. model.layers[il].attn_norm, NULL,
  11451. LLM_NORM_RMS, cb, il);
  11452. cb(cur, "attn_norm", il);
  11453. // self-attention
  11454. {
  11455. // compute Q and K and RoPE them
  11456. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11457. cb(Qcur, "Qcur", il);
  11458. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11459. cb(Kcur, "Kcur", il);
  11460. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11461. cb(Vcur, "Vcur", il);
  11462. Qcur = ggml_rope_ext(
  11463. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11464. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11465. ext_factor, attn_factor, beta_fast, beta_slow);
  11466. cb(Qcur, "Qcur", il);
  11467. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  11468. cb(Qcur, "Qcur_scaled", il);
  11469. Kcur = ggml_rope_ext(
  11470. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11471. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11472. ext_factor, attn_factor, beta_fast, beta_slow);
  11473. cb(Kcur, "Kcur", il);
  11474. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11475. model.layers[il].wo, NULL,
  11476. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11477. }
  11478. if (il == n_layer - 1) {
  11479. // skip computing output for unused tokens
  11480. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11481. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11482. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11483. }
  11484. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11485. cb(sa_out, "sa_out", il);
  11486. cur = llm_build_norm(ctx0, sa_out, hparams,
  11487. model.layers[il].ffn_norm, NULL,
  11488. LLM_NORM_RMS, cb, il);
  11489. cb(cur, "ffn_norm", il);
  11490. // feed-forward network
  11491. {
  11492. cur = llm_build_ffn(ctx0, lctx, cur,
  11493. model.layers[il].ffn_up, NULL, NULL,
  11494. model.layers[il].ffn_gate, NULL, NULL,
  11495. model.layers[il].ffn_down, NULL, NULL,
  11496. NULL,
  11497. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11498. cb(cur, "ffn_out", il);
  11499. }
  11500. cur = ggml_add(ctx0, cur, sa_out);
  11501. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11502. cb(cur, "l_out", il);
  11503. // input for next layer
  11504. inpL = cur;
  11505. }
  11506. cur = inpL;
  11507. cur = llm_build_norm(ctx0, cur, hparams,
  11508. model.output_norm, NULL,
  11509. LLM_NORM_RMS, cb, -1);
  11510. cb(cur, "result_norm", -1);
  11511. // lm_head
  11512. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11513. cb(cur, "result_output", -1);
  11514. ggml_build_forward_expand(gf, cur);
  11515. return gf;
  11516. }
  11517. struct ggml_cgraph * build_gemma2() {
  11518. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11519. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  11520. struct ggml_tensor * cur;
  11521. struct ggml_tensor * inpL;
  11522. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11523. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  11524. cb(inpL, "inp_scaled", -1);
  11525. // inp_pos - contains the positions
  11526. struct ggml_tensor * inp_pos = build_inp_pos();
  11527. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11528. // gemma 2 requires different mask for layers using sliding window (SWA)
  11529. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  11530. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  11531. for (int il = 0; il < n_layer; ++il) {
  11532. // (il % 2) layers use SWA
  11533. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  11534. // norm
  11535. cur = llm_build_norm(ctx0, inpL, hparams,
  11536. model.layers[il].attn_norm, NULL,
  11537. LLM_NORM_RMS, cb, il);
  11538. cb(cur, "attn_norm", il);
  11539. // self-attention
  11540. {
  11541. // compute Q and K and RoPE them
  11542. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11543. cb(Qcur, "Qcur", il);
  11544. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11545. cb(Kcur, "Kcur", il);
  11546. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11547. cb(Vcur, "Vcur", il);
  11548. Qcur = ggml_rope_ext(
  11549. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  11550. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11551. ext_factor, attn_factor, beta_fast, beta_slow);
  11552. cb(Qcur, "Qcur", il);
  11553. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  11554. switch (model.type) {
  11555. case e_model::MODEL_2B:
  11556. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  11557. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  11558. default: GGML_ABORT("fatal error");
  11559. };
  11560. cb(Qcur, "Qcur_scaled", il);
  11561. Kcur = ggml_rope_ext(
  11562. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  11563. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11564. ext_factor, attn_factor, beta_fast, beta_slow);
  11565. cb(Kcur, "Kcur", il);
  11566. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11567. model.layers[il].wo, NULL,
  11568. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  11569. }
  11570. cur = llm_build_norm(ctx0, cur, hparams,
  11571. model.layers[il].attn_post_norm, NULL,
  11572. LLM_NORM_RMS, cb, il);
  11573. cb(cur, "attn_post_norm", il);
  11574. if (il == n_layer - 1) {
  11575. // skip computing output for unused tokens
  11576. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11577. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11578. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11579. }
  11580. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  11581. cb(sa_out, "sa_out", il);
  11582. cur = llm_build_norm(ctx0, sa_out, hparams,
  11583. model.layers[il].ffn_norm, NULL,
  11584. LLM_NORM_RMS, cb, il);
  11585. cb(cur, "ffn_norm", il);
  11586. // feed-forward network
  11587. {
  11588. cur = llm_build_ffn(ctx0, lctx, cur,
  11589. model.layers[il].ffn_up, NULL, NULL,
  11590. model.layers[il].ffn_gate, NULL, NULL,
  11591. model.layers[il].ffn_down, NULL, NULL,
  11592. NULL,
  11593. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  11594. cb(cur, "ffn_out", il);
  11595. }
  11596. cur = llm_build_norm(ctx0, cur, hparams,
  11597. model.layers[il].ffn_post_norm, NULL,
  11598. LLM_NORM_RMS, cb, -1);
  11599. cb(cur, "ffn_post_norm", -1);
  11600. cur = ggml_add(ctx0, cur, sa_out);
  11601. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11602. cb(cur, "l_out", il);
  11603. // input for next layer
  11604. inpL = cur;
  11605. }
  11606. cur = inpL;
  11607. cur = llm_build_norm(ctx0, cur, hparams,
  11608. model.output_norm, NULL,
  11609. LLM_NORM_RMS, cb, -1);
  11610. cb(cur, "result_norm", -1);
  11611. // lm_head
  11612. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11613. // final logit soft-capping
  11614. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  11615. cur = ggml_tanh(ctx0, cur);
  11616. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  11617. cb(cur, "result_output", -1);
  11618. ggml_build_forward_expand(gf, cur);
  11619. return gf;
  11620. }
  11621. struct ggml_cgraph * build_starcoder2() {
  11622. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11623. const int64_t n_embd_head = hparams.n_embd_head_v;
  11624. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11625. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11626. struct ggml_tensor * cur;
  11627. struct ggml_tensor * inpL;
  11628. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11629. // inp_pos - contains the positions
  11630. struct ggml_tensor * inp_pos = build_inp_pos();
  11631. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11632. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11633. for (int il = 0; il < n_layer; ++il) {
  11634. struct ggml_tensor * inpSA = inpL;
  11635. // norm
  11636. cur = llm_build_norm(ctx0, inpL, hparams,
  11637. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  11638. LLM_NORM, cb, il);
  11639. cb(cur, "attn_norm", il);
  11640. // self-attention
  11641. {
  11642. // compute Q and K and RoPE them
  11643. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11644. cb(Qcur, "Qcur", il);
  11645. if (model.layers[il].bq) {
  11646. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11647. cb(Qcur, "Qcur", il);
  11648. }
  11649. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11650. cb(Kcur, "Kcur", il);
  11651. if (model.layers[il].bk) {
  11652. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11653. cb(Kcur, "Kcur", il);
  11654. }
  11655. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11656. cb(Vcur, "Vcur", il);
  11657. if (model.layers[il].bv) {
  11658. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11659. cb(Vcur, "Vcur", il);
  11660. }
  11661. Qcur = ggml_rope_ext(
  11662. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11663. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11664. ext_factor, attn_factor, beta_fast, beta_slow
  11665. );
  11666. cb(Qcur, "Qcur", il);
  11667. Kcur = ggml_rope_ext(
  11668. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11669. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11670. ext_factor, attn_factor, beta_fast, beta_slow
  11671. );
  11672. cb(Kcur, "Kcur", il);
  11673. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11674. model.layers[il].wo, model.layers[il].bo,
  11675. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11676. }
  11677. if (il == n_layer - 1) {
  11678. // skip computing output for unused tokens
  11679. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11680. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11681. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11682. }
  11683. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11684. cb(ffn_inp, "ffn_inp", il);
  11685. // feed-forward network
  11686. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11687. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  11688. LLM_NORM, cb, il);
  11689. cb(cur, "ffn_norm", il);
  11690. cur = llm_build_ffn(ctx0, lctx, cur,
  11691. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11692. NULL, NULL, NULL,
  11693. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11694. NULL,
  11695. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11696. cb(cur, "ffn_out", il);
  11697. cur = ggml_add(ctx0, cur, ffn_inp);
  11698. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11699. cb(cur, "l_out", il);
  11700. // input for next layer
  11701. inpL = cur;
  11702. }
  11703. cur = inpL;
  11704. cur = llm_build_norm(ctx0, cur, hparams,
  11705. model.output_norm, model.output_norm_b,
  11706. LLM_NORM, cb, -1);
  11707. cb(cur, "result_norm", -1);
  11708. // lm_head
  11709. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11710. cb(cur, "result_output", -1);
  11711. ggml_build_forward_expand(gf, cur);
  11712. return gf;
  11713. }
  11714. struct ggml_cgraph * build_mamba() {
  11715. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11716. struct ggml_tensor * cur;
  11717. struct ggml_tensor * inpL;
  11718. // {n_embd, n_tokens}
  11719. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11720. struct ggml_tensor * state_copy = build_inp_s_copy();
  11721. struct ggml_tensor * state_mask = build_inp_s_mask();
  11722. for (int il = 0; il < n_layer; ++il) {
  11723. // norm
  11724. cur = llm_build_norm(ctx0, inpL, hparams,
  11725. model.layers[il].attn_norm, NULL,
  11726. LLM_NORM_RMS, cb, il);
  11727. cb(cur, "attn_norm", il);
  11728. cur = llm_build_mamba(ctx0, lctx, batch, gf, cur,
  11729. state_copy, state_mask,
  11730. kv_head, n_kv, cb, il);
  11731. if (il == n_layer - 1) {
  11732. // skip computing output for unused tokens
  11733. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11734. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11735. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11736. }
  11737. // residual
  11738. cur = ggml_add(ctx0, cur, inpL);
  11739. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11740. cb(cur, "l_out", il);
  11741. // input for next layer
  11742. inpL = cur;
  11743. }
  11744. // final rmsnorm
  11745. cur = llm_build_norm(ctx0, inpL, hparams,
  11746. model.output_norm, NULL,
  11747. LLM_NORM_RMS, cb, -1);
  11748. cb(cur, "result_norm", -1);
  11749. // lm_head
  11750. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11751. cb(cur, "result_output", -1);
  11752. ggml_build_forward_expand(gf, cur);
  11753. return gf;
  11754. }
  11755. struct ggml_cgraph * build_command_r() {
  11756. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11757. const int64_t n_embd_head = hparams.n_embd_head_v;
  11758. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11759. const float f_logit_scale = hparams.f_logit_scale;
  11760. struct ggml_tensor * cur;
  11761. struct ggml_tensor * inpL;
  11762. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11763. // inp_pos - contains the positions
  11764. struct ggml_tensor * inp_pos = build_inp_pos();
  11765. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11766. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11767. for (int il = 0; il < n_layer; ++il) {
  11768. // norm
  11769. cur = llm_build_norm(ctx0, inpL, hparams,
  11770. model.layers[il].attn_norm, NULL,
  11771. LLM_NORM, cb, il);
  11772. cb(cur, "attn_norm", il);
  11773. struct ggml_tensor * ffn_inp = cur;
  11774. // self-attention
  11775. {
  11776. // compute Q and K and RoPE them
  11777. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11778. cb(Qcur, "Qcur", il);
  11779. if (model.layers[il].bq) {
  11780. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11781. cb(Qcur, "Qcur", il);
  11782. }
  11783. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11784. cb(Kcur, "Kcur", il);
  11785. if (model.layers[il].bk) {
  11786. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11787. cb(Kcur, "Kcur", il);
  11788. }
  11789. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11790. cb(Vcur, "Vcur", il);
  11791. if (model.layers[il].bv) {
  11792. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11793. cb(Vcur, "Vcur", il);
  11794. }
  11795. if (model.layers[il].attn_q_norm) {
  11796. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  11797. ggml_element_size(Qcur) * n_embd_head,
  11798. ggml_element_size(Qcur) * n_embd_head * n_head,
  11799. 0);
  11800. cb(Qcur, "Qcur", il);
  11801. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  11802. ggml_element_size(Kcur) * n_embd_head,
  11803. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  11804. 0);
  11805. cb(Kcur, "Kcur", il);
  11806. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  11807. model.layers[il].attn_q_norm,
  11808. NULL,
  11809. LLM_NORM, cb, il);
  11810. cb(Qcur, "Qcur", il);
  11811. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  11812. model.layers[il].attn_k_norm,
  11813. NULL,
  11814. LLM_NORM, cb, il);
  11815. cb(Kcur, "Kcur", il);
  11816. }
  11817. Qcur = ggml_rope_ext(
  11818. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11819. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11820. ext_factor, attn_factor, beta_fast, beta_slow
  11821. );
  11822. cb(Qcur, "Qcur", il);
  11823. Kcur = ggml_rope_ext(
  11824. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11825. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11826. ext_factor, attn_factor, beta_fast, beta_slow
  11827. );
  11828. cb(Kcur, "Kcur", il);
  11829. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11830. model.layers[il].wo, model.layers[il].bo,
  11831. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11832. }
  11833. if (il == n_layer - 1) {
  11834. // skip computing output for unused tokens
  11835. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11836. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11837. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11838. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  11839. }
  11840. struct ggml_tensor * attn_out = cur;
  11841. // feed-forward network
  11842. {
  11843. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  11844. model.layers[il].ffn_up, NULL, NULL,
  11845. model.layers[il].ffn_gate, NULL, NULL,
  11846. model.layers[il].ffn_down, NULL, NULL,
  11847. NULL,
  11848. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11849. cb(cur, "ffn_out", il);
  11850. }
  11851. // add together residual + FFN + self-attention
  11852. cur = ggml_add(ctx0, cur, inpL);
  11853. cur = ggml_add(ctx0, cur, attn_out);
  11854. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11855. cb(cur, "l_out", il);
  11856. // input for next layer
  11857. inpL = cur;
  11858. }
  11859. cur = inpL;
  11860. cur = llm_build_norm(ctx0, cur, hparams,
  11861. model.output_norm, NULL,
  11862. LLM_NORM, cb, -1);
  11863. cb(cur, "result_norm", -1);
  11864. // lm_head
  11865. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11866. if (f_logit_scale) {
  11867. cur = ggml_scale(ctx0, cur, f_logit_scale);
  11868. }
  11869. cb(cur, "result_output", -1);
  11870. ggml_build_forward_expand(gf, cur);
  11871. return gf;
  11872. }
  11873. // ref: https://allenai.org/olmo
  11874. // based on the original build_llama() function, changes:
  11875. // * non-parametric layer norm
  11876. // * clamp qkv
  11877. // * removed bias
  11878. // * removed MoE
  11879. struct ggml_cgraph * build_olmo() {
  11880. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11881. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11882. int32_t n_tokens = this->n_tokens;
  11883. const int64_t n_embd_head = hparams.n_embd_head_v;
  11884. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11885. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11886. struct ggml_tensor * cur;
  11887. struct ggml_tensor * inpL;
  11888. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11889. // inp_pos - contains the positions
  11890. struct ggml_tensor * inp_pos = build_inp_pos();
  11891. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11892. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11893. for (int il = 0; il < n_layer; ++il) {
  11894. struct ggml_tensor * inpSA = inpL;
  11895. // norm
  11896. cur = llm_build_norm(ctx0, inpL, hparams,
  11897. NULL, NULL,
  11898. LLM_NORM, cb, il);
  11899. cb(cur, "attn_norm", il);
  11900. // self-attention
  11901. {
  11902. // compute Q and K and RoPE them
  11903. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11904. cb(Qcur, "Qcur", il);
  11905. if (hparams.f_clamp_kqv > 0.0f) {
  11906. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  11907. cb(Qcur, "Qcur", il);
  11908. }
  11909. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11910. cb(Kcur, "Kcur", il);
  11911. if (hparams.f_clamp_kqv > 0.0f) {
  11912. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  11913. cb(Kcur, "Kcur", il);
  11914. }
  11915. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11916. cb(Vcur, "Vcur", il);
  11917. if (hparams.f_clamp_kqv > 0.0f) {
  11918. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  11919. cb(Vcur, "Vcur", il);
  11920. }
  11921. Qcur = ggml_rope_ext(
  11922. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11923. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11924. ext_factor, attn_factor, beta_fast, beta_slow
  11925. );
  11926. cb(Qcur, "Qcur", il);
  11927. Kcur = ggml_rope_ext(
  11928. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11929. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11930. ext_factor, attn_factor, beta_fast, beta_slow
  11931. );
  11932. cb(Kcur, "Kcur", il);
  11933. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11934. model.layers[il].wo, nullptr,
  11935. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11936. }
  11937. if (il == n_layer - 1) {
  11938. // skip computing output for unused tokens
  11939. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11940. n_tokens = n_outputs;
  11941. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11942. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11943. }
  11944. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11945. cb(ffn_inp, "ffn_inp", il);
  11946. // feed-forward network
  11947. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11948. NULL, NULL,
  11949. LLM_NORM, cb, il);
  11950. cb(cur, "ffn_norm", il);
  11951. cur = llm_build_ffn(ctx0, lctx, cur,
  11952. model.layers[il].ffn_up, NULL, NULL,
  11953. model.layers[il].ffn_gate, NULL, NULL,
  11954. model.layers[il].ffn_down, NULL, NULL,
  11955. NULL,
  11956. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11957. cb(cur, "ffn_out", il);
  11958. cur = ggml_add(ctx0, cur, ffn_inp);
  11959. cb(cur, "ffn_out", il);
  11960. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11961. cb(cur, "l_out", il);
  11962. // input for next layer
  11963. inpL = cur;
  11964. }
  11965. cur = inpL;
  11966. cur = llm_build_norm(ctx0, cur, hparams,
  11967. NULL, NULL,
  11968. LLM_NORM, cb, -1);
  11969. cb(cur, "result_norm", -1);
  11970. // lm_head
  11971. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11972. cb(cur, "result_output", -1);
  11973. ggml_build_forward_expand(gf, cur);
  11974. return gf;
  11975. }
  11976. // based on the build_qwen2moe() function, changes:
  11977. // * removed shared experts
  11978. // * removed bias
  11979. // * added q, k norm
  11980. struct ggml_cgraph * build_olmoe() {
  11981. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11982. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11983. int32_t n_tokens = this->n_tokens;
  11984. const int64_t n_embd_head = hparams.n_embd_head_v;
  11985. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11986. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11987. struct ggml_tensor * cur;
  11988. struct ggml_tensor * inpL;
  11989. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11990. // inp_pos - contains the positions
  11991. struct ggml_tensor * inp_pos = build_inp_pos();
  11992. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11993. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11994. for (int il = 0; il < n_layer; ++il) {
  11995. struct ggml_tensor * inpSA = inpL;
  11996. // norm
  11997. cur = llm_build_norm(ctx0, inpL, hparams,
  11998. model.layers[il].attn_norm, NULL,
  11999. LLM_NORM_RMS, cb, il);
  12000. cb(cur, "attn_norm", il);
  12001. // self_attention
  12002. {
  12003. // compute Q and K and RoPE them
  12004. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12005. cb(Qcur, "Qcur", il);
  12006. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12007. cb(Kcur, "Kcur", il);
  12008. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12009. cb(Vcur, "Vcur", il);
  12010. Qcur = llm_build_norm(ctx0, Qcur, hparams, model.layers[il].attn_q_norm, NULL,
  12011. LLM_NORM_RMS, cb, il);
  12012. cb(Qcur, "Qcur_normed", il);
  12013. Kcur = llm_build_norm(ctx0, Kcur, hparams, model.layers[il].attn_k_norm, NULL,
  12014. LLM_NORM_RMS, cb, il);
  12015. cb(Kcur, "Kcur_normed", il);
  12016. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12017. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12018. Qcur = ggml_rope_ext(
  12019. ctx0, Qcur, inp_pos, nullptr,
  12020. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12021. ext_factor, attn_factor, beta_fast, beta_slow
  12022. );
  12023. cb(Qcur, "Qcur_rope", il);
  12024. Kcur = ggml_rope_ext(
  12025. ctx0, Kcur, inp_pos, nullptr,
  12026. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12027. ext_factor, attn_factor, beta_fast, beta_slow
  12028. );
  12029. cb(Kcur, "Kcur_rope", il);
  12030. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12031. model.layers[il].wo, NULL,
  12032. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12033. }
  12034. if (il == n_layer - 1) {
  12035. // skip computing output for unused tokens
  12036. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12037. n_tokens = n_outputs;
  12038. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12039. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12040. }
  12041. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12042. cb(ffn_inp, "ffn_inp", il);
  12043. // MoE branch
  12044. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12045. model.layers[il].ffn_norm, NULL,
  12046. LLM_NORM_RMS, cb, il);
  12047. cb(cur, "ffn_norm", il);
  12048. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12049. model.layers[il].ffn_gate_inp,
  12050. model.layers[il].ffn_up_exps,
  12051. model.layers[il].ffn_gate_exps,
  12052. model.layers[il].ffn_down_exps,
  12053. n_expert, n_expert_used,
  12054. LLM_FFN_SILU, false,
  12055. false, 0.0,
  12056. cb, il);
  12057. cb(cur, "ffn_moe_out", il);
  12058. cur = ggml_add(ctx0, cur, ffn_inp);
  12059. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12060. cb(cur, "l_out", il);
  12061. // input for next layer
  12062. inpL = cur;
  12063. }
  12064. cur = inpL;
  12065. cur = llm_build_norm(ctx0, cur, hparams,
  12066. model.output_norm, NULL,
  12067. LLM_NORM_RMS, cb, -1);
  12068. cb(cur, "result_norm", -1);
  12069. // lm_head
  12070. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12071. cb(cur, "result_output", -1);
  12072. ggml_build_forward_expand(gf, cur);
  12073. return gf;
  12074. }
  12075. struct ggml_cgraph * build_openelm() {
  12076. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12077. const int64_t n_embd_head = hparams.n_embd_head_v;
  12078. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12079. struct ggml_tensor * cur;
  12080. struct ggml_tensor * inpL;
  12081. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12082. // inp_pos - contains the positions
  12083. struct ggml_tensor * inp_pos = build_inp_pos();
  12084. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12085. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12086. for (int il = 0; il < n_layer; ++il) {
  12087. const int64_t n_head = hparams.n_head(il);
  12088. const int64_t n_head_kv = hparams.n_head_kv(il);
  12089. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  12090. cur = inpL;
  12091. struct ggml_tensor * residual = cur;
  12092. // norm
  12093. cur = llm_build_norm(ctx0, inpL, hparams,
  12094. model.layers[il].attn_norm, NULL,
  12095. LLM_NORM_RMS, cb, il);
  12096. cb(cur, "attn_norm", il);
  12097. // self-attention
  12098. {
  12099. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12100. cb(cur, "wqkv", il);
  12101. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  12102. 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));
  12103. cb(Qcur, "Qcur", il);
  12104. 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));
  12105. cb(Kcur, "Kcur", il);
  12106. 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)));
  12107. cb(Vcur, "Vcur", il);
  12108. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  12109. model.layers[il].attn_q_norm, NULL,
  12110. LLM_NORM_RMS, cb, il);
  12111. cb(Qcur, "Qcur", il);
  12112. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  12113. model.layers[il].attn_k_norm, NULL,
  12114. LLM_NORM_RMS, cb, il);
  12115. cb(Kcur, "Kcur", il);
  12116. Qcur = ggml_rope_ext(
  12117. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12118. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12119. );
  12120. cb(Qcur, "Qcur", il);
  12121. Kcur = ggml_rope_ext(
  12122. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  12123. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  12124. );
  12125. cb(Kcur, "Kcur", il);
  12126. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  12127. cb(Qcur, "Vcur", il);
  12128. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12129. model.layers[il].wo, NULL,
  12130. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12131. }
  12132. if (il == n_layer - 1) {
  12133. // skip computing output for unused tokens
  12134. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12135. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  12136. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12137. }
  12138. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  12139. cb(ffn_inp, "ffn_inp", il);
  12140. // feed-forward network
  12141. {
  12142. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12143. model.layers[il].ffn_norm, NULL,
  12144. LLM_NORM_RMS, cb, il);
  12145. cb(cur, "ffn_norm", il);
  12146. cur = llm_build_ffn(ctx0, lctx, cur,
  12147. model.layers[il].ffn_up, NULL, NULL,
  12148. model.layers[il].ffn_gate, NULL, NULL,
  12149. model.layers[il].ffn_down, NULL, NULL,
  12150. NULL,
  12151. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12152. cb(cur, "ffn_out", il);
  12153. }
  12154. cur = ggml_add(ctx0, cur, ffn_inp);
  12155. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12156. cb(cur, "l_out", il);
  12157. inpL = cur;
  12158. }
  12159. cur = inpL;
  12160. // norm
  12161. cur = llm_build_norm(ctx0, cur, hparams,
  12162. model.output_norm, NULL,
  12163. LLM_NORM_RMS, cb, -1);
  12164. cb(cur, "result_norm", -1);
  12165. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12166. cb(cur, "result_output", -1);
  12167. ggml_build_forward_expand(gf, cur);
  12168. return gf;
  12169. }
  12170. struct ggml_cgraph * build_gptneox() {
  12171. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12172. const int64_t n_embd_head = hparams.n_embd_head_v;
  12173. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12174. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12175. struct ggml_tensor * cur;
  12176. struct ggml_tensor * inpL;
  12177. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12178. // inp_pos - contains the positions
  12179. struct ggml_tensor * inp_pos = build_inp_pos();
  12180. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12181. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12182. for (int il = 0; il < n_layer; ++il) {
  12183. cur = llm_build_norm(ctx0, inpL, hparams,
  12184. model.layers[il].attn_norm,
  12185. model.layers[il].attn_norm_b,
  12186. LLM_NORM, cb, il);
  12187. cb(cur, "attn_norm", il);
  12188. // self-attention
  12189. {
  12190. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12191. cb(cur, "wqkv", il);
  12192. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  12193. cb(cur, "bqkv", il);
  12194. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  12195. 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)));
  12196. 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)));
  12197. cb(Qcur, "Qcur", il);
  12198. cb(Kcur, "Kcur", il);
  12199. cb(Vcur, "Vcur", il);
  12200. Qcur = ggml_rope_ext(
  12201. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12202. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12203. ext_factor, attn_factor, beta_fast, beta_slow
  12204. );
  12205. cb(Qcur, "Qcur", il);
  12206. Kcur = ggml_rope_ext(
  12207. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12208. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12209. ext_factor, attn_factor, beta_fast, beta_slow
  12210. );
  12211. cb(Kcur, "Kcur", il);
  12212. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12213. model.layers[il].wo, model.layers[il].bo,
  12214. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12215. }
  12216. if (il == n_layer - 1) {
  12217. // skip computing output for unused tokens
  12218. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12219. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12220. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12221. }
  12222. // ffn
  12223. if (hparams.use_par_res) {
  12224. // attention and ffn are computed in parallel
  12225. // x = x + attn(ln1(x)) + ffn(ln2(x))
  12226. struct ggml_tensor * attn_out = cur;
  12227. cur = llm_build_norm(ctx0, inpL, hparams,
  12228. model.layers[il].ffn_norm,
  12229. model.layers[il].ffn_norm_b,
  12230. LLM_NORM, cb, il);
  12231. cb(cur, "ffn_norm", il);
  12232. cur = llm_build_ffn(ctx0, lctx, cur,
  12233. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12234. NULL, NULL, NULL,
  12235. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12236. NULL,
  12237. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12238. cb(cur, "ffn_out", il);
  12239. cur = ggml_add(ctx0, cur, inpL);
  12240. cb(cur, "ffn_out", il);
  12241. cur = ggml_add(ctx0, cur, attn_out);
  12242. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12243. cb(cur, "l_out", il);
  12244. // input for next layer
  12245. inpL = cur;
  12246. } else {
  12247. // attention and ffn are computed sequentially
  12248. // x = x + attn(ln1(x))
  12249. // x = x + ffn(ln2(x))
  12250. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  12251. cb(ffn_inp, "ffn_inp", il);
  12252. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12253. model.layers[il].ffn_norm,
  12254. model.layers[il].ffn_norm_b,
  12255. LLM_NORM, cb, il);
  12256. cb(cur, "ffn_norm", il);
  12257. cur = llm_build_ffn(ctx0, lctx, cur,
  12258. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12259. NULL, NULL, NULL,
  12260. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12261. NULL,
  12262. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  12263. cb(cur, "ffn_out", il);
  12264. cur = ggml_add(ctx0, cur, ffn_inp);
  12265. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12266. cb(cur, "l_out", il);
  12267. // input for next layer
  12268. inpL = cur;
  12269. }
  12270. }
  12271. cur = llm_build_norm(ctx0, inpL, hparams,
  12272. model.output_norm,
  12273. model.output_norm_b,
  12274. LLM_NORM, cb, -1);
  12275. cb(cur, "result_norm", -1);
  12276. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12277. cb(cur, "result_output", -1);
  12278. ggml_build_forward_expand(gf, cur);
  12279. return gf;
  12280. }
  12281. struct ggml_cgraph * build_arctic() {
  12282. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12283. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12284. int32_t n_tokens = this->n_tokens;
  12285. const int64_t n_embd_head = hparams.n_embd_head_v;
  12286. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12287. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12288. struct ggml_tensor * cur;
  12289. struct ggml_tensor * inpL;
  12290. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12291. // inp_pos - contains the positions
  12292. struct ggml_tensor * inp_pos = build_inp_pos();
  12293. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12294. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12295. for (int il = 0; il < n_layer; ++il) {
  12296. struct ggml_tensor * inpSA = inpL;
  12297. // norm
  12298. cur = llm_build_norm(ctx0, inpL, hparams,
  12299. model.layers[il].attn_norm, NULL,
  12300. LLM_NORM_RMS, cb, il);
  12301. cb(cur, "attn_norm", il);
  12302. // self-attention
  12303. {
  12304. // compute Q and K and RoPE them
  12305. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12306. cb(Qcur, "Qcur", il);
  12307. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12308. cb(Kcur, "Kcur", il);
  12309. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12310. cb(Vcur, "Vcur", il);
  12311. Qcur = ggml_rope_ext(
  12312. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12313. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12314. ext_factor, attn_factor, beta_fast, beta_slow
  12315. );
  12316. cb(Qcur, "Qcur", il);
  12317. Kcur = ggml_rope_ext(
  12318. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12319. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12320. ext_factor, attn_factor, beta_fast, beta_slow
  12321. );
  12322. cb(Kcur, "Kcur", il);
  12323. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12324. model.layers[il].wo, NULL,
  12325. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12326. }
  12327. if (il == n_layer - 1) {
  12328. // skip computing output for unused tokens
  12329. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12330. n_tokens = n_outputs;
  12331. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12332. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12333. }
  12334. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12335. cb(ffn_inp, "ffn_inp", il);
  12336. // feed-forward network
  12337. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12338. model.layers[il].ffn_norm, NULL,
  12339. LLM_NORM_RMS, cb, il);
  12340. cb(cur, "ffn_norm", il);
  12341. cur = llm_build_ffn(ctx0, lctx, cur,
  12342. model.layers[il].ffn_up, NULL, NULL,
  12343. model.layers[il].ffn_gate, NULL, NULL,
  12344. model.layers[il].ffn_down, NULL, NULL,
  12345. NULL,
  12346. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12347. cb(cur, "ffn_out", il);
  12348. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  12349. cb(ffn_out, "ffn_out", il);
  12350. // MoE
  12351. cur = llm_build_norm(ctx0, inpSA, hparams,
  12352. model.layers[il].ffn_norm_exps, NULL,
  12353. LLM_NORM_RMS, cb, il);
  12354. cb(cur, "ffn_norm_exps", il);
  12355. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  12356. model.layers[il].ffn_gate_inp,
  12357. model.layers[il].ffn_up_exps,
  12358. model.layers[il].ffn_gate_exps,
  12359. model.layers[il].ffn_down_exps,
  12360. n_expert, n_expert_used,
  12361. LLM_FFN_SILU, true,
  12362. false, 0.0,
  12363. cb, il);
  12364. cb(cur, "ffn_moe_out", il);
  12365. cur = ggml_add(ctx0, cur, ffn_out);
  12366. cb(cur, "ffn_out", il);
  12367. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12368. cb(cur, "l_out", il);
  12369. // input for next layer
  12370. inpL = cur;
  12371. }
  12372. cur = inpL;
  12373. cur = llm_build_norm(ctx0, cur, hparams,
  12374. model.output_norm, NULL,
  12375. LLM_NORM_RMS, cb, -1);
  12376. cb(cur, "result_norm", -1);
  12377. // lm_head
  12378. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12379. cb(cur, "result_output", -1);
  12380. ggml_build_forward_expand(gf, cur);
  12381. return gf;
  12382. }
  12383. struct ggml_cgraph * build_deepseek2() {
  12384. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12385. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12386. int32_t n_tokens = this->n_tokens;
  12387. bool is_lite = (hparams.n_layer == 27);
  12388. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  12389. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  12390. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  12391. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  12392. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  12393. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  12394. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  12395. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  12396. struct ggml_tensor * cur;
  12397. struct ggml_tensor * inpL;
  12398. // {n_embd, n_tokens}
  12399. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12400. // inp_pos - contains the positions
  12401. struct ggml_tensor * inp_pos = build_inp_pos();
  12402. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12403. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12404. for (int il = 0; il < n_layer; ++il) {
  12405. struct ggml_tensor * inpSA = inpL;
  12406. // norm
  12407. cur = llm_build_norm(ctx0, inpL, hparams,
  12408. model.layers[il].attn_norm, NULL,
  12409. LLM_NORM_RMS, cb, il);
  12410. cb(cur, "attn_norm", il);
  12411. // self_attention
  12412. {
  12413. struct ggml_tensor * q = NULL;
  12414. if (!is_lite) {
  12415. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  12416. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  12417. cb(q, "q", il);
  12418. q = llm_build_norm(ctx0, q, hparams,
  12419. model.layers[il].attn_q_a_norm, NULL,
  12420. LLM_NORM_RMS, cb, il);
  12421. cb(q, "q", il);
  12422. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  12423. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  12424. cb(q, "q", il);
  12425. } else {
  12426. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  12427. cb(q, "q", il);
  12428. }
  12429. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12430. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  12431. ggml_row_size(q->type, hparams.n_embd_head_k),
  12432. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12433. 0);
  12434. cb(q_nope, "q_nope", il);
  12435. // and {n_head * n_embd_head_qk_rope, n_tokens}
  12436. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  12437. ggml_row_size(q->type, hparams.n_embd_head_k),
  12438. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  12439. ggml_row_size(q->type, n_embd_head_qk_nope));
  12440. cb(q_pe, "q_pe", il);
  12441. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  12442. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  12443. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  12444. // split into {kv_lora_rank, n_tokens}
  12445. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  12446. kv_pe_compresseed->nb[1],
  12447. 0);
  12448. cb(kv_compressed, "kv_compressed", il);
  12449. // and {n_embd_head_qk_rope, n_tokens}
  12450. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  12451. kv_pe_compresseed->nb[1],
  12452. kv_pe_compresseed->nb[1],
  12453. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  12454. cb(k_pe, "k_pe", il);
  12455. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  12456. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  12457. model.layers[il].attn_kv_a_norm, NULL,
  12458. LLM_NORM_RMS, cb, il);
  12459. cb(kv_compressed, "kv_compressed", il);
  12460. // {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}
  12461. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  12462. cb(kv, "kv", il);
  12463. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  12464. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  12465. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  12466. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12467. 0);
  12468. cb(k_nope, "k_nope", il);
  12469. // and {n_head * n_embd_head_v, n_tokens}
  12470. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  12471. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  12472. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  12473. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  12474. cb(v_states, "v_states", il);
  12475. v_states = ggml_cont(ctx0, v_states);
  12476. cb(v_states, "v_states", il);
  12477. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  12478. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  12479. 0);
  12480. cb(v_states, "v_states", il);
  12481. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12482. q_pe = ggml_rope_ext(
  12483. ctx0, q_pe, inp_pos, nullptr,
  12484. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12485. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12486. );
  12487. cb(q_pe, "q_pe", il);
  12488. // shared RoPE key
  12489. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  12490. k_pe = ggml_rope_ext(
  12491. ctx0, k_pe, inp_pos, nullptr,
  12492. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12493. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  12494. );
  12495. cb(k_pe, "k_pe", il);
  12496. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  12497. cb(q_states, "q_states", il);
  12498. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  12499. cb(k_states, "k_states", il);
  12500. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12501. model.layers[il].wo, NULL,
  12502. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  12503. }
  12504. if (il == n_layer - 1) {
  12505. // skip computing output for unused tokens
  12506. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12507. n_tokens = n_outputs;
  12508. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12509. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12510. }
  12511. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12512. cb(ffn_inp, "ffn_inp", il);
  12513. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12514. model.layers[il].ffn_norm, NULL,
  12515. LLM_NORM_RMS, cb, il);
  12516. cb(cur, "ffn_norm", il);
  12517. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  12518. cur = llm_build_ffn(ctx0, lctx, cur,
  12519. model.layers[il].ffn_up, NULL, NULL,
  12520. model.layers[il].ffn_gate, NULL, NULL,
  12521. model.layers[il].ffn_down, NULL, NULL,
  12522. NULL,
  12523. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12524. cb(cur, "ffn_out", il);
  12525. } else {
  12526. // MoE branch
  12527. ggml_tensor * moe_out =
  12528. llm_build_moe_ffn(ctx0, lctx, cur,
  12529. model.layers[il].ffn_gate_inp,
  12530. model.layers[il].ffn_up_exps,
  12531. model.layers[il].ffn_gate_exps,
  12532. model.layers[il].ffn_down_exps,
  12533. n_expert, n_expert_used,
  12534. LLM_FFN_SILU, false,
  12535. true, hparams.expert_weights_scale,
  12536. cb, il);
  12537. cb(moe_out, "ffn_moe_out", il);
  12538. // FFN shared expert
  12539. {
  12540. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  12541. model.layers[il].ffn_up_shexp, NULL, NULL,
  12542. model.layers[il].ffn_gate_shexp, NULL, NULL,
  12543. model.layers[il].ffn_down_shexp, NULL, NULL,
  12544. NULL,
  12545. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12546. cb(ffn_shexp, "ffn_shexp", il);
  12547. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  12548. cb(cur, "ffn_out", il);
  12549. }
  12550. }
  12551. cur = ggml_add(ctx0, cur, ffn_inp);
  12552. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12553. cb(cur, "l_out", il);
  12554. // input for next layer
  12555. inpL = cur;
  12556. }
  12557. cur = inpL;
  12558. cur = llm_build_norm(ctx0, cur, hparams,
  12559. model.output_norm, NULL,
  12560. LLM_NORM_RMS, cb, -1);
  12561. cb(cur, "result_norm", -1);
  12562. // lm_head
  12563. cur = ggml_mul_mat(ctx0, model.output, cur);
  12564. cb(cur, "result_output", -1);
  12565. ggml_build_forward_expand(gf, cur);
  12566. return gf;
  12567. }
  12568. struct ggml_cgraph * build_bitnet() {
  12569. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12570. const int64_t n_embd_head = hparams.n_embd_head_v;
  12571. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12572. struct ggml_tensor * cur;
  12573. struct ggml_tensor * inpL;
  12574. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12575. // inp_pos - contains the positions
  12576. struct ggml_tensor * inp_pos = build_inp_pos();
  12577. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12578. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12579. for (int il = 0; il < n_layer; ++il) {
  12580. struct ggml_tensor * inpSA = inpL;
  12581. cur = llm_build_norm(ctx0, inpL, hparams,
  12582. model.layers[il].attn_norm, NULL,
  12583. LLM_NORM_RMS, cb, il);
  12584. cb(cur, "attn_norm", il);
  12585. // self-attention
  12586. {
  12587. // compute Q and K and RoPE them
  12588. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12589. if (model.layers[il].wq_scale) {
  12590. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  12591. }
  12592. cb(Qcur, "Qcur", il);
  12593. if (model.layers[il].bq) {
  12594. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12595. cb(Qcur, "Qcur", il);
  12596. }
  12597. // B1.K
  12598. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12599. if (model.layers[il].wk_scale) {
  12600. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  12601. }
  12602. cb(Kcur, "Kcur", il);
  12603. if (model.layers[il].bk) {
  12604. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12605. cb(Kcur, "Kcur", il);
  12606. }
  12607. // B1.V
  12608. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12609. if (model.layers[il].wv_scale) {
  12610. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  12611. }
  12612. cb(Vcur, "Vcur", il);
  12613. if (model.layers[il].bv) {
  12614. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12615. cb(Vcur, "Vcur", il);
  12616. }
  12617. Qcur = ggml_rope_ext(
  12618. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12619. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12620. ext_factor, attn_factor, beta_fast, beta_slow
  12621. );
  12622. cb(Qcur, "Qcur", il);
  12623. Kcur = ggml_rope_ext(
  12624. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12625. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12626. ext_factor, attn_factor, beta_fast, beta_slow
  12627. );
  12628. cb(Kcur, "Kcur", il);
  12629. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12630. NULL, NULL,
  12631. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12632. cur = llm_build_norm(ctx0, cur, hparams,
  12633. model.layers[il].attn_sub_norm, NULL,
  12634. LLM_NORM_RMS, cb, il);
  12635. cb(cur, "attn_sub_norm", il);
  12636. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  12637. if (model.layers[il].wo_scale) {
  12638. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  12639. }
  12640. if (model.layers[il].bo) {
  12641. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  12642. }
  12643. cb(cur, "attn_o_out", il);
  12644. }
  12645. if (il == n_layer - 1) {
  12646. // skip computing output for unused tokens
  12647. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12648. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12649. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12650. }
  12651. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12652. cb(ffn_inp, "ffn_inp", il);
  12653. // feed-forward forward
  12654. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12655. model.layers[il].ffn_norm, NULL,
  12656. LLM_NORM_RMS, cb, il);
  12657. cb(cur, "ffn_norm", il);
  12658. cur = llm_build_ffn(ctx0, lctx, cur,
  12659. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  12660. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  12661. NULL, NULL, NULL,
  12662. NULL,
  12663. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12664. cb(cur, "ffn_sub_out", il);
  12665. cur = llm_build_norm(ctx0, cur, hparams,
  12666. model.layers[il].ffn_sub_norm, NULL,
  12667. LLM_NORM_RMS, cb, il);
  12668. cb(cur, "ffn_sub_norm", il);
  12669. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  12670. if (model.layers[il].ffn_down_scale) {
  12671. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  12672. }
  12673. cb(cur, "ffn_down", il);
  12674. cur = ggml_add(ctx0, cur, ffn_inp);
  12675. cb(cur, "l_out", il);
  12676. // input for next layer
  12677. inpL = cur;
  12678. }
  12679. cur = inpL;
  12680. cur = llm_build_norm(ctx0, cur, hparams,
  12681. model.output_norm, NULL,
  12682. LLM_NORM_RMS, cb, -1);
  12683. cb(cur, "result_norm", -1);
  12684. // lm_head
  12685. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  12686. cb(cur, "result_output", -1);
  12687. ggml_build_forward_expand(gf, cur);
  12688. return gf;
  12689. }
  12690. struct ggml_cgraph * build_t5_encoder() {
  12691. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12692. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12693. int32_t n_tokens = this->n_tokens;
  12694. const int64_t n_embd_head = hparams.n_embd_head_v;
  12695. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12696. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12697. struct ggml_tensor * cur;
  12698. struct ggml_tensor * inpL;
  12699. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12700. GGML_ASSERT(lctx.is_encoding);
  12701. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  12702. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12703. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  12704. for (int il = 0; il < n_layer; ++il) {
  12705. struct ggml_tensor * inpSA = inpL;
  12706. // norm
  12707. cur = llm_build_norm(ctx0, inpL, hparams,
  12708. model.layers[il].attn_norm_enc, NULL,
  12709. LLM_NORM_RMS, cb, il);
  12710. cb(cur, "attn_norm", il);
  12711. // self-attention
  12712. {
  12713. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  12714. cb(Qcur, "Qcur", il);
  12715. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  12716. cb(Kcur, "Kcur", il);
  12717. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  12718. cb(Vcur, "Vcur", il);
  12719. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12720. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  12721. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  12722. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  12723. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  12724. cb(kq, "kq", il);
  12725. 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;
  12726. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  12727. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  12728. cb(kq_b, "kq_b", il);
  12729. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  12730. cb(kq, "kq_soft_max_ext", il);
  12731. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  12732. cb(v, "v", il);
  12733. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  12734. cb(kqv, "kqv", il);
  12735. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  12736. cb(kqv_merged, "kqv_merged", il);
  12737. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  12738. cb(cur, "kqv_merged_cont", il);
  12739. ggml_build_forward_expand(gf, cur);
  12740. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  12741. cb(cur, "kqv_out", il);
  12742. }
  12743. if (il == n_layer - 1) {
  12744. // skip computing output for unused tokens
  12745. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12746. n_tokens = n_outputs;
  12747. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12748. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12749. }
  12750. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12751. cb(ffn_inp, "ffn_inp", il);
  12752. // feed-forward network
  12753. {
  12754. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12755. model.layers[il].ffn_norm_enc, NULL,
  12756. LLM_NORM_RMS, cb, il);
  12757. cb(cur, "ffn_norm", il);
  12758. // T5 uses relu, flan-T5 uses gelu-gated
  12759. cur = llm_build_ffn(ctx0, lctx, cur,
  12760. model.layers[il].ffn_up_enc, NULL, NULL,
  12761. model.layers[il].ffn_gate_enc, NULL, NULL,
  12762. model.layers[il].ffn_down_enc, NULL, NULL,
  12763. NULL,
  12764. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  12765. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  12766. cb, il);
  12767. cb(cur, "ffn_out", il);
  12768. }
  12769. cur = ggml_add(ctx0, cur, ffn_inp);
  12770. cb(cur, "ffn_out", il);
  12771. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  12772. if (layer_dir != nullptr) {
  12773. cur = ggml_add(ctx0, cur, layer_dir);
  12774. }
  12775. cb(cur, "l_out", il);
  12776. // input for next layer
  12777. inpL = cur;
  12778. }
  12779. cur = inpL;
  12780. cb(cur, "result_embd", -1);
  12781. cur = llm_build_norm(ctx0, cur, hparams,
  12782. model.output_norm_enc, NULL,
  12783. LLM_NORM_RMS, cb, -1);
  12784. cb(cur, "result_norm", -1);
  12785. ggml_build_forward_expand(gf, cur);
  12786. return gf;
  12787. }
  12788. struct ggml_cgraph * build_t5_decoder() {
  12789. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12790. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12791. int32_t n_tokens = this->n_tokens;
  12792. const int64_t n_embd_head = hparams.n_embd_head_v;
  12793. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12794. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12795. struct ggml_tensor * cur;
  12796. struct ggml_tensor * inpL;
  12797. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12798. GGML_ASSERT(!lctx.is_encoding);
  12799. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  12800. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  12801. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  12802. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  12803. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  12804. for (int il = 0; il < n_layer; ++il) {
  12805. struct ggml_tensor * inpSA = inpL;
  12806. // norm
  12807. cur = llm_build_norm(ctx0, inpL, hparams,
  12808. model.layers[il].attn_norm, NULL,
  12809. LLM_NORM_RMS, cb, il);
  12810. cb(cur, "attn_norm", il);
  12811. // self-attention
  12812. {
  12813. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12814. cb(Qcur, "Qcur", il);
  12815. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12816. cb(Kcur, "Kcur", il);
  12817. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12818. cb(Vcur, "Vcur", il);
  12819. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  12820. struct ggml_tensor * k =
  12821. ggml_view_3d(ctx0, kv_self.k_l[il],
  12822. n_embd_head_k, n_kv, n_head_kv,
  12823. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  12824. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  12825. 0);
  12826. cb(k, "k", il);
  12827. struct ggml_tensor * v =
  12828. ggml_view_3d(ctx0, kv_self.v_l[il],
  12829. n_kv, n_embd_head_v, n_head_kv,
  12830. ggml_element_size(kv_self.v_l[il])*n_ctx,
  12831. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  12832. 0);
  12833. cb(v, "v", il);
  12834. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12835. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  12836. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  12837. cb(kq, "kq", il);
  12838. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  12839. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  12840. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  12841. cb(kq_b, "kq_b", il);
  12842. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  12843. cb(kq, "kq_soft_max_ext", il);
  12844. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  12845. cb(kqv, "kqv", il);
  12846. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  12847. cb(kqv_merged, "kqv_merged", il);
  12848. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  12849. cb(cur, "kqv_merged_cont", il);
  12850. ggml_build_forward_expand(gf, cur);
  12851. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  12852. cb(cur, "kqv_out", il);
  12853. }
  12854. cur = ggml_add(ctx0, cur, inpSA);
  12855. cb(cur, "cross_inp", il);
  12856. struct ggml_tensor * inpCA = cur;
  12857. // norm
  12858. cur = llm_build_norm(ctx0, cur, hparams,
  12859. model.layers[il].attn_norm_cross, NULL,
  12860. LLM_NORM_RMS, cb, il);
  12861. cb(cur, "attn_norm_cross", il);
  12862. // cross-attention
  12863. {
  12864. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  12865. cb(Qcur, "Qcur", il);
  12866. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  12867. cb(Kcur, "Kcur", il);
  12868. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  12869. cb(Vcur, "Vcur", il);
  12870. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12871. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  12872. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  12873. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  12874. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  12875. cb(kq, "kq", il);
  12876. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  12877. cb(kq, "kq_soft_max_ext", il);
  12878. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  12879. cb(v, "v", il);
  12880. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  12881. cb(kqv, "kqv", il);
  12882. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  12883. cb(kqv_merged, "kqv_merged", il);
  12884. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  12885. cb(cur, "kqv_merged_cont", il);
  12886. ggml_build_forward_expand(gf, cur);
  12887. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  12888. cb(cur, "kqv_out", 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. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  12897. }
  12898. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  12899. cb(ffn_inp, "ffn_inp", il);
  12900. // feed-forward network
  12901. {
  12902. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12903. model.layers[il].ffn_norm, NULL,
  12904. LLM_NORM_RMS, cb, il);
  12905. cb(cur, "ffn_norm", il);
  12906. // T5 uses relu, flan-T5 uses gelu-gated
  12907. cur = llm_build_ffn(ctx0, lctx, cur,
  12908. model.layers[il].ffn_up, NULL, NULL,
  12909. model.layers[il].ffn_gate, NULL, NULL,
  12910. model.layers[il].ffn_down, NULL, NULL,
  12911. NULL,
  12912. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  12913. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  12914. cb, il);
  12915. cb(cur, "ffn_out", il);
  12916. }
  12917. cur = ggml_add(ctx0, cur, ffn_inp);
  12918. cb(cur, "ffn_out", il);
  12919. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  12920. if (layer_dir != nullptr) {
  12921. cur = ggml_add(ctx0, cur, layer_dir);
  12922. }
  12923. cb(cur, "l_out", il);
  12924. // input for next layer
  12925. inpL = cur;
  12926. }
  12927. cur = inpL;
  12928. cb(cur, "result_embd", -1);
  12929. cur = llm_build_norm(ctx0, cur, hparams,
  12930. model.output_norm, NULL,
  12931. LLM_NORM_RMS, cb, -1);
  12932. cb(cur, "result_norm", -1);
  12933. // lm_head
  12934. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12935. cb(cur, "result_output", -1);
  12936. ggml_build_forward_expand(gf, cur);
  12937. return gf;
  12938. }
  12939. struct ggml_cgraph * build_jais() {
  12940. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12941. const int64_t n_embd_head = hparams.n_embd_head_v;
  12942. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  12943. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12944. struct ggml_tensor * cur;
  12945. struct ggml_tensor * inpL;
  12946. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12947. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12948. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12949. for (int il = 0; il < n_layer; ++il) {
  12950. cur = llm_build_norm(ctx0, inpL, hparams,
  12951. model.layers[il].attn_norm,
  12952. model.layers[il].attn_norm_b,
  12953. LLM_NORM, cb, il);
  12954. cb(cur, "attn_norm", il);
  12955. // self-attention
  12956. {
  12957. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  12958. cb(cur, "wqkv", il);
  12959. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  12960. cb(cur, "bqkv", il);
  12961. 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)));
  12962. 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)));
  12963. 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)));
  12964. cb(Qcur, "Qcur", il);
  12965. cb(Kcur, "Kcur", il);
  12966. cb(Vcur, "Vcur", il);
  12967. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  12968. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12969. model.layers[il].wo, model.layers[il].bo,
  12970. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  12971. }
  12972. if (il == n_layer - 1) {
  12973. // skip computing output for unused tokens
  12974. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12975. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12976. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  12977. }
  12978. // add the input
  12979. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  12980. cb(ffn_inp, "ffn_inp", il);
  12981. // FF
  12982. {
  12983. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12984. model.layers[il].ffn_norm,
  12985. model.layers[il].ffn_norm_b,
  12986. LLM_NORM, cb, il);
  12987. cb(cur, "ffn_norm", il);
  12988. cur = llm_build_ffn(ctx0, lctx, cur,
  12989. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12990. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  12991. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12992. NULL,
  12993. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12994. cb(cur, "ffn_out", il);
  12995. }
  12996. inpL = ggml_add(ctx0, cur, ffn_inp);
  12997. cb(inpL, "l_out", il);
  12998. }
  12999. cur = llm_build_norm(ctx0, inpL, hparams,
  13000. model.output_norm,
  13001. model.output_norm_b,
  13002. LLM_NORM, cb, -1);
  13003. cb(cur, "result_norm", -1);
  13004. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13005. cb(cur, "result_output", -1);
  13006. ggml_build_forward_expand(gf, cur);
  13007. return gf;
  13008. }
  13009. struct ggml_cgraph * build_chatglm() {
  13010. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13011. const int64_t n_embd_head = hparams.n_embd_head_v;
  13012. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  13013. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13014. struct ggml_tensor * cur;
  13015. struct ggml_tensor * inpL;
  13016. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13017. // inp_pos - contains the positions
  13018. struct ggml_tensor * inp_pos = build_inp_pos();
  13019. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13020. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13021. for (int il = 0; il < n_layer; ++il) {
  13022. struct ggml_tensor * inpSA = inpL;
  13023. cur = llm_build_norm(ctx0, inpL, hparams,
  13024. model.layers[il].attn_norm,
  13025. NULL,
  13026. LLM_NORM_RMS, cb, il);
  13027. cb(cur, "attn_norm", il);
  13028. // self-attention
  13029. {
  13030. struct ggml_tensor * Qcur = nullptr;
  13031. struct ggml_tensor * Kcur = nullptr;
  13032. struct ggml_tensor * Vcur = nullptr;
  13033. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  13034. cb(cur, "wqkv", il);
  13035. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  13036. cb(cur, "bqkv", il);
  13037. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  13038. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  13039. 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)));
  13040. cb(Qcur, "Qcur", il);
  13041. cb(Kcur, "Kcur", il);
  13042. cb(Vcur, "Vcur", il);
  13043. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  13044. Qcur = ggml_rope_ext(
  13045. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13046. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13047. ext_factor, attn_factor, beta_fast, beta_slow
  13048. );
  13049. cb(Qcur, "Qcur_rope", il);
  13050. Kcur = ggml_rope_ext(
  13051. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13052. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13053. ext_factor, attn_factor, beta_fast, beta_slow
  13054. );
  13055. cb(Kcur, "Kcur_rope", il);
  13056. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13057. model.layers[il].wo, NULL,
  13058. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13059. }
  13060. if (il == n_layer - 1) {
  13061. // skip computing output for unused tokens
  13062. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13063. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13064. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13065. }
  13066. // Add the input
  13067. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13068. cb(ffn_inp, "ffn_inp", il);
  13069. // FF
  13070. {
  13071. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13072. model.layers[il].ffn_norm,
  13073. NULL,
  13074. LLM_NORM_RMS, cb, il);
  13075. cb(cur, "ffn_norm", il);
  13076. cur = llm_build_ffn(ctx0, lctx, cur,
  13077. model.layers[il].ffn_up, NULL, NULL,
  13078. NULL, NULL, NULL,
  13079. model.layers[il].ffn_down, NULL, NULL,
  13080. NULL,
  13081. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  13082. cb(cur, "ffn_out", il);
  13083. }
  13084. inpL = ggml_add(ctx0, cur, ffn_inp);
  13085. cb(inpL, "l_out", il);
  13086. }
  13087. cur = llm_build_norm(ctx0, inpL, hparams,
  13088. model.output_norm,
  13089. NULL,
  13090. LLM_NORM_RMS, cb, -1);
  13091. cb(cur, "result_norm", -1);
  13092. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13093. cb(cur, "result_output", -1);
  13094. ggml_build_forward_expand(gf, cur);
  13095. return gf;
  13096. }
  13097. struct ggml_cgraph * build_nemotron() {
  13098. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13099. const int64_t n_embd_head = hparams.n_embd_head_v;
  13100. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13101. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  13102. struct ggml_tensor * cur;
  13103. struct ggml_tensor * inpL;
  13104. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13105. // inp_pos - contains the positions
  13106. struct ggml_tensor * inp_pos = build_inp_pos();
  13107. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13108. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13109. for (int il = 0; il < n_layer; ++il) {
  13110. struct ggml_tensor * inpSA = inpL;
  13111. // norm
  13112. cur = llm_build_norm(ctx0, inpL, hparams,
  13113. model.layers[il].attn_norm,
  13114. model.layers[il].attn_norm_b,
  13115. LLM_NORM, cb, il);
  13116. cb(cur, "attn_norm", il);
  13117. // self-attention
  13118. {
  13119. // compute Q and K and RoPE them
  13120. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13121. cb(Qcur, "Qcur", il);
  13122. if (model.layers[il].bq) {
  13123. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13124. cb(Qcur, "Qcur", il);
  13125. }
  13126. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13127. cb(Kcur, "Kcur", il);
  13128. if (model.layers[il].bk) {
  13129. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13130. cb(Kcur, "Kcur", il);
  13131. }
  13132. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13133. cb(Vcur, "Vcur", il);
  13134. if (model.layers[il].bv) {
  13135. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13136. cb(Vcur, "Vcur", il);
  13137. }
  13138. Qcur = ggml_rope_ext(
  13139. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13140. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13141. ext_factor, attn_factor, beta_fast, beta_slow
  13142. );
  13143. cb(Qcur, "Qcur", il);
  13144. Kcur = ggml_rope_ext(
  13145. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13146. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13147. ext_factor, attn_factor, beta_fast, beta_slow
  13148. );
  13149. cb(Kcur, "Kcur", il);
  13150. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13151. model.layers[il].wo, model.layers[il].bo,
  13152. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13153. }
  13154. if (il == n_layer - 1) {
  13155. // skip computing output for unused tokens
  13156. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13157. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13158. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13159. }
  13160. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13161. cb(ffn_inp, "ffn_inp", il);
  13162. // feed-forward network
  13163. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13164. model.layers[il].ffn_norm,
  13165. model.layers[il].ffn_norm_b,
  13166. LLM_NORM, cb, il);
  13167. cb(cur, "ffn_norm", il);
  13168. cur = llm_build_ffn(ctx0, lctx, cur,
  13169. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  13170. NULL, NULL, NULL,
  13171. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  13172. NULL,
  13173. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  13174. cur = ggml_add(ctx0, cur, ffn_inp);
  13175. cb(cur, "ffn_out", il);
  13176. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13177. cb(cur, "l_out", il);
  13178. // input for next layer
  13179. inpL = cur;
  13180. }
  13181. cur = inpL;
  13182. cur = llm_build_norm(ctx0, cur, hparams,
  13183. model.output_norm, model.output_norm_b,
  13184. LLM_NORM, cb, -1);
  13185. cb(cur, "result_norm", -1);
  13186. // lm_head
  13187. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13188. cb(cur, "result_output", -1);
  13189. ggml_build_forward_expand(gf, cur);
  13190. return gf;
  13191. }
  13192. struct ggml_cgraph * build_exaone() {
  13193. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13194. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13195. int32_t n_tokens = this->n_tokens;
  13196. const int64_t n_embd_head = hparams.n_embd_head_v;
  13197. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13198. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13199. struct ggml_tensor * cur;
  13200. struct ggml_tensor * inpL;
  13201. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13202. // inp_pos - contains the positions
  13203. struct ggml_tensor * inp_pos = build_inp_pos();
  13204. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13205. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13206. for (int il = 0; il < n_layer; ++il) {
  13207. struct ggml_tensor * inpSA = inpL;
  13208. // norm
  13209. cur = llm_build_norm(ctx0, inpL, hparams,
  13210. model.layers[il].attn_norm, NULL,
  13211. LLM_NORM_RMS, cb, il);
  13212. cb(cur, "attn_norm", il);
  13213. // self-attention
  13214. {
  13215. // rope freq factors for llama3; may return nullptr for llama2 and other models
  13216. struct ggml_tensor * rope_factors = build_rope_factors(il);
  13217. // compute Q and K and RoPE them
  13218. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13219. cb(Qcur, "Qcur", il);
  13220. if (model.layers[il].bq) {
  13221. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  13222. cb(Qcur, "Qcur", il);
  13223. }
  13224. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13225. cb(Kcur, "Kcur", il);
  13226. if (model.layers[il].bk) {
  13227. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  13228. cb(Kcur, "Kcur", il);
  13229. }
  13230. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13231. cb(Vcur, "Vcur", il);
  13232. if (model.layers[il].bv) {
  13233. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  13234. cb(Vcur, "Vcur", il);
  13235. }
  13236. Qcur = ggml_rope_ext(
  13237. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  13238. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13239. ext_factor, attn_factor, beta_fast, beta_slow
  13240. );
  13241. cb(Qcur, "Qcur", il);
  13242. Kcur = ggml_rope_ext(
  13243. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  13244. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13245. ext_factor, attn_factor, beta_fast, beta_slow
  13246. );
  13247. cb(Kcur, "Kcur", il);
  13248. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13249. model.layers[il].wo, model.layers[il].bo,
  13250. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13251. }
  13252. if (il == n_layer - 1) {
  13253. // skip computing output for unused tokens
  13254. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13255. n_tokens = n_outputs;
  13256. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13257. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13258. }
  13259. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13260. cb(ffn_inp, "ffn_inp", il);
  13261. // feed-forward network
  13262. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13263. model.layers[il].ffn_norm, NULL,
  13264. LLM_NORM_RMS, cb, il);
  13265. cb(cur, "ffn_norm", il);
  13266. cur = llm_build_ffn(ctx0, lctx, cur,
  13267. model.layers[il].ffn_up, NULL, NULL,
  13268. model.layers[il].ffn_gate, NULL, NULL,
  13269. model.layers[il].ffn_down, NULL, NULL,
  13270. NULL,
  13271. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13272. cb(cur, "ffn_out", il);
  13273. cur = ggml_add(ctx0, cur, ffn_inp);
  13274. cb(cur, "ffn_out", il);
  13275. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13276. cb(cur, "l_out", il);
  13277. // input for next layer
  13278. inpL = cur;
  13279. }
  13280. cur = inpL;
  13281. cur = llm_build_norm(ctx0, cur, hparams,
  13282. model.output_norm, NULL,
  13283. LLM_NORM_RMS, cb, -1);
  13284. cb(cur, "result_norm", -1);
  13285. // lm_head
  13286. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13287. cb(cur, "result_output", -1);
  13288. ggml_build_forward_expand(gf, cur);
  13289. return gf;
  13290. }
  13291. ggml_cgraph * build_rwkv6() {
  13292. ggml_cgraph *gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13293. // Token shift state dimensions should be 2 * n_emb
  13294. GGML_ASSERT(n_embd == hparams.n_embd_k_s() / 2);
  13295. const int64_t n_seqs = batch.n_seqs;
  13296. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13297. const int64_t n_tokens = batch.n_tokens;
  13298. GGML_ASSERT(n_seqs != 0);
  13299. GGML_ASSERT(batch.equal_seqs);
  13300. GGML_ASSERT(n_tokens == n_seq_tokens * n_seqs);
  13301. struct ggml_tensor * cur;
  13302. struct ggml_tensor * inpL;
  13303. struct ggml_tensor * state_copy = build_inp_s_copy();
  13304. struct ggml_tensor * state_mask = build_inp_s_mask();
  13305. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13306. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  13307. for (int il = 0; il < n_layer; ++il) {
  13308. const llama_layer * layer = &model.layers[il];
  13309. // (ab)using the KV cache to store the states
  13310. struct ggml_tensor * token_shift = llm_build_copy_mask_state(ctx0,
  13311. gf, kv_self.k_l[il], state_copy, state_mask,
  13312. hparams.n_embd_k_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13313. struct ggml_tensor * wkv_states = llm_build_copy_mask_state(ctx0,
  13314. gf, kv_self.v_l[il], state_copy, state_mask,
  13315. hparams.n_embd_v_s(), kv_self.size, kv_head, n_kv, n_seqs);
  13316. cur = ggml_reshape_3d(ctx0, inpL, n_embd, n_seq_tokens, n_seqs);
  13317. token_shift = ggml_reshape_3d(ctx0, token_shift, n_embd, 2, n_seqs);
  13318. 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);
  13319. 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));
  13320. struct ggml_tensor * x_norm_att = llm_build_norm(ctx0, cur, hparams, layer->attn_norm, layer->attn_norm_b, LLM_NORM, cb, il);
  13321. struct ggml_tensor * x_prev = ggml_concat(
  13322. ctx0,
  13323. att_shift,
  13324. 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),
  13325. 1
  13326. );
  13327. cur = ggml_add(ctx0, cur, llm_build_rwkv6_time_mix(lctx, ctx0, layer, x_norm_att, x_prev, &wkv_states));
  13328. ggml_build_forward_expand(gf, cur);
  13329. ggml_build_forward_expand(
  13330. gf,
  13331. ggml_cpy(
  13332. ctx0,
  13333. wkv_states,
  13334. ggml_view_1d(
  13335. ctx0,
  13336. kv_self.v_l[il],
  13337. hparams.n_embd_v_s() * n_seqs,
  13338. hparams.n_embd_v_s() * kv_head * ggml_element_size(kv_self.v_l[il])
  13339. )
  13340. )
  13341. );
  13342. 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);
  13343. x_prev = ggml_concat(
  13344. ctx0,
  13345. ffn_shift,
  13346. 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),
  13347. 1
  13348. );
  13349. cur = ggml_add(ctx0, cur, llm_build_rwkv6_channel_mix(lctx, ctx0, layer, x_norm_ffn, x_prev));
  13350. ggml_build_forward_expand(gf, cur);
  13351. 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));
  13352. 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));
  13353. token_shift = ggml_concat(ctx0, last_norm_att, last_norm_ffn, 1);
  13354. ggml_build_forward_expand(
  13355. gf,
  13356. ggml_cpy(
  13357. ctx0,
  13358. ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * 2, 0),
  13359. 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]))
  13360. )
  13361. );
  13362. if (hparams.rescale_every_n_layers != 0 && (il + 1) % hparams.rescale_every_n_layers == 0) {
  13363. cur = ggml_scale(ctx0, cur, 0.5F);
  13364. }
  13365. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13366. cb(cur, "l_out", il);
  13367. // input for next layer
  13368. inpL = cur;
  13369. }
  13370. cur = inpL;
  13371. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13372. cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
  13373. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13374. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, model.output_norm_b, LLM_NORM, cb, -1);
  13375. cb(cur, "result_norm", -1);
  13376. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13377. cb(cur, "result_output", -1);
  13378. ggml_build_forward_expand(gf, cur);
  13379. return gf;
  13380. }
  13381. // ref: https://github.com/facebookresearch/chameleon
  13382. // based on the original build_llama() function, changes:
  13383. // * qk-norm
  13384. // * swin-norm
  13385. // * removed bias
  13386. // * removed MoE
  13387. struct ggml_cgraph * build_chameleon() {
  13388. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  13389. // mutable variable, needed during the last layer of the computation to skip unused tokens
  13390. int32_t n_tokens = this->n_tokens;
  13391. const int64_t n_embd_head = hparams.n_embd_head_v;
  13392. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  13393. GGML_ASSERT(n_embd_head == hparams.n_rot);
  13394. struct ggml_tensor * cur;
  13395. struct ggml_tensor * inpL;
  13396. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  13397. // inp_pos - contains the positions
  13398. struct ggml_tensor * inp_pos = build_inp_pos();
  13399. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  13400. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  13401. for (int il = 0; il < n_layer; ++il) {
  13402. struct ggml_tensor * inpSA = inpL;
  13403. // norm
  13404. if (hparams.swin_norm) {
  13405. cur = inpL;
  13406. } else {
  13407. cur = llm_build_norm(ctx0, inpL, hparams,
  13408. model.layers[il].attn_norm, NULL,
  13409. LLM_NORM_RMS, cb, il);
  13410. cb(cur, "attn_norm", il);
  13411. }
  13412. // self-attention
  13413. {
  13414. // compute Q and K and RoPE them
  13415. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  13416. cb(Qcur, "Qcur", il);
  13417. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  13418. cb(Kcur, "Kcur", il);
  13419. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  13420. cb(Vcur, "Vcur", il);
  13421. if (model.layers[il].attn_q_norm) {
  13422. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  13423. ggml_element_size(Qcur) * n_embd_head,
  13424. ggml_element_size(Qcur) * n_embd_head * n_head,
  13425. 0);
  13426. cb(Qcur, "Qcur", il);
  13427. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  13428. model.layers[il].attn_q_norm,
  13429. model.layers[il].attn_q_norm_b,
  13430. LLM_NORM, cb, il);
  13431. cb(Qcur, "Qcur", il);
  13432. }
  13433. if (model.layers[il].attn_k_norm) {
  13434. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  13435. ggml_element_size(Kcur) * n_embd_head,
  13436. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  13437. 0);
  13438. cb(Kcur, "Kcur", il);
  13439. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  13440. model.layers[il].attn_k_norm,
  13441. model.layers[il].attn_k_norm_b,
  13442. LLM_NORM, cb, il);
  13443. cb(Kcur, "Kcur", il);
  13444. }
  13445. Qcur = ggml_rope_ext(
  13446. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  13447. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13448. ext_factor, attn_factor, beta_fast, beta_slow
  13449. );
  13450. cb(Qcur, "Qcur", il);
  13451. Kcur = ggml_rope_ext(
  13452. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  13453. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  13454. ext_factor, attn_factor, beta_fast, beta_slow
  13455. );
  13456. cb(Kcur, "Kcur", il);
  13457. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  13458. model.layers[il].wo, nullptr,
  13459. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  13460. if (hparams.swin_norm) {
  13461. cur = llm_build_norm(ctx0, cur, hparams,
  13462. model.layers[il].attn_norm, NULL,
  13463. LLM_NORM_RMS, cb, il);
  13464. }
  13465. }
  13466. if (il == n_layer - 1) {
  13467. // skip computing output for unused tokens
  13468. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  13469. n_tokens = n_outputs;
  13470. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  13471. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  13472. }
  13473. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  13474. cb(ffn_inp, "ffn_inp", il);
  13475. // feed-forward network
  13476. if (!hparams.swin_norm) {
  13477. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  13478. model.layers[il].ffn_norm, NULL,
  13479. LLM_NORM_RMS, cb, il);
  13480. cb(cur, "ffn_norm", il);
  13481. }
  13482. cur = llm_build_ffn(ctx0, lctx, cur,
  13483. model.layers[il].ffn_up, NULL, NULL,
  13484. model.layers[il].ffn_gate, NULL, NULL,
  13485. model.layers[il].ffn_down, NULL, NULL,
  13486. NULL,
  13487. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  13488. cb(cur, "ffn_out", il);
  13489. if (hparams.swin_norm) {
  13490. cur = llm_build_norm(ctx0, cur, hparams,
  13491. model.layers[il].ffn_norm, NULL,
  13492. LLM_NORM_RMS, cb, il);
  13493. cb(cur, "ffn_norm", il);
  13494. }
  13495. cur = ggml_add(ctx0, cur, ffn_inp);
  13496. cb(cur, "ffn_out", il);
  13497. cur = lctx.cvec.apply_to(ctx0, cur, il);
  13498. cb(cur, "l_out", il);
  13499. // input for next layer
  13500. inpL = cur;
  13501. }
  13502. cur = inpL;
  13503. cur = llm_build_norm(ctx0, cur, hparams,
  13504. model.output_norm, NULL,
  13505. LLM_NORM_RMS, cb, -1);
  13506. cb(cur, "result_norm", -1);
  13507. // lm_head
  13508. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  13509. cb(cur, "result_output_with_img_logits", -1);
  13510. // TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
  13511. // Needs to be removed once image outputs are supported.
  13512. int img_token_end_idx = 8196;
  13513. int img_token_start_idx = 4;
  13514. int num_img_tokens = img_token_end_idx - img_token_start_idx;
  13515. // creates 1d tensor of size num_img_tokens and values -FLT_MAX,
  13516. // which ensures that text token values are always at least larger than image token values
  13517. struct ggml_tensor * img_logits = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, num_img_tokens);
  13518. img_logits = ggml_clamp(ctx0, img_logits, -FLT_MAX, -FLT_MAX);
  13519. cb(img_logits, "img_logits", -1);
  13520. cur = ggml_set_1d(ctx0, cur, img_logits, ggml_element_size(cur) * img_token_start_idx);
  13521. cb(cur, "result_output", -1);
  13522. ggml_build_forward_expand(gf, cur);
  13523. return gf;
  13524. }
  13525. };
  13526. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  13527. llama_ubatch dummy = {};
  13528. dummy.equal_seqs = true;
  13529. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  13530. struct llm_build_context llm(lctx, dummy, cb, false);
  13531. llm.init();
  13532. struct ggml_cgraph * result = llm.build_defrag(ids);
  13533. llm.free();
  13534. return result;
  13535. }
  13536. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  13537. llama_ubatch dummy = {};
  13538. dummy.equal_seqs = true;
  13539. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  13540. struct llm_build_context llm(lctx, dummy, cb, false);
  13541. llm.init();
  13542. struct ggml_cgraph * result = llm.build_k_shift();
  13543. llm.free();
  13544. return result;
  13545. }
  13546. static struct ggml_cgraph * llama_build_graph(
  13547. llama_context & lctx,
  13548. const llama_ubatch & batch,
  13549. bool worst_case) {
  13550. const auto & model = lctx.model;
  13551. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  13552. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  13553. if (il >= 0) {
  13554. ggml_format_name(cur, "%s-%d", name, il);
  13555. } else {
  13556. ggml_set_name(cur, name);
  13557. }
  13558. if (!lctx.cparams.offload_kqv) {
  13559. if (strcmp(name, "kqv_merged_cont") == 0) {
  13560. // all nodes between the KV store and the attention output are run on the CPU
  13561. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  13562. }
  13563. }
  13564. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  13565. // FIXME: fix in ggml_backend_sched
  13566. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  13567. if (batch.n_tokens < 32 || full_offload) {
  13568. if (il != -1 && strcmp(name, "norm") == 0) {
  13569. for (auto * backend : lctx.backends) {
  13570. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  13571. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  13572. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  13573. break;
  13574. }
  13575. }
  13576. }
  13577. }
  13578. };
  13579. struct ggml_cgraph * result = NULL;
  13580. struct llm_build_context llm(lctx, batch, cb, worst_case);
  13581. llm.init();
  13582. switch (model.arch) {
  13583. case LLM_ARCH_LLAMA:
  13584. case LLM_ARCH_GRANITE:
  13585. case LLM_ARCH_GRANITE_MOE:
  13586. {
  13587. result = llm.build_llama();
  13588. } break;
  13589. case LLM_ARCH_BAICHUAN:
  13590. {
  13591. result = llm.build_baichuan();
  13592. } break;
  13593. case LLM_ARCH_FALCON:
  13594. {
  13595. result = llm.build_falcon();
  13596. } break;
  13597. case LLM_ARCH_GROK:
  13598. {
  13599. result = llm.build_grok();
  13600. } break;
  13601. case LLM_ARCH_STARCODER:
  13602. {
  13603. result = llm.build_starcoder();
  13604. } break;
  13605. case LLM_ARCH_REFACT:
  13606. {
  13607. result = llm.build_refact();
  13608. } break;
  13609. case LLM_ARCH_BERT:
  13610. case LLM_ARCH_JINA_BERT_V2:
  13611. case LLM_ARCH_NOMIC_BERT:
  13612. {
  13613. result = llm.build_bert();
  13614. } break;
  13615. case LLM_ARCH_BLOOM:
  13616. {
  13617. result = llm.build_bloom();
  13618. } break;
  13619. case LLM_ARCH_MPT:
  13620. {
  13621. result = llm.build_mpt();
  13622. } break;
  13623. case LLM_ARCH_STABLELM:
  13624. {
  13625. result = llm.build_stablelm();
  13626. } break;
  13627. case LLM_ARCH_QWEN:
  13628. {
  13629. result = llm.build_qwen();
  13630. } break;
  13631. case LLM_ARCH_QWEN2:
  13632. {
  13633. result = llm.build_qwen2();
  13634. } break;
  13635. case LLM_ARCH_QWEN2MOE:
  13636. {
  13637. result = llm.build_qwen2moe();
  13638. } break;
  13639. case LLM_ARCH_PHI2:
  13640. {
  13641. result = llm.build_phi2();
  13642. } break;
  13643. case LLM_ARCH_PHI3:
  13644. {
  13645. result = llm.build_phi3();
  13646. } break;
  13647. case LLM_ARCH_PLAMO:
  13648. {
  13649. result = llm.build_plamo();
  13650. } break;
  13651. case LLM_ARCH_GPT2:
  13652. {
  13653. result = llm.build_gpt2();
  13654. } break;
  13655. case LLM_ARCH_CODESHELL:
  13656. {
  13657. result = llm.build_codeshell();
  13658. } break;
  13659. case LLM_ARCH_ORION:
  13660. {
  13661. result = llm.build_orion();
  13662. } break;
  13663. case LLM_ARCH_INTERNLM2:
  13664. {
  13665. result = llm.build_internlm2();
  13666. } break;
  13667. case LLM_ARCH_MINICPM:
  13668. {
  13669. result = llm.build_minicpm();
  13670. } break;
  13671. case LLM_ARCH_MINICPM3:
  13672. {
  13673. result = llm.build_minicpm3();
  13674. } break;
  13675. case LLM_ARCH_GEMMA:
  13676. {
  13677. result = llm.build_gemma();
  13678. } break;
  13679. case LLM_ARCH_GEMMA2:
  13680. {
  13681. result = llm.build_gemma2();
  13682. } break;
  13683. case LLM_ARCH_STARCODER2:
  13684. {
  13685. result = llm.build_starcoder2();
  13686. } break;
  13687. case LLM_ARCH_MAMBA:
  13688. {
  13689. result = llm.build_mamba();
  13690. } break;
  13691. case LLM_ARCH_XVERSE:
  13692. {
  13693. result = llm.build_xverse();
  13694. } break;
  13695. case LLM_ARCH_COMMAND_R:
  13696. {
  13697. result = llm.build_command_r();
  13698. } break;
  13699. case LLM_ARCH_DBRX:
  13700. {
  13701. result = llm.build_dbrx();
  13702. } break;
  13703. case LLM_ARCH_OLMO:
  13704. {
  13705. result = llm.build_olmo();
  13706. } break;
  13707. case LLM_ARCH_OLMOE:
  13708. {
  13709. result = llm.build_olmoe();
  13710. } break;
  13711. case LLM_ARCH_OPENELM:
  13712. {
  13713. result = llm.build_openelm();
  13714. } break;
  13715. case LLM_ARCH_GPTNEOX:
  13716. {
  13717. result = llm.build_gptneox();
  13718. } break;
  13719. case LLM_ARCH_ARCTIC:
  13720. {
  13721. result = llm.build_arctic();
  13722. } break;
  13723. case LLM_ARCH_DEEPSEEK2:
  13724. {
  13725. result = llm.build_deepseek2();
  13726. } break;
  13727. case LLM_ARCH_CHATGLM:
  13728. {
  13729. result = llm.build_chatglm();
  13730. } break;
  13731. case LLM_ARCH_BITNET:
  13732. {
  13733. result = llm.build_bitnet();
  13734. } break;
  13735. case LLM_ARCH_T5:
  13736. {
  13737. if (lctx.is_encoding) {
  13738. result = llm.build_t5_encoder();
  13739. } else {
  13740. result = llm.build_t5_decoder();
  13741. }
  13742. } break;
  13743. case LLM_ARCH_T5ENCODER:
  13744. {
  13745. result = llm.build_t5_encoder();
  13746. } break;
  13747. case LLM_ARCH_JAIS:
  13748. {
  13749. result = llm.build_jais();
  13750. } break;
  13751. case LLM_ARCH_NEMOTRON:
  13752. {
  13753. result = llm.build_nemotron();
  13754. } break;
  13755. case LLM_ARCH_EXAONE:
  13756. {
  13757. result = llm.build_exaone();
  13758. } break;
  13759. case LLM_ARCH_RWKV6:
  13760. {
  13761. result = llm.build_rwkv6();
  13762. } break;
  13763. case LLM_ARCH_CHAMELEON:
  13764. {
  13765. result = llm.build_chameleon();
  13766. } break;
  13767. default:
  13768. GGML_ABORT("fatal error");
  13769. }
  13770. // add on pooling layer
  13771. if (lctx.cparams.embeddings) {
  13772. result = llm.append_pooling(result);
  13773. }
  13774. llm.free();
  13775. return result;
  13776. }
  13777. static void llama_set_k_shift(llama_context & lctx) {
  13778. const int64_t kv_size = lctx.kv_self.size;
  13779. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  13780. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  13781. for (int i = 0; i < kv_size; ++i) {
  13782. data[i] = lctx.kv_self.cells[i].delta;
  13783. }
  13784. }
  13785. static void llama_set_s_copy(llama_context & lctx) {
  13786. const int64_t kv_size = lctx.kv_self.size;
  13787. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  13788. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  13789. for (int i = 0; i < kv_size; ++i) {
  13790. data[i] = lctx.kv_self.cells[i].src;
  13791. }
  13792. }
  13793. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  13794. // TODO move to hparams if a T5 variant appears that uses a different value
  13795. const int64_t max_distance = 128;
  13796. if (bidirectional) {
  13797. n_buckets >>= 1;
  13798. }
  13799. const int64_t max_exact = n_buckets >> 1;
  13800. int32_t relative_position = x - y;
  13801. int32_t relative_bucket = 0;
  13802. if (bidirectional) {
  13803. relative_bucket += (relative_position > 0) * n_buckets;
  13804. relative_position = abs(relative_position);
  13805. } else {
  13806. relative_position = -std::min<int32_t>(relative_position, 0);
  13807. }
  13808. 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));
  13809. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  13810. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  13811. return relative_bucket;
  13812. }
  13813. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & batch) {
  13814. //
  13815. // set input data
  13816. //
  13817. const auto & hparams = lctx.model.hparams;
  13818. const auto & cparams = lctx.cparams;
  13819. const auto & kv_self = lctx.kv_self;
  13820. if (batch.token) {
  13821. const int64_t n_tokens = batch.n_tokens;
  13822. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  13823. }
  13824. if (batch.embd) {
  13825. const int64_t n_embd = hparams.n_embd;
  13826. const int64_t n_tokens = batch.n_tokens;
  13827. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  13828. }
  13829. if (batch.pos && lctx.inp_pos) {
  13830. const int64_t n_tokens = batch.n_tokens;
  13831. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  13832. }
  13833. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  13834. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  13835. const int64_t n_tokens = batch.n_tokens;
  13836. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  13837. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  13838. if (lctx.n_outputs == n_tokens) {
  13839. for (int i = 0; i < n_tokens; ++i) {
  13840. data[i] = i;
  13841. }
  13842. } else if (batch.output) {
  13843. int32_t n_outputs = 0;
  13844. for (int i = 0; i < n_tokens; ++i) {
  13845. if (batch.output[i]) {
  13846. data[n_outputs++] = i;
  13847. }
  13848. }
  13849. // the graph needs to have been passed the correct number of outputs
  13850. GGML_ASSERT(lctx.n_outputs == n_outputs);
  13851. } else if (lctx.n_outputs == 1) {
  13852. // only keep last output
  13853. data[0] = n_tokens - 1;
  13854. } else {
  13855. GGML_ASSERT(lctx.n_outputs == 0);
  13856. }
  13857. }
  13858. GGML_ASSERT(
  13859. // (!a || b) is a logical implication (a -> b)
  13860. // !hparams.causal_attn -> !cparams.causal_attn
  13861. (hparams.causal_attn || !cparams.causal_attn) &&
  13862. "causal attention is not supported by this model"
  13863. );
  13864. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  13865. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  13866. if (cparams.causal_attn && !lctx.is_encoding) {
  13867. const int64_t n_kv = kv_self.n;
  13868. const int64_t n_tokens = batch.n_tokens;
  13869. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13870. const int64_t n_seqs = batch.n_seqs;
  13871. float * data = nullptr;
  13872. float * data_swa = nullptr;
  13873. if (lctx.inp_KQ_mask) {
  13874. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  13875. data = (float *) lctx.inp_KQ_mask->data;
  13876. }
  13877. if (lctx.inp_KQ_mask_swa) {
  13878. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  13879. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  13880. }
  13881. // For causal attention, use only the previous KV cells
  13882. // of the correct sequence for each token of the batch.
  13883. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  13884. for (int h = 0; h < 1; ++h) {
  13885. for (int s = 0; s < n_seqs; ++s) {
  13886. const llama_seq_id seq_id = batch.seq_id[s][0];
  13887. for (int j = 0; j < n_seq_tokens; ++j) {
  13888. const llama_pos pos = batch.pos[s*n_seq_tokens + j];
  13889. for (int i = 0; i < n_kv; ++i) {
  13890. float f;
  13891. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  13892. f = -INFINITY;
  13893. } else {
  13894. if (hparams.use_alibi) {
  13895. f = -std::abs(kv_self.cells[i].pos - pos);
  13896. } else {
  13897. f = 0.0f;
  13898. }
  13899. }
  13900. if (data) {
  13901. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  13902. }
  13903. // may need to cut off old tokens for sliding window
  13904. if (data_swa) {
  13905. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  13906. f = -INFINITY;
  13907. }
  13908. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  13909. }
  13910. }
  13911. }
  13912. }
  13913. if (data) {
  13914. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  13915. for (int j = 0; j < n_kv; ++j) {
  13916. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  13917. }
  13918. }
  13919. }
  13920. if (data_swa) {
  13921. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  13922. for (int j = 0; j < n_kv; ++j) {
  13923. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  13924. }
  13925. }
  13926. }
  13927. }
  13928. } else {
  13929. const int64_t n_tokens = batch.n_tokens;
  13930. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13931. const int64_t n_seqs = batch.n_seqs;
  13932. // when using kv cache, the mask needs to match the kv cache size
  13933. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  13934. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  13935. float * data = (float *) lctx.inp_KQ_mask->data;
  13936. for (int h = 0; h < 1; ++h) {
  13937. for (int s1 = 0; s1 < n_seqs; ++s1) {
  13938. const llama_seq_id seq_id = batch.seq_id[s1][0];
  13939. for (int j = 0; j < n_seq_tokens; ++j) {
  13940. const int32_t tj = s1*n_seq_tokens + j;
  13941. for (int s0 = 0; s0 < n_seqs; ++s0) {
  13942. for (int i = 0; i < n_seq_tokens; ++i) {
  13943. const int32_t ti = s0*n_seq_tokens + i;
  13944. float f = -INFINITY;
  13945. for (int s = 0; s < batch.n_seq_id[s0]; ++s) {
  13946. if (batch.seq_id[s0][s] == seq_id) {
  13947. if (hparams.use_alibi) {
  13948. f = -std::abs(batch.pos[ti] - batch.pos[tj]);
  13949. } else {
  13950. f = 0.0f;
  13951. }
  13952. break;
  13953. }
  13954. }
  13955. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  13956. }
  13957. }
  13958. for (int i = n_tokens; i < n_stride; ++i) {
  13959. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  13960. }
  13961. }
  13962. }
  13963. }
  13964. }
  13965. }
  13966. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  13967. const int64_t n_tokens = batch.n_tokens;
  13968. const int64_t n_seq_tokens = batch.n_seq_tokens;
  13969. const int64_t n_seqs = batch.n_seqs;
  13970. GGML_ASSERT(lctx.inp_mean);
  13971. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  13972. float * data = (float *) lctx.inp_mean->data;
  13973. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  13974. std::vector<uint64_t> sum(n_tokens, 0);
  13975. for (int s = 0; s < n_seqs; ++s) {
  13976. const llama_seq_id seq_id = batch.seq_id[s][0];
  13977. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  13978. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  13979. sum[seq_id] += batch.n_seq_tokens;
  13980. }
  13981. std::vector<float> div(n_tokens, 0.0f);
  13982. for (int i = 0; i < n_tokens; ++i) {
  13983. const uint64_t s = sum[i];
  13984. if (s > 0) {
  13985. div[i] = 1.0f/float(s);
  13986. }
  13987. }
  13988. for (int s = 0; s < n_seqs; ++s) {
  13989. const llama_seq_id seq_id = batch.seq_id[s][0];
  13990. for (int i = 0; i < n_seq_tokens; ++i) {
  13991. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  13992. }
  13993. }
  13994. }
  13995. if (cparams.embeddings && (
  13996. cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
  13997. cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
  13998. const int64_t n_tokens = batch.n_tokens;
  13999. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14000. const int64_t n_seqs = batch.n_seqs;
  14001. GGML_ASSERT(lctx.inp_cls);
  14002. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14003. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14004. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14005. for (int s = 0; s < n_seqs; ++s) {
  14006. const llama_seq_id seq_id = batch.seq_id[s][0];
  14007. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14008. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
  14009. for (int i = 0; i < n_seq_tokens; ++i) {
  14010. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14011. if (pos == 0) {
  14012. data[seq_id] = s*n_seq_tokens + i;
  14013. }
  14014. }
  14015. }
  14016. }
  14017. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  14018. const int64_t n_tokens = batch.n_tokens;
  14019. const int64_t n_seq_tokens = batch.n_seq_tokens;
  14020. const int64_t n_seqs = batch.n_seqs;
  14021. GGML_ASSERT(lctx.inp_cls);
  14022. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  14023. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  14024. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  14025. std::vector<int> last_pos(n_tokens, -1);
  14026. std::vector<int> last_row(n_tokens, -1);
  14027. for (int s = 0; s < n_seqs; ++s) {
  14028. const llama_seq_id seq_id = batch.seq_id[s][0];
  14029. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  14030. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  14031. for (int i = 0; i < n_seq_tokens; ++i) {
  14032. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  14033. if (pos >= last_pos[seq_id]) {
  14034. last_pos[seq_id] = pos;
  14035. last_row[seq_id] = s*n_seq_tokens + i;
  14036. }
  14037. }
  14038. }
  14039. for (int i = 0; i < n_tokens; ++i) {
  14040. if (last_row[i] >= 0) {
  14041. data[i] = last_row[i];
  14042. }
  14043. }
  14044. }
  14045. if (kv_self.recurrent) {
  14046. const int64_t n_kv = kv_self.n;
  14047. if (lctx.inp_s_mask) {
  14048. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  14049. float * data = (float *) lctx.inp_s_mask->data;
  14050. // clear unused states
  14051. for (int i = 0; i < n_kv; ++i) {
  14052. const uint32_t cell_id = i + kv_self.head;
  14053. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14054. data[i] = (float) (kv_cell.src >= 0);
  14055. // only clear once
  14056. if (kv_cell.src < 0) {
  14057. kv_cell.src = cell_id;
  14058. }
  14059. }
  14060. }
  14061. if (lctx.inp_s_copy) {
  14062. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  14063. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  14064. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  14065. for (uint32_t i = 0; i < n_kv; ++i) {
  14066. const uint32_t cell_id = i + kv_self.head;
  14067. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  14068. // prevent out-of-bound sources
  14069. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  14070. kv_cell.src = cell_id;
  14071. }
  14072. data[i] = kv_cell.src;
  14073. // ensure copy only happens once
  14074. if (kv_cell.src != (int32_t) cell_id) {
  14075. kv_cell.src = cell_id;
  14076. }
  14077. }
  14078. }
  14079. }
  14080. if (lctx.inp_pos_bucket) {
  14081. const int64_t n_tokens = batch.n_tokens;
  14082. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  14083. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14084. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  14085. if (!lctx.is_encoding) {
  14086. const int64_t n_kv = kv_self.n;
  14087. for (int h = 0; h < 1; ++h) {
  14088. for (int j = 0; j < n_tokens; ++j) {
  14089. for (int i = 0; i < n_kv; ++i) {
  14090. 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);
  14091. }
  14092. }
  14093. }
  14094. } else {
  14095. for (int h = 0; h < 1; ++h) {
  14096. for (int j = 0; j < n_tokens; ++j) {
  14097. for (int i = 0; i < n_tokens; ++i) {
  14098. 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);
  14099. }
  14100. }
  14101. }
  14102. }
  14103. }
  14104. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  14105. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  14106. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  14107. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  14108. }
  14109. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  14110. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  14111. const int64_t n_tokens = batch.n_tokens;
  14112. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  14113. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  14114. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  14115. for (int h = 0; h < 1; ++h) {
  14116. for (int j = 0; j < n_tokens; ++j) {
  14117. for (int i = 0; i < n_output_enc; ++i) {
  14118. float f = -INFINITY;
  14119. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  14120. const llama_seq_id seq_id = batch.seq_id[j][s];
  14121. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  14122. f = 0.0f;
  14123. }
  14124. }
  14125. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  14126. }
  14127. }
  14128. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  14129. for (int j = 0; j < n_output_enc; ++j) {
  14130. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  14131. }
  14132. }
  14133. }
  14134. }
  14135. }
  14136. // Make sure enough space is available for outputs.
  14137. // Returns max number of outputs for which space was reserved.
  14138. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  14139. const auto & cparams = lctx.cparams;
  14140. const auto & hparams = lctx.model.hparams;
  14141. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  14142. const auto n_batch = cparams.n_batch;
  14143. const auto n_vocab = hparams.n_vocab;
  14144. const auto n_embd = hparams.n_embd;
  14145. // TODO: use a per-batch flag for logits presence instead
  14146. const bool has_logits = !cparams.embeddings;
  14147. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  14148. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  14149. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  14150. if (lctx.output_ids.empty()) {
  14151. // init, never resized afterwards
  14152. lctx.output_ids.resize(n_batch);
  14153. }
  14154. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  14155. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  14156. // alloc only when more than the current capacity is required
  14157. // TODO: also consider shrinking the buffer
  14158. if (!lctx.buf_output || prev_size < new_size) {
  14159. if (lctx.buf_output) {
  14160. #ifndef NDEBUG
  14161. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  14162. 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);
  14163. #endif
  14164. ggml_backend_buffer_free(lctx.buf_output);
  14165. lctx.buf_output = nullptr;
  14166. lctx.logits = nullptr;
  14167. lctx.embd = nullptr;
  14168. }
  14169. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(lctx.model, true), new_size);
  14170. if (lctx.buf_output == nullptr) {
  14171. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  14172. return 0;
  14173. }
  14174. }
  14175. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  14176. lctx.logits = has_logits ? output_base : nullptr;
  14177. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  14178. lctx.output_size = n_outputs_max;
  14179. lctx.logits_size = logits_size;
  14180. lctx.embd_size = embd_size;
  14181. // set all ids as invalid (negative)
  14182. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  14183. ggml_backend_buffer_clear(lctx.buf_output, 0);
  14184. lctx.n_outputs = 0;
  14185. return n_outputs_max;
  14186. }
  14187. // make the outputs have the same order they had in the user-provided batch
  14188. static void llama_output_reorder(struct llama_context * ctx) {
  14189. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  14190. if (!out_ids.empty()) {
  14191. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  14192. uint32_t n_embd = ctx->model.hparams.n_embd;
  14193. int32_t n_outputs = ctx->n_outputs;
  14194. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  14195. // TODO: is there something more efficient which also minimizes swaps?
  14196. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  14197. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  14198. int32_t j_min = i;
  14199. for (int32_t j = i + 1; j < n_outputs; ++j) {
  14200. if (out_ids[j] < out_ids[j_min]) {
  14201. j_min = j;
  14202. }
  14203. }
  14204. if (j_min == i) { continue; }
  14205. std::swap(out_ids[i], out_ids[j_min]);
  14206. if (ctx->logits_size > 0) {
  14207. for (uint32_t k = 0; k < n_vocab; k++) {
  14208. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  14209. }
  14210. }
  14211. if (ctx->embd_size > 0) {
  14212. for (uint32_t k = 0; k < n_embd; k++) {
  14213. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  14214. }
  14215. }
  14216. }
  14217. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  14218. for (int32_t i = 0; i < n_outputs; ++i) {
  14219. ctx->output_ids[out_ids[i]] = i;
  14220. }
  14221. out_ids.clear();
  14222. }
  14223. }
  14224. static void llama_graph_compute(
  14225. llama_context & lctx,
  14226. ggml_cgraph * gf,
  14227. int n_threads,
  14228. ggml_threadpool * threadpool) {
  14229. if (lctx.backend_cpu != nullptr) {
  14230. ggml_backend_cpu_set_threadpool(lctx.backend_cpu, threadpool);
  14231. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  14232. }
  14233. // set the number of threads for all the backends
  14234. for (const auto & set_n_threads_fn : lctx.set_n_threads_fns) {
  14235. set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
  14236. }
  14237. auto err = ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  14238. if (err != GGML_STATUS_SUCCESS) {
  14239. LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, err);
  14240. }
  14241. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  14242. }
  14243. // decode a batch of tokens by evaluating the transformer
  14244. //
  14245. // - lctx: llama context
  14246. // - batch: batch to evaluate
  14247. //
  14248. // return 0 on success
  14249. // return positive int on warning
  14250. // return negative int on error
  14251. //
  14252. static int llama_decode_internal(
  14253. llama_context & lctx,
  14254. llama_batch batch) {
  14255. lctx.is_encoding = false;
  14256. const uint32_t n_tokens_all = batch.n_tokens;
  14257. if (n_tokens_all == 0) {
  14258. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  14259. return -1;
  14260. }
  14261. const auto & model = lctx.model;
  14262. const auto & hparams = model.hparams;
  14263. const auto & cparams = lctx.cparams;
  14264. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  14265. if (batch.token) {
  14266. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14267. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  14268. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  14269. return -1;
  14270. }
  14271. }
  14272. }
  14273. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  14274. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  14275. if (lctx.t_compute_start_us == 0) {
  14276. lctx.t_compute_start_us = ggml_time_us();
  14277. }
  14278. lctx.n_queued_tokens += n_tokens_all;
  14279. auto & kv_self = lctx.kv_self;
  14280. const int64_t n_embd = hparams.n_embd;
  14281. const int64_t n_vocab = hparams.n_vocab;
  14282. uint32_t n_outputs = 0;
  14283. uint32_t n_outputs_prev = 0;
  14284. const auto n_ubatch = cparams.n_ubatch;
  14285. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  14286. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  14287. lctx.embd_seq.clear();
  14288. // count outputs
  14289. if (batch.logits && !embd_pooled) {
  14290. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  14291. n_outputs += batch.logits[i] != 0;
  14292. }
  14293. } else if (lctx.logits_all || embd_pooled) {
  14294. n_outputs = n_tokens_all;
  14295. } else {
  14296. // keep last output only
  14297. n_outputs = 1;
  14298. }
  14299. lctx.sbatch.from_batch(batch, n_embd,
  14300. /* simple_split */ !kv_self.recurrent,
  14301. /* logits_all */ n_outputs == n_tokens_all);
  14302. // reserve output buffer
  14303. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  14304. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  14305. return -2;
  14306. };
  14307. while (lctx.sbatch.n_tokens > 0) {
  14308. llama_ubatch ubatch;
  14309. if (kv_self.recurrent) {
  14310. if (embd_pooled) {
  14311. // Pooled embeddings cannot be split across ubatches (yet)
  14312. ubatch = lctx.sbatch.split_seq(n_ubatch);
  14313. } else {
  14314. // recurrent model architectures are easier to implement
  14315. // with equal-length sequences
  14316. ubatch = lctx.sbatch.split_equal(n_ubatch);
  14317. }
  14318. } else {
  14319. ubatch = lctx.sbatch.split_simple(n_ubatch);
  14320. }
  14321. const uint32_t n_tokens = ubatch.n_tokens;
  14322. // count the outputs in this u_batch
  14323. {
  14324. int32_t n_outputs_new = 0;
  14325. if (n_outputs == n_tokens_all) {
  14326. n_outputs_new = n_tokens;
  14327. } else {
  14328. GGML_ASSERT(ubatch.output);
  14329. for (uint32_t i = 0; i < n_tokens; i++) {
  14330. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  14331. }
  14332. }
  14333. // needs to happen before the graph is built
  14334. lctx.n_outputs = n_outputs_new;
  14335. }
  14336. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  14337. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  14338. GGML_ASSERT(n_threads > 0);
  14339. // non-causal masks do not use the KV cache
  14340. if (hparams.causal_attn) {
  14341. llama_kv_cache_update(&lctx);
  14342. // if we have enough unused cells before the current head ->
  14343. // better to start searching from the beginning of the cache, hoping to fill it
  14344. if (kv_self.head > kv_self.used + 2*n_tokens) {
  14345. kv_self.head = 0;
  14346. }
  14347. if (!llama_kv_cache_find_slot(kv_self, ubatch)) {
  14348. return 1;
  14349. }
  14350. if (!kv_self.recurrent) {
  14351. // a heuristic, to avoid attending the full cache if it is not yet utilized
  14352. // after enough generations, the benefit from this heuristic disappears
  14353. // if we start defragmenting the cache, the benefit from this will be more important
  14354. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  14355. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  14356. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  14357. }
  14358. }
  14359. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  14360. ggml_backend_sched_reset(lctx.sched);
  14361. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  14362. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  14363. // the output is always the last tensor in the graph
  14364. struct ggml_tensor * res = ggml_graph_node(gf, -1);
  14365. struct ggml_tensor * embd = ggml_graph_node(gf, -2);
  14366. if (lctx.n_outputs == 0) {
  14367. // no output
  14368. res = nullptr;
  14369. embd = nullptr;
  14370. } else if (cparams.embeddings) {
  14371. res = nullptr; // do not extract logits for embedding case
  14372. embd = nullptr;
  14373. for (int i = ggml_graph_n_nodes(gf) - 1; i >= 0; --i) {
  14374. if (strcmp(ggml_graph_node(gf, i)->name, "result_embd_pooled") == 0) {
  14375. embd = ggml_graph_node(gf, i);
  14376. break;
  14377. }
  14378. }
  14379. GGML_ASSERT(embd != nullptr && "missing embeddings tensor");
  14380. } else {
  14381. embd = nullptr; // do not extract embeddings when not needed
  14382. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  14383. }
  14384. // 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);
  14385. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  14386. llama_set_inputs(lctx, ubatch);
  14387. llama_graph_compute(lctx, gf, n_threads, threadpool);
  14388. // update the kv ring buffer
  14389. {
  14390. kv_self.head += n_tokens;
  14391. // Ensure kv cache head points to a valid index.
  14392. if (kv_self.head >= kv_self.size) {
  14393. kv_self.head = 0;
  14394. }
  14395. }
  14396. // plot the computation graph in dot format (for debugging purposes)
  14397. //if (n_past%100 == 0) {
  14398. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  14399. //}
  14400. // extract logits
  14401. if (res) {
  14402. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  14403. GGML_ASSERT(backend_res != nullptr);
  14404. GGML_ASSERT(lctx.logits != nullptr);
  14405. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  14406. const int32_t n_outputs_new = lctx.n_outputs;
  14407. if (n_outputs_new) {
  14408. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14409. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  14410. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  14411. }
  14412. }
  14413. // extract embeddings
  14414. if (embd) {
  14415. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  14416. GGML_ASSERT(backend_embd != nullptr);
  14417. switch (cparams.pooling_type) {
  14418. case LLAMA_POOLING_TYPE_NONE:
  14419. {
  14420. // extract token embeddings
  14421. GGML_ASSERT(lctx.embd != nullptr);
  14422. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  14423. const int32_t n_outputs_new = lctx.n_outputs;
  14424. if (n_outputs_new) {
  14425. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  14426. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  14427. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  14428. }
  14429. } break;
  14430. case LLAMA_POOLING_TYPE_MEAN:
  14431. case LLAMA_POOLING_TYPE_CLS:
  14432. case LLAMA_POOLING_TYPE_LAST:
  14433. {
  14434. // extract sequence embeddings (cleared before processing each batch)
  14435. auto & embd_seq_out = lctx.embd_seq;
  14436. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14437. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14438. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14439. continue;
  14440. }
  14441. embd_seq_out[seq_id].resize(n_embd);
  14442. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  14443. }
  14444. } break;
  14445. case LLAMA_POOLING_TYPE_RANK:
  14446. {
  14447. // extract the rerank score - a single float per sequence
  14448. auto & embd_seq_out = lctx.embd_seq;
  14449. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  14450. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  14451. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14452. continue;
  14453. }
  14454. embd_seq_out[seq_id].resize(1);
  14455. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (seq_id)*sizeof(float), sizeof(float));
  14456. }
  14457. } break;
  14458. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  14459. {
  14460. GGML_ABORT("unknown pooling type");
  14461. }
  14462. }
  14463. }
  14464. n_outputs_prev += lctx.n_outputs;
  14465. }
  14466. // set output mappings
  14467. {
  14468. bool sorted_output = true;
  14469. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  14470. for (size_t i = 0; i < n_outputs; ++i) {
  14471. size_t out_id = lctx.sbatch.out_ids[i];
  14472. lctx.output_ids[out_id] = i;
  14473. if (out_id != i) {
  14474. sorted_output = false;
  14475. }
  14476. }
  14477. if (sorted_output) {
  14478. lctx.sbatch.out_ids.clear();
  14479. }
  14480. }
  14481. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  14482. lctx.n_outputs = n_outputs;
  14483. // wait for the computation to finish (automatically done when obtaining the model output)
  14484. //llama_synchronize(&lctx);
  14485. // decide if we need to defrag the kv cache
  14486. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  14487. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  14488. // queue defragmentation for next llama_kv_cache_update
  14489. if (fragmentation > cparams.defrag_thold) {
  14490. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  14491. llama_kv_cache_defrag(kv_self);
  14492. }
  14493. }
  14494. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  14495. // overlap with device computation.
  14496. ggml_backend_sched_reset(lctx.sched);
  14497. return 0;
  14498. }
  14499. // encode a batch of tokens by evaluating the encoder part of the transformer
  14500. //
  14501. // - lctx: llama context
  14502. // - batch: batch to evaluate
  14503. //
  14504. // return 0 on success
  14505. // return positive int on warning
  14506. // return negative int on error
  14507. //
  14508. static int llama_encode_internal(
  14509. llama_context & lctx,
  14510. llama_batch batch) {
  14511. lctx.is_encoding = true;
  14512. const uint32_t n_tokens = batch.n_tokens;
  14513. if (n_tokens == 0) {
  14514. LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
  14515. return -1;
  14516. }
  14517. const auto & model = lctx.model;
  14518. const auto & hparams = model.hparams;
  14519. const auto & cparams = lctx.cparams;
  14520. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  14521. if (batch.token) {
  14522. for (uint32_t i = 0; i < n_tokens; ++i) {
  14523. if (batch.token[i] < 0 || (uint32_t)batch.token[i] >= model.vocab.n_vocab) {
  14524. LLAMA_LOG_ERROR("%s: invalid token[%d] = %d\n", __func__, i, batch.token[i]);
  14525. return -1;
  14526. }
  14527. }
  14528. }
  14529. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  14530. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  14531. if (lctx.t_compute_start_us == 0) {
  14532. lctx.t_compute_start_us = ggml_time_us();
  14533. }
  14534. lctx.n_queued_tokens += n_tokens;
  14535. const int64_t n_embd = hparams.n_embd;
  14536. lctx.sbatch.from_batch(batch, n_embd, /* simple_split */ true, /* logits_all */ true);
  14537. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  14538. // reserve output buffer
  14539. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  14540. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  14541. return -2;
  14542. };
  14543. for (uint32_t i = 0; i < n_tokens; ++i) {
  14544. lctx.output_ids[i] = i;
  14545. }
  14546. lctx.inp_embd_enc = NULL;
  14547. lctx.n_outputs = n_tokens;
  14548. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  14549. ggml_threadpool_t threadpool = n_tokens == 1 ? lctx.threadpool : lctx.threadpool_batch;
  14550. GGML_ASSERT(n_threads > 0);
  14551. ggml_backend_sched_reset(lctx.sched);
  14552. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  14553. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  14554. // the output embeddings after the final encoder normalization
  14555. struct ggml_tensor * embd = nullptr;
  14556. // there are two cases here
  14557. if (llama_model_has_decoder(&lctx.model)) {
  14558. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  14559. embd = ggml_graph_node(gf, -1);
  14560. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  14561. } else {
  14562. // second case is an encoder-only T5 model
  14563. if (cparams.embeddings) {
  14564. // only output embeddings if required
  14565. embd = ggml_graph_node(gf, -1);
  14566. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  14567. embd = ggml_graph_node(gf, -2);
  14568. }
  14569. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  14570. }
  14571. }
  14572. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  14573. llama_set_inputs(lctx, ubatch);
  14574. llama_graph_compute(lctx, gf, n_threads, threadpool);
  14575. // extract embeddings
  14576. if (embd) {
  14577. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  14578. GGML_ASSERT(backend_embd != nullptr);
  14579. if (llama_model_has_decoder(&lctx.model)) {
  14580. lctx.embd_enc.resize(n_tokens*n_embd);
  14581. float * embd_out = lctx.embd_enc.data();
  14582. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  14583. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  14584. // remember the sequence ids used during the encoding - needed for cross attention later
  14585. lctx.seq_ids_enc.resize(n_tokens);
  14586. for (uint32_t i = 0; i < n_tokens; i++) {
  14587. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  14588. llama_seq_id seq_id = ubatch.seq_id[i][s];
  14589. lctx.seq_ids_enc[i].insert(seq_id);
  14590. }
  14591. }
  14592. } else {
  14593. GGML_ASSERT(lctx.embd != nullptr);
  14594. switch (cparams.pooling_type) {
  14595. case LLAMA_POOLING_TYPE_NONE:
  14596. {
  14597. // extract token embeddings
  14598. GGML_ASSERT(lctx.embd != nullptr);
  14599. float * embd_out = lctx.embd;
  14600. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  14601. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  14602. } break;
  14603. case LLAMA_POOLING_TYPE_MEAN:
  14604. case LLAMA_POOLING_TYPE_CLS:
  14605. case LLAMA_POOLING_TYPE_LAST:
  14606. {
  14607. // extract sequence embeddings
  14608. auto & embd_seq_out = lctx.embd_seq;
  14609. embd_seq_out.clear();
  14610. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  14611. for (uint32_t i = 0; i < n_tokens; i++) {
  14612. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  14613. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  14614. continue;
  14615. }
  14616. embd_seq_out[seq_id].resize(n_embd);
  14617. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  14618. }
  14619. } break;
  14620. case LLAMA_POOLING_TYPE_RANK:
  14621. {
  14622. // TODO: this likely should be the same logic as in llama_decoder_internal, but better to
  14623. // wait for an encoder model that requires this pooling type in order to test it
  14624. // https://github.com/ggerganov/llama.cpp/pull/9510
  14625. GGML_ABORT("RANK pooling not implemented yet");
  14626. }
  14627. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  14628. {
  14629. GGML_ABORT("unknown pooling type");
  14630. }
  14631. }
  14632. }
  14633. }
  14634. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  14635. // overlap with device computation.
  14636. ggml_backend_sched_reset(lctx.sched);
  14637. return 0;
  14638. }
  14639. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  14640. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  14641. auto & kv_self = lctx.kv_self;
  14642. const auto & hparams = lctx.model.hparams;
  14643. const uint32_t n_layer = hparams.n_layer;
  14644. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  14645. const uint32_t n_used = kv_self.used;
  14646. assert(n_used <= n_kv);
  14647. //const int64_t t_start = ggml_time_us();
  14648. // number of cells moved
  14649. uint32_t n_moves = 0;
  14650. // each move requires 6*n_layer tensors (see build_defrag)
  14651. // - source view, destination view, copy operation
  14652. // - x2 for keys and values
  14653. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  14654. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  14655. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  14656. // determine which KV cells to move where
  14657. //
  14658. // cell i moves to ids[i]
  14659. //
  14660. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  14661. //
  14662. std::vector<uint32_t> ids(n_kv, n_kv);
  14663. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  14664. const auto & cell0 = kv_self.cells[i0];
  14665. if (!cell0.is_empty()) {
  14666. ids[i0] = i0;
  14667. continue;
  14668. }
  14669. // found a hole - fill it with data from the end of the cache
  14670. uint32_t nh = 1;
  14671. // determine the size of the hole
  14672. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  14673. nh++;
  14674. }
  14675. uint32_t nf = 0;
  14676. uint32_t is = n_kv - 1;
  14677. // starting from the end, find nh non-empty cells
  14678. for (; is > i0; --is) {
  14679. const auto & cell1 = kv_self.cells[is];
  14680. if (cell1.is_empty() || ids[is] != n_kv) {
  14681. continue;
  14682. }
  14683. // non-empty cell which is not yet moved
  14684. nf++;
  14685. if (nf == nh) {
  14686. break;
  14687. }
  14688. }
  14689. // this can only happen if `n_used` is not accurate, which would be a bug
  14690. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  14691. nf = 0;
  14692. uint32_t i1 = is;
  14693. // are we moving a continuous block of memory?
  14694. bool cont = false;
  14695. // should we stop searching for the next move?
  14696. bool stop = false;
  14697. // go back and move the nf cells to the hole
  14698. for (; i1 < n_kv; ++i1) {
  14699. auto & cell1 = kv_self.cells[i1];
  14700. if (cell1.is_empty() || ids[i1] != n_kv) {
  14701. if (n_moves == max_moves) {
  14702. stop = true;
  14703. break;
  14704. }
  14705. cont = false;
  14706. continue;
  14707. }
  14708. // this cell goes to (i0 + nf)
  14709. ids[i1] = i0 + nf;
  14710. // move the cell meta data
  14711. kv_self.cells[i0 + nf] = cell1;
  14712. // clear the old cell and move the head there
  14713. cell1 = llama_kv_cell();
  14714. kv_self.head = n_used;
  14715. if (!cont) {
  14716. n_moves++;
  14717. cont = true;
  14718. }
  14719. nf++;
  14720. if (nf == nh) {
  14721. break;
  14722. }
  14723. }
  14724. if (stop || n_moves == max_moves) {
  14725. break;
  14726. }
  14727. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  14728. i0 += nh - 1;
  14729. }
  14730. if (n_moves == 0) {
  14731. return;
  14732. }
  14733. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  14734. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  14735. #if 0
  14736. // CPU defrag
  14737. //
  14738. // TODO: optimizations are possible:
  14739. // - multiple threads
  14740. // - avoid copying to the host memory when already there
  14741. //
  14742. // likely not worth the effort, as we have ggml_graph based defrag
  14743. //
  14744. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  14745. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  14746. const uint32_t kv_size = kv_self.size;
  14747. std::vector<uint8_t> buf_k;
  14748. std::vector<uint8_t> buf_v;
  14749. for (uint32_t il = 0; il < n_layer; ++il) {
  14750. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14751. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  14752. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14753. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  14754. buf_k.resize(k_size);
  14755. buf_v.resize(v_size);
  14756. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  14757. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  14758. // batch move [i, i+nm) to [id, id+nm)
  14759. // note: cells can move only to a lower index
  14760. for (uint32_t i = 0; i < n_kv; ++i) {
  14761. const uint32_t id = ids[i];
  14762. if (i == id || id == n_kv) {
  14763. continue;
  14764. }
  14765. uint32_t nm = 1;
  14766. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  14767. nm++;
  14768. }
  14769. // move keys
  14770. {
  14771. const int64_t os = i*k_size_row;
  14772. const int64_t od = id*k_size_row;
  14773. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  14774. }
  14775. // move values (note: they are transposed)
  14776. {
  14777. const int64_t os = i;
  14778. const int64_t od = id;
  14779. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14780. 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);
  14781. }
  14782. }
  14783. i += nm - 1;
  14784. }
  14785. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  14786. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  14787. }
  14788. #else
  14789. // ggml_graph defrag
  14790. ggml_backend_sched_reset(lctx.sched);
  14791. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  14792. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  14793. #endif
  14794. //const int64_t t_end = ggml_time_us();
  14795. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  14796. }
  14797. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  14798. bool need_reserve = false;
  14799. // apply K-shift if needed
  14800. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  14801. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  14802. GGML_ABORT("Deepseek2 does not support K-shift");
  14803. }
  14804. {
  14805. ggml_backend_sched_reset(lctx.sched);
  14806. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  14807. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  14808. llama_set_k_shift(lctx);
  14809. llama_graph_compute(lctx, gf, lctx.cparams.n_threads, lctx.threadpool);
  14810. need_reserve = true;
  14811. }
  14812. {
  14813. auto & kv_self = lctx.kv_self;
  14814. kv_self.has_shift = false;
  14815. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14816. kv_self.cells[i].delta = 0;
  14817. }
  14818. }
  14819. }
  14820. // defragment the KV cache if needed
  14821. if (lctx.kv_self.do_defrag) {
  14822. llama_kv_cache_defrag_internal(lctx);
  14823. need_reserve = true;
  14824. lctx.kv_self.do_defrag = false;
  14825. }
  14826. // reserve a worst case graph again
  14827. if (need_reserve) {
  14828. // TODO: extract to a function
  14829. // build worst-case graph
  14830. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  14831. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  14832. 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
  14833. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  14834. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  14835. // initialize scheduler with the worst-case graph
  14836. ggml_backend_sched_reset(lctx.sched);
  14837. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  14838. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  14839. }
  14840. }
  14841. }
  14842. //
  14843. // quantization
  14844. //
  14845. struct quantize_state_internal {
  14846. const llama_model & model;
  14847. const llama_model_quantize_params * params;
  14848. int n_attention_wv = 0;
  14849. int n_ffn_down = 0;
  14850. int n_ffn_gate = 0;
  14851. int n_ffn_up = 0;
  14852. int i_attention_wv = 0;
  14853. int i_ffn_down = 0;
  14854. int i_ffn_gate = 0;
  14855. int i_ffn_up = 0;
  14856. int n_k_quantized = 0;
  14857. int n_fallback = 0;
  14858. bool has_imatrix = false;
  14859. // used to figure out if a model shares tok_embd with the output weight
  14860. bool has_output = false;
  14861. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  14862. : model(model)
  14863. , params(params)
  14864. {}
  14865. };
  14866. static void llama_tensor_dequantize_internal(
  14867. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  14868. const size_t nelements, const int nthread
  14869. ) {
  14870. if (output.size() < nelements) {
  14871. output.resize(nelements);
  14872. }
  14873. float * f32_output = (float *) output.data();
  14874. const ggml_type_traits * qtype = ggml_get_type_traits(tensor->type);
  14875. if (ggml_is_quantized(tensor->type)) {
  14876. if (qtype->to_float == NULL) {
  14877. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  14878. }
  14879. } else if (tensor->type != GGML_TYPE_F16 &&
  14880. tensor->type != GGML_TYPE_BF16) {
  14881. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  14882. }
  14883. if (nthread < 2) {
  14884. if (tensor->type == GGML_TYPE_F16) {
  14885. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  14886. } else if (tensor->type == GGML_TYPE_BF16) {
  14887. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  14888. } else if (ggml_is_quantized(tensor->type)) {
  14889. qtype->to_float(tensor->data, f32_output, nelements);
  14890. } else {
  14891. GGML_ABORT("fatal error"); // unreachable
  14892. }
  14893. return;
  14894. }
  14895. size_t block_size;
  14896. if (tensor->type == GGML_TYPE_F16 ||
  14897. tensor->type == GGML_TYPE_BF16) {
  14898. block_size = 1;
  14899. } else {
  14900. block_size = (size_t)ggml_blck_size(tensor->type);
  14901. }
  14902. size_t block_size_bytes = ggml_type_size(tensor->type);
  14903. GGML_ASSERT(nelements % block_size == 0);
  14904. size_t nblocks = nelements / block_size;
  14905. size_t blocks_per_thread = nblocks / nthread;
  14906. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  14907. size_t in_buff_offs = 0;
  14908. size_t out_buff_offs = 0;
  14909. for (int tnum = 0; tnum < nthread; tnum++) {
  14910. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  14911. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  14912. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  14913. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  14914. if (typ == GGML_TYPE_F16) {
  14915. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  14916. } else if (typ == GGML_TYPE_BF16) {
  14917. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  14918. } else {
  14919. qtype->to_float(inbuf, outbuf, nels);
  14920. }
  14921. };
  14922. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  14923. in_buff_offs += thr_block_bytes;
  14924. out_buff_offs += thr_elems;
  14925. }
  14926. for (auto & w : workers) { w.join(); }
  14927. workers.clear();
  14928. }
  14929. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  14930. const std::string name = ggml_get_name(tensor);
  14931. // TODO: avoid hardcoded tensor names - use the TN_* constants
  14932. const llm_arch arch = qs.model.arch;
  14933. const auto tn = LLM_TN(arch);
  14934. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  14935. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  14936. };
  14937. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  14938. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  14939. if (n_expert > 1) {
  14940. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  14941. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  14942. // for getting the current layer as I initially thought, and we need to resort to parsing the
  14943. // tensor name.
  14944. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  14945. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  14946. }
  14947. if (i_layer < 0 || i_layer >= n_layer) {
  14948. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  14949. }
  14950. }
  14951. return std::make_pair(i_layer, n_layer);
  14952. };
  14953. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  14954. // with the quantization of the output tensor
  14955. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  14956. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  14957. new_type = qs.params->output_tensor_type;
  14958. } else {
  14959. int nx = tensor->ne[0];
  14960. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  14961. new_type = GGML_TYPE_Q8_0;
  14962. }
  14963. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  14964. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  14965. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  14966. new_type = GGML_TYPE_Q5_K;
  14967. }
  14968. else if (new_type != GGML_TYPE_Q8_0) {
  14969. new_type = GGML_TYPE_Q6_K;
  14970. }
  14971. }
  14972. } else if (name == "token_embd.weight") {
  14973. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  14974. new_type = qs.params->token_embedding_type;
  14975. } else {
  14976. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  14977. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  14978. new_type = GGML_TYPE_Q2_K;
  14979. }
  14980. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  14981. new_type = GGML_TYPE_IQ3_S;
  14982. }
  14983. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  14984. new_type = GGML_TYPE_IQ3_S;
  14985. }
  14986. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  14987. new_type == GGML_TYPE_Q4_0_8_8) {
  14988. new_type = GGML_TYPE_Q4_0;
  14989. }
  14990. else if (ftype == LLAMA_FTYPE_MOSTLY_TQ1_0 || ftype == LLAMA_FTYPE_MOSTLY_TQ2_0) {
  14991. new_type = GGML_TYPE_Q4_K;
  14992. }
  14993. }
  14994. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  14995. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  14996. if (name.find("attn_v.weight") != std::string::npos) {
  14997. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  14998. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  14999. ++qs.i_attention_wv;
  15000. }
  15001. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  15002. new_type = GGML_TYPE_Q4_K;
  15003. }
  15004. else if (name.find("ffn_down") != std::string::npos) {
  15005. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  15006. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  15007. }
  15008. ++qs.i_ffn_down;
  15009. }
  15010. else if (name.find("attn_output.weight") != std::string::npos) {
  15011. if (qs.model.hparams.n_expert == 8) {
  15012. new_type = GGML_TYPE_Q5_K;
  15013. } else {
  15014. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  15015. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  15016. }
  15017. }
  15018. } else if (name.find("attn_v.weight") != std::string::npos) {
  15019. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  15020. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15021. }
  15022. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  15023. new_type = GGML_TYPE_Q4_K;
  15024. }
  15025. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15026. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  15027. }
  15028. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  15029. new_type = GGML_TYPE_Q4_K;
  15030. }
  15031. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15032. new_type = GGML_TYPE_Q4_K;
  15033. }
  15034. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15035. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15036. }
  15037. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  15038. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  15039. new_type = GGML_TYPE_Q5_K;
  15040. }
  15041. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  15042. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  15043. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  15044. if (qs.model.type == MODEL_70B) {
  15045. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  15046. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  15047. // nearly negligible increase in model size by quantizing this tensor with more bits:
  15048. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  15049. }
  15050. if (qs.model.hparams.n_expert == 8) {
  15051. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15052. // TODO: explore better strategies
  15053. new_type = GGML_TYPE_Q8_0;
  15054. }
  15055. ++qs.i_attention_wv;
  15056. } else if (name.find("attn_k.weight") != std::string::npos) {
  15057. if (qs.model.hparams.n_expert == 8) {
  15058. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  15059. // TODO: explore better strategies
  15060. new_type = GGML_TYPE_Q8_0;
  15061. }
  15062. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15063. new_type = GGML_TYPE_IQ3_XXS;
  15064. }
  15065. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15066. new_type = GGML_TYPE_IQ2_S;
  15067. }
  15068. } else if (name.find("attn_q.weight") != std::string::npos) {
  15069. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  15070. new_type = GGML_TYPE_IQ3_XXS;
  15071. }
  15072. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  15073. new_type = GGML_TYPE_IQ2_S;
  15074. }
  15075. } else if (name.find("ffn_down") != std::string::npos) {
  15076. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  15077. int i_layer = info.first, n_layer = info.second;
  15078. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15079. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  15080. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  15081. }
  15082. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  15083. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  15084. }
  15085. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  15086. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  15087. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  15088. : GGML_TYPE_Q3_K;
  15089. }
  15090. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  15091. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  15092. new_type = GGML_TYPE_Q4_K;
  15093. }
  15094. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  15095. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  15096. }
  15097. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  15098. if (arch == LLM_ARCH_FALCON) {
  15099. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  15100. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  15101. } else {
  15102. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15103. }
  15104. }
  15105. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  15106. new_type = GGML_TYPE_Q5_K;
  15107. }
  15108. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  15109. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  15110. new_type = GGML_TYPE_Q5_K;
  15111. }
  15112. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  15113. && qs.has_imatrix && i_layer < n_layer/8) {
  15114. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  15115. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  15116. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  15117. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  15118. }
  15119. ++qs.i_ffn_down;
  15120. } else if (name.find("attn_output.weight") != std::string::npos) {
  15121. if (arch != LLM_ARCH_FALCON) {
  15122. if (qs.model.hparams.n_expert == 8) {
  15123. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  15124. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  15125. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  15126. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  15127. new_type = GGML_TYPE_Q5_K;
  15128. }
  15129. } else {
  15130. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  15131. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  15132. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  15133. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  15134. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  15135. }
  15136. } else {
  15137. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  15138. }
  15139. }
  15140. else if (name.find("attn_qkv.weight") != std::string::npos) {
  15141. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  15142. new_type = GGML_TYPE_Q4_K;
  15143. }
  15144. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  15145. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  15146. }
  15147. else if (name.find("ffn_gate") != std::string::npos) {
  15148. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  15149. int i_layer = info.first, n_layer = info.second;
  15150. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15151. new_type = GGML_TYPE_IQ3_XXS;
  15152. }
  15153. ++qs.i_ffn_gate;
  15154. }
  15155. else if (name.find("ffn_up") != std::string::npos) {
  15156. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  15157. int i_layer = info.first, n_layer = info.second;
  15158. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  15159. new_type = GGML_TYPE_IQ3_XXS;
  15160. }
  15161. ++qs.i_ffn_up;
  15162. }
  15163. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15164. //}
  15165. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  15166. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  15167. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  15168. //}
  15169. // This can be used to reduce the size of the Q5_K_S model.
  15170. // The associated PPL increase is fully in line with the size reduction
  15171. //else {
  15172. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  15173. //}
  15174. bool convert_incompatible_tensor = false;
  15175. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  15176. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  15177. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  15178. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  15179. new_type == GGML_TYPE_IQ1_M) {
  15180. int nx = tensor->ne[0];
  15181. int ny = tensor->ne[1];
  15182. if (nx % QK_K != 0) {
  15183. 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));
  15184. convert_incompatible_tensor = true;
  15185. } else {
  15186. ++qs.n_k_quantized;
  15187. }
  15188. }
  15189. if (convert_incompatible_tensor) {
  15190. switch (new_type) {
  15191. case GGML_TYPE_TQ1_0:
  15192. case GGML_TYPE_TQ2_0: new_type = GGML_TYPE_Q4_0; break; // TODO: use a symmetric type instead
  15193. case GGML_TYPE_IQ2_XXS:
  15194. case GGML_TYPE_IQ2_XS:
  15195. case GGML_TYPE_IQ2_S:
  15196. case GGML_TYPE_IQ3_XXS:
  15197. case GGML_TYPE_IQ3_S:
  15198. case GGML_TYPE_IQ1_S:
  15199. case GGML_TYPE_IQ1_M:
  15200. case GGML_TYPE_Q2_K:
  15201. case GGML_TYPE_Q3_K:
  15202. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  15203. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  15204. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  15205. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  15206. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  15207. }
  15208. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  15209. new_type = GGML_TYPE_F16;
  15210. }
  15211. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  15212. ++qs.n_fallback;
  15213. }
  15214. return new_type;
  15215. }
  15216. 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) {
  15217. if (nthread < 2) {
  15218. // single-thread
  15219. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  15220. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  15221. throw std::runtime_error("quantized data validation failed");
  15222. }
  15223. return new_size;
  15224. }
  15225. std::mutex mutex;
  15226. int64_t counter = 0;
  15227. size_t new_size = 0;
  15228. bool valid = true;
  15229. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  15230. nrows, n_per_row, imatrix]() {
  15231. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  15232. size_t local_size = 0;
  15233. while (true) {
  15234. std::unique_lock<std::mutex> lock(mutex);
  15235. int64_t first_row = counter; counter += nrows_per_chunk;
  15236. if (first_row >= nrows) {
  15237. if (local_size > 0) {
  15238. new_size += local_size;
  15239. }
  15240. break;
  15241. }
  15242. lock.unlock();
  15243. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  15244. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  15245. local_size += this_size;
  15246. // validate the quantized data
  15247. const size_t row_size = ggml_row_size(new_type, n_per_row);
  15248. void * this_data = (char *) new_data + first_row * row_size;
  15249. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  15250. std::unique_lock<std::mutex> lock(mutex);
  15251. valid = false;
  15252. break;
  15253. }
  15254. }
  15255. };
  15256. for (int it = 0; it < nthread - 1; ++it) {
  15257. workers.emplace_back(compute);
  15258. }
  15259. compute();
  15260. for (auto & w : workers) { w.join(); }
  15261. workers.clear();
  15262. if (!valid) {
  15263. throw std::runtime_error("quantized data validation failed");
  15264. }
  15265. return new_size;
  15266. }
  15267. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  15268. ggml_type default_type;
  15269. llama_ftype ftype = params->ftype;
  15270. switch (params->ftype) {
  15271. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  15272. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  15273. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  15274. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  15275. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  15276. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  15277. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  15278. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  15279. // K-quants
  15280. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  15281. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  15282. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  15283. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  15284. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  15285. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  15286. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  15287. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  15288. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  15289. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  15290. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  15291. case LLAMA_FTYPE_MOSTLY_TQ1_0: default_type = GGML_TYPE_TQ1_0; break;
  15292. case LLAMA_FTYPE_MOSTLY_TQ2_0: default_type = GGML_TYPE_TQ2_0; break;
  15293. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  15294. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  15295. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  15296. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  15297. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  15298. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  15299. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  15300. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  15301. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  15302. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  15303. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  15304. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  15305. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  15306. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  15307. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  15308. }
  15309. int nthread = params->nthread;
  15310. if (nthread <= 0) {
  15311. nthread = std::thread::hardware_concurrency();
  15312. }
  15313. // mmap consistently increases speed Linux, and also increases speed on Windows with
  15314. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  15315. #if defined(__linux__) || defined(_WIN32)
  15316. constexpr bool use_mmap = true;
  15317. #else
  15318. constexpr bool use_mmap = false;
  15319. #endif
  15320. llama_model_kv_override * kv_overrides = nullptr;
  15321. if (params->kv_overrides) {
  15322. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  15323. kv_overrides = v->data();
  15324. }
  15325. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  15326. ml.init_mappings(false); // no prefetching
  15327. llama_model model;
  15328. llm_load_arch(ml, model);
  15329. llm_load_hparams(ml, model);
  15330. struct quantize_state_internal qs(model, params);
  15331. if (params->only_copy) {
  15332. ftype = model.ftype;
  15333. }
  15334. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  15335. if (params->imatrix) {
  15336. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  15337. if (imatrix_data) {
  15338. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  15339. qs.has_imatrix = true;
  15340. // check imatrix for nans or infs
  15341. for (const auto & kv : *imatrix_data) {
  15342. for (float f : kv.second) {
  15343. if (!std::isfinite(f)) {
  15344. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  15345. }
  15346. }
  15347. }
  15348. }
  15349. }
  15350. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  15351. struct gguf_context * ctx_out = gguf_init_empty();
  15352. // copy the KV pairs from the input file
  15353. gguf_set_kv (ctx_out, ml.meta);
  15354. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  15355. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  15356. // Remove split metadata
  15357. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  15358. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  15359. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  15360. if (params->kv_overrides) {
  15361. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  15362. for (auto & o : overrides) {
  15363. if (o.key[0] == 0) break;
  15364. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  15365. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  15366. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  15367. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  15368. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  15369. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  15370. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  15371. gguf_set_val_str(ctx_out, o.key, o.val_str);
  15372. } else {
  15373. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  15374. }
  15375. }
  15376. }
  15377. for (int i = 0; i < ml.n_tensors; ++i) {
  15378. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  15379. const std::string name = ggml_get_name(meta);
  15380. // TODO: avoid hardcoded tensor names - use the TN_* constants
  15381. if (name.find("attn_v.weight") != std::string::npos ||
  15382. name.find("attn_qkv.weight") != std::string::npos ||
  15383. name.find("attn_kv_b.weight")!= std::string::npos) {
  15384. ++qs.n_attention_wv;
  15385. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  15386. qs.has_output = true;
  15387. }
  15388. }
  15389. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  15390. // sanity checks
  15391. {
  15392. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  15393. // attention layers have a non-zero number of kv heads
  15394. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  15395. if (llama_model_has_encoder(&model)) {
  15396. n_attn_layer *= 3;
  15397. }
  15398. GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
  15399. }
  15400. size_t total_size_org = 0;
  15401. size_t total_size_new = 0;
  15402. std::vector<std::thread> workers;
  15403. workers.reserve(nthread);
  15404. int idx = 0;
  15405. std::vector<no_init<uint8_t>> read_data;
  15406. std::vector<no_init<uint8_t>> work;
  15407. std::vector<no_init<float>> f32_conv_buf;
  15408. uint16_t n_split = 1;
  15409. // Assume split index is continuous
  15410. if (params->keep_split) {
  15411. for (int i = 0; i < ml.n_tensors; ++i) {
  15412. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  15413. }
  15414. }
  15415. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  15416. ctx_outs[0] = ctx_out;
  15417. // populate the original tensors so we get an initial meta data
  15418. for (int i = 0; i < ml.n_tensors; ++i) {
  15419. auto weight = ml.get_weight(i);
  15420. uint16_t i_split = params->keep_split ? weight->idx : 0;
  15421. struct ggml_tensor * tensor = weight->tensor;
  15422. if (ctx_outs[i_split] == NULL) {
  15423. ctx_outs[i_split] = gguf_init_empty();
  15424. }
  15425. gguf_add_tensor(ctx_outs[i_split], tensor);
  15426. }
  15427. // Set split info if needed
  15428. if (n_split > 1) {
  15429. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  15430. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  15431. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  15432. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  15433. }
  15434. }
  15435. int cur_split = -1;
  15436. std::ofstream fout;
  15437. auto close_ofstream = [&]() {
  15438. // Write metadata and close file handler
  15439. if (fout.is_open()) {
  15440. fout.seekp(0);
  15441. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  15442. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  15443. fout.write((const char *) data.data(), data.size());
  15444. fout.close();
  15445. }
  15446. };
  15447. auto new_ofstream = [&](int index) {
  15448. cur_split = index;
  15449. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  15450. std::string fname = fname_out;
  15451. if (params->keep_split) {
  15452. char split_path[PATH_MAX] = {0};
  15453. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  15454. fname = std::string(split_path);
  15455. }
  15456. fout = std::ofstream(fname, std::ios::binary);
  15457. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  15458. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  15459. // placeholder for the meta data
  15460. ::zeros(fout, meta_size);
  15461. };
  15462. const auto tn = LLM_TN(model.arch);
  15463. new_ofstream(0);
  15464. for (int i = 0; i < ml.n_tensors; ++i) {
  15465. auto weight = ml.get_weight(i);
  15466. struct ggml_tensor * tensor = weight->tensor;
  15467. if (weight->idx != cur_split && params->keep_split) {
  15468. close_ofstream();
  15469. new_ofstream(weight->idx);
  15470. }
  15471. const std::string name = ggml_get_name(tensor);
  15472. if (!ml.use_mmap) {
  15473. if (read_data.size() < ggml_nbytes(tensor)) {
  15474. read_data.resize(ggml_nbytes(tensor));
  15475. }
  15476. tensor->data = read_data.data();
  15477. }
  15478. ml.load_data_for(tensor);
  15479. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  15480. ++idx, ml.n_tensors,
  15481. ggml_get_name(tensor),
  15482. llama_format_tensor_shape(tensor).c_str(),
  15483. ggml_type_name(tensor->type));
  15484. // This used to be a regex, but <regex> has an extreme cost to compile times.
  15485. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  15486. // quantize only 2D and 3D tensors (experts)
  15487. quantize &= (ggml_n_dims(tensor) >= 2);
  15488. // do not quantize norm tensors
  15489. quantize &= name.find("_norm.weight") == std::string::npos;
  15490. quantize &= params->quantize_output_tensor || name != "output.weight";
  15491. quantize &= !params->only_copy;
  15492. // do not quantize expert gating tensors
  15493. // NOTE: can't use LLM_TN here because the layer number is not known
  15494. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  15495. // do not quantize positional embeddings and token types (BERT)
  15496. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  15497. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  15498. // do not quantize Mamba's small yet 2D weights
  15499. // NOTE: can't use LLM_TN here because the layer number is not known
  15500. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  15501. // do not quantize RWKV's time_mix_first tensors
  15502. quantize &= name.find("time_mix_first.weight") == std::string::npos;
  15503. quantize &= name.find("time_mix_w1.weight") == std::string::npos;
  15504. quantize &= name.find("time_mix_w2.weight") == std::string::npos;
  15505. quantize &= name.find("time_mix_decay_w1.weight") == std::string::npos;
  15506. quantize &= name.find("time_mix_decay_w2.weight") == std::string::npos;
  15507. // do not quantize relative position bias (T5)
  15508. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  15509. enum ggml_type new_type;
  15510. void * new_data;
  15511. size_t new_size;
  15512. if (quantize) {
  15513. new_type = default_type;
  15514. // get more optimal quantization type based on the tensor shape, layer, etc.
  15515. if (!params->pure && ggml_is_quantized(default_type)) {
  15516. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  15517. }
  15518. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  15519. new_type = params->token_embedding_type;
  15520. }
  15521. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  15522. new_type = params->output_tensor_type;
  15523. }
  15524. // If we've decided to quantize to the same type the tensor is already
  15525. // in then there's nothing to do.
  15526. quantize = tensor->type != new_type;
  15527. }
  15528. if (!quantize) {
  15529. new_type = tensor->type;
  15530. new_data = tensor->data;
  15531. new_size = ggml_nbytes(tensor);
  15532. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  15533. } else {
  15534. const int64_t nelements = ggml_nelements(tensor);
  15535. const float * imatrix = nullptr;
  15536. if (imatrix_data) {
  15537. auto it = imatrix_data->find(tensor->name);
  15538. if (it == imatrix_data->end()) {
  15539. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  15540. } else {
  15541. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  15542. imatrix = it->second.data();
  15543. } else {
  15544. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  15545. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  15546. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  15547. // this is a significant error and it may be good idea to abort the process if this happens,
  15548. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  15549. // tok_embd should be ignored in this case, since it always causes this warning
  15550. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  15551. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  15552. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  15553. }
  15554. }
  15555. }
  15556. }
  15557. if ((new_type == GGML_TYPE_IQ2_XXS ||
  15558. new_type == GGML_TYPE_IQ2_XS ||
  15559. new_type == GGML_TYPE_IQ2_S ||
  15560. new_type == GGML_TYPE_IQ1_S ||
  15561. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  15562. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  15563. LLAMA_LOG_ERROR("\n\n============================================================\n");
  15564. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  15565. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  15566. LLAMA_LOG_ERROR("============================================================\n\n");
  15567. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  15568. }
  15569. float * f32_data;
  15570. if (tensor->type == GGML_TYPE_F32) {
  15571. f32_data = (float *) tensor->data;
  15572. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  15573. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  15574. } else {
  15575. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  15576. f32_data = (float *) f32_conv_buf.data();
  15577. }
  15578. int chunk_size_multiplier = 1;
  15579. 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) {
  15580. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  15581. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  15582. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  15583. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  15584. }
  15585. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  15586. fflush(stdout);
  15587. if (work.size() < (size_t)nelements * 4) {
  15588. work.resize(nelements * 4); // upper bound on size
  15589. }
  15590. new_data = work.data();
  15591. const int64_t n_per_row = tensor->ne[0];
  15592. const int64_t nrows = tensor->ne[1];
  15593. static const int64_t min_chunk_size = 32 * 512;
  15594. 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)) *
  15595. chunk_size_multiplier;
  15596. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  15597. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  15598. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  15599. // quantize each expert separately since they have different importance matrices
  15600. new_size = 0;
  15601. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  15602. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  15603. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  15604. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  15605. 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);
  15606. }
  15607. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  15608. }
  15609. total_size_org += ggml_nbytes(tensor);
  15610. total_size_new += new_size;
  15611. // update the gguf meta data as we go
  15612. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  15613. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  15614. // write tensor data + padding
  15615. fout.write((const char *) new_data, new_size);
  15616. zeros(fout, GGML_PAD(new_size, align) - new_size);
  15617. }
  15618. close_ofstream();
  15619. for (auto & c:ctx_outs) {
  15620. gguf_free(c);
  15621. }
  15622. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  15623. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  15624. if (qs.n_fallback > 0) {
  15625. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  15626. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  15627. }
  15628. }
  15629. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  15630. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  15631. ggml_context * ctx = nullptr;
  15632. struct gguf_init_params meta_gguf_params = {
  15633. /* .no_alloc = */ true,
  15634. /* .ctx = */ &ctx,
  15635. };
  15636. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  15637. if (!ctx_gguf) {
  15638. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  15639. }
  15640. // check metadata
  15641. {
  15642. auto get_kv_str = [&](const std::string & key) -> std::string {
  15643. int id = gguf_find_key(ctx_gguf, key.c_str());
  15644. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  15645. };
  15646. auto get_kv_f32 = [&](const std::string & key) -> float {
  15647. int id = gguf_find_key(ctx_gguf, key.c_str());
  15648. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  15649. };
  15650. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  15651. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  15652. if (general_type != "adapter") {
  15653. gguf_free(ctx_gguf);
  15654. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  15655. }
  15656. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  15657. auto general_arch = llm_arch_from_string(general_arch_str);
  15658. if (general_arch != model->arch) {
  15659. gguf_free(ctx_gguf);
  15660. throw std::runtime_error("model arch and LoRA arch mismatch");
  15661. }
  15662. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  15663. if (adapter_type != "lora") {
  15664. gguf_free(ctx_gguf);
  15665. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  15666. }
  15667. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  15668. }
  15669. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  15670. // contexts for each buffer type
  15671. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  15672. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  15673. auto it = ctx_map.find(buft);
  15674. if (it == ctx_map.end()) {
  15675. // add a new context
  15676. struct ggml_init_params params = {
  15677. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  15678. /*.mem_buffer =*/ NULL,
  15679. /*.no_alloc =*/ true,
  15680. };
  15681. ggml_context * buft_ctx = ggml_init(params);
  15682. ctx_map[buft] = buft_ctx;
  15683. return buft_ctx;
  15684. };
  15685. return it->second;
  15686. };
  15687. // bundle lora_a and lora_b into pairs
  15688. std::map<std::string, llama_lora_weight> ab_map;
  15689. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  15690. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  15691. };
  15692. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  15693. std::string name(cur->name);
  15694. if (str_endswith(name, ".lora_a")) {
  15695. replace_all(name, ".lora_a", "");
  15696. if (ab_map.find(name) == ab_map.end()) {
  15697. ab_map[name] = llama_lora_weight(cur, nullptr);
  15698. } else {
  15699. ab_map[name].a = cur;
  15700. }
  15701. } else if (str_endswith(name, ".lora_b")) {
  15702. replace_all(name, ".lora_b", "");
  15703. if (ab_map.find(name) == ab_map.end()) {
  15704. ab_map[name] = llama_lora_weight(nullptr, cur);
  15705. } else {
  15706. ab_map[name].b = cur;
  15707. }
  15708. } else {
  15709. gguf_free(ctx_gguf);
  15710. ggml_free(ctx);
  15711. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  15712. }
  15713. }
  15714. // add tensors
  15715. for (auto & it : ab_map) {
  15716. const std::string & name = it.first;
  15717. llama_lora_weight & w = it.second;
  15718. if (!w.a || !w.b) {
  15719. gguf_free(ctx_gguf);
  15720. ggml_free(ctx);
  15721. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  15722. }
  15723. // device buft and device ctx
  15724. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  15725. if (!model_tensor) {
  15726. gguf_free(ctx_gguf);
  15727. ggml_free(ctx);
  15728. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  15729. }
  15730. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  15731. // validate tensor shape
  15732. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  15733. gguf_free(ctx_gguf);
  15734. ggml_free(ctx);
  15735. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  15736. }
  15737. if (w.a->ne[1] != w.b->ne[0]) {
  15738. gguf_free(ctx_gguf);
  15739. ggml_free(ctx);
  15740. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  15741. }
  15742. // save tensor to adapter
  15743. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  15744. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  15745. ggml_set_name(tensor_a, w.a->name);
  15746. ggml_set_name(tensor_b, w.b->name);
  15747. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  15748. }
  15749. // allocate tensors / buffers and zero
  15750. {
  15751. adapter.ctxs.reserve(ctx_map.size());
  15752. adapter.bufs.reserve(ctx_map.size());
  15753. for (auto it : ctx_map) {
  15754. ggml_backend_buffer_type_t buft = it.first;
  15755. ggml_context * ctx_dev = it.second;
  15756. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  15757. if (!buf) {
  15758. gguf_free(ctx_gguf);
  15759. ggml_free(ctx);
  15760. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  15761. }
  15762. 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);
  15763. adapter.ctxs.push_back(ctx_dev);
  15764. adapter.bufs.push_back(buf);
  15765. }
  15766. }
  15767. // set tensor data
  15768. {
  15769. llama_file gguf_file(path_lora, "rb");
  15770. std::vector<uint8_t> read_buf;
  15771. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  15772. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  15773. size_t size = ggml_nbytes(orig);
  15774. read_buf.resize(size);
  15775. gguf_file.seek(offs, SEEK_SET);
  15776. gguf_file.read_raw(read_buf.data(), size);
  15777. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  15778. };
  15779. for (auto & it : adapter.ab_map) {
  15780. auto orig = ab_map[it.first];
  15781. auto dev = it.second;
  15782. set_tensor(orig.a, dev.a);
  15783. set_tensor(orig.b, dev.b);
  15784. }
  15785. }
  15786. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  15787. // free ctx for reading gguf
  15788. gguf_free(ctx_gguf);
  15789. ggml_free(ctx);
  15790. }
  15791. int32_t llama_lora_adapter_set(
  15792. struct llama_context * ctx,
  15793. struct llama_lora_adapter * adapter,
  15794. float scale) {
  15795. if (ctx->cparams.flash_attn) {
  15796. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  15797. return -1;
  15798. }
  15799. ctx->lora_adapters[adapter] = scale;
  15800. return 0;
  15801. }
  15802. int32_t llama_lora_adapter_remove(
  15803. struct llama_context * ctx,
  15804. struct llama_lora_adapter * adapter) {
  15805. auto pos = ctx->lora_adapters.find(adapter);
  15806. if (pos != ctx->lora_adapters.end()) {
  15807. ctx->lora_adapters.erase(pos);
  15808. return 0;
  15809. }
  15810. return -1;
  15811. }
  15812. void llama_lora_adapter_clear(struct llama_context * ctx) {
  15813. ctx->lora_adapters.clear();
  15814. }
  15815. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  15816. delete adapter;
  15817. }
  15818. //
  15819. // interface implementation
  15820. //
  15821. struct llama_model_params llama_model_default_params() {
  15822. struct llama_model_params result = {
  15823. /*.n_gpu_layers =*/ 0,
  15824. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  15825. /*.main_gpu =*/ 0,
  15826. /*.tensor_split =*/ nullptr,
  15827. /*.rpc_servers =*/ nullptr,
  15828. /*.progress_callback =*/ nullptr,
  15829. /*.progress_callback_user_data =*/ nullptr,
  15830. /*.kv_overrides =*/ nullptr,
  15831. /*.vocab_only =*/ false,
  15832. /*.use_mmap =*/ true,
  15833. /*.use_mlock =*/ false,
  15834. /*.check_tensors =*/ false,
  15835. };
  15836. #ifdef GGML_USE_METAL
  15837. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  15838. result.n_gpu_layers = 999;
  15839. #endif
  15840. return result;
  15841. }
  15842. struct llama_context_params llama_context_default_params() {
  15843. struct llama_context_params result = {
  15844. /*.n_ctx =*/ 512,
  15845. /*.n_batch =*/ 2048,
  15846. /*.n_ubatch =*/ 512,
  15847. /*.n_seq_max =*/ 1,
  15848. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  15849. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  15850. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  15851. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  15852. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  15853. /*.rope_freq_base =*/ 0.0f,
  15854. /*.rope_freq_scale =*/ 0.0f,
  15855. /*.yarn_ext_factor =*/ -1.0f,
  15856. /*.yarn_attn_factor =*/ 1.0f,
  15857. /*.yarn_beta_fast =*/ 32.0f,
  15858. /*.yarn_beta_slow =*/ 1.0f,
  15859. /*.yarn_orig_ctx =*/ 0,
  15860. /*.defrag_thold =*/ -1.0f,
  15861. /*.cb_eval =*/ nullptr,
  15862. /*.cb_eval_user_data =*/ nullptr,
  15863. /*.type_k =*/ GGML_TYPE_F16,
  15864. /*.type_v =*/ GGML_TYPE_F16,
  15865. /*.logits_all =*/ false,
  15866. /*.embeddings =*/ false,
  15867. /*.offload_kqv =*/ true,
  15868. /*.flash_attn =*/ false,
  15869. /*.no_perf =*/ true,
  15870. /*.abort_callback =*/ nullptr,
  15871. /*.abort_callback_data =*/ nullptr,
  15872. };
  15873. return result;
  15874. }
  15875. struct llama_sampler_chain_params llama_sampler_chain_default_params() {
  15876. struct llama_sampler_chain_params result = {
  15877. /*.no_perf =*/ true,
  15878. };
  15879. return result;
  15880. }
  15881. struct llama_model_quantize_params llama_model_quantize_default_params() {
  15882. struct llama_model_quantize_params result = {
  15883. /*.nthread =*/ 0,
  15884. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  15885. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  15886. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  15887. /*.allow_requantize =*/ false,
  15888. /*.quantize_output_tensor =*/ true,
  15889. /*.only_copy =*/ false,
  15890. /*.pure =*/ false,
  15891. /*.keep_split =*/ false,
  15892. /*.imatrix =*/ nullptr,
  15893. /*.kv_overrides =*/ nullptr,
  15894. };
  15895. return result;
  15896. }
  15897. size_t llama_max_devices(void) {
  15898. return 16;
  15899. }
  15900. bool llama_supports_mmap(void) {
  15901. return llama_mmap::SUPPORTED;
  15902. }
  15903. bool llama_supports_mlock(void) {
  15904. return llama_mlock::SUPPORTED;
  15905. }
  15906. bool llama_supports_gpu_offload(void) {
  15907. #if defined(GGML_USE_KOMPUTE)
  15908. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  15909. return true;
  15910. #else
  15911. return ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nullptr ||
  15912. ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU_FULL) != nullptr ||
  15913. llama_supports_rpc();
  15914. #endif
  15915. }
  15916. bool llama_supports_rpc(void) {
  15917. return ggml_backend_reg_by_name("RPC") != nullptr;
  15918. }
  15919. void llama_backend_init(void) {
  15920. ggml_time_init();
  15921. // needed to initialize f16 tables
  15922. {
  15923. struct ggml_init_params params = { 0, NULL, false };
  15924. struct ggml_context * ctx = ggml_init(params);
  15925. ggml_free(ctx);
  15926. }
  15927. }
  15928. void llama_numa_init(enum ggml_numa_strategy numa) {
  15929. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  15930. ggml_numa_init(numa);
  15931. }
  15932. }
  15933. void llama_attach_threadpool(
  15934. struct llama_context * ctx,
  15935. ggml_threadpool_t threadpool,
  15936. ggml_threadpool_t threadpool_batch) {
  15937. ctx->threadpool = threadpool;
  15938. ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
  15939. }
  15940. void llama_detach_threadpool(struct llama_context * ctx) {
  15941. ctx->threadpool = nullptr;
  15942. ctx->threadpool_batch = nullptr;
  15943. }
  15944. void llama_backend_free(void) {
  15945. ggml_quantize_free();
  15946. }
  15947. int64_t llama_time_us(void) {
  15948. return ggml_time_us();
  15949. }
  15950. struct llama_model * llama_load_model_from_file(
  15951. const char * path_model,
  15952. struct llama_model_params params) {
  15953. ggml_time_init();
  15954. llama_model * model = new llama_model;
  15955. unsigned cur_percentage = 0;
  15956. if (params.progress_callback == NULL) {
  15957. params.progress_callback_user_data = &cur_percentage;
  15958. params.progress_callback = [](float progress, void * ctx) {
  15959. unsigned * cur_percentage_p = (unsigned *) ctx;
  15960. unsigned percentage = (unsigned) (100 * progress);
  15961. while (percentage > *cur_percentage_p) {
  15962. *cur_percentage_p = percentage;
  15963. LLAMA_LOG_CONT(".");
  15964. if (percentage >= 100) {
  15965. LLAMA_LOG_CONT("\n");
  15966. }
  15967. }
  15968. return true;
  15969. };
  15970. }
  15971. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  15972. // split the servers set them into model->rpc_servers
  15973. std::string servers(params.rpc_servers);
  15974. size_t pos = 0;
  15975. while ((pos = servers.find(',')) != std::string::npos) {
  15976. std::string server = servers.substr(0, pos);
  15977. model->rpc_servers.push_back(server);
  15978. servers.erase(0, pos + 1);
  15979. }
  15980. model->rpc_servers.push_back(servers);
  15981. }
  15982. // add RPC devices
  15983. if (!model->rpc_servers.empty()) {
  15984. ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
  15985. if (!rpc_reg) {
  15986. LLAMA_LOG_ERROR("%s: failed to find RPC backend\n", __func__);
  15987. llama_free_model(model);
  15988. return nullptr;
  15989. }
  15990. // ggml_backend_dev_t ggml_backend_rpc_add_device(const char * endpoint);
  15991. using ggml_backend_rpc_add_device_t = ggml_backend_dev_t (*)(const char *);
  15992. ggml_backend_rpc_add_device_t ggml_backend_rpc_add_device_fn = (ggml_backend_rpc_add_device_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_device");
  15993. if (!ggml_backend_rpc_add_device_fn) {
  15994. LLAMA_LOG_ERROR("%s: failed to find RPC device add function\n", __func__);
  15995. llama_free_model(model);
  15996. return nullptr;
  15997. }
  15998. for (const std::string & server : model->rpc_servers) {
  15999. ggml_backend_dev_t dev = ggml_backend_rpc_add_device_fn(server.c_str());
  16000. if (dev) {
  16001. model->devices.push_back(dev);
  16002. } else {
  16003. LLAMA_LOG_ERROR("%s: failed to add RPC device for server '%s'\n", __func__, server.c_str());
  16004. llama_free_model(model);
  16005. return nullptr;
  16006. }
  16007. }
  16008. }
  16009. // create list of devices to use with this model
  16010. // currently, we use all available devices
  16011. // TODO: rework API to give user more control over device selection
  16012. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  16013. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  16014. switch (ggml_backend_dev_type(dev)) {
  16015. case GGML_BACKEND_DEVICE_TYPE_CPU:
  16016. case GGML_BACKEND_DEVICE_TYPE_CPU_FULL:
  16017. // skip CPU backends since they are `handled separately
  16018. break;
  16019. case GGML_BACKEND_DEVICE_TYPE_GPU:
  16020. case GGML_BACKEND_DEVICE_TYPE_GPU_FULL:
  16021. {
  16022. size_t free, total; // NOLINT
  16023. ggml_backend_dev_memory(dev, &free, &total);
  16024. LLAMA_LOG_INFO("%s: using device %s (%s) - %zu MiB free\n", __func__, ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), free/1024/1024);
  16025. model->devices.push_back(dev);
  16026. break;
  16027. }
  16028. }
  16029. }
  16030. int status = llama_model_load(path_model, *model, params);
  16031. GGML_ASSERT(status <= 0);
  16032. if (status < 0) {
  16033. if (status == -1) {
  16034. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  16035. } else if (status == -2) {
  16036. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  16037. }
  16038. llama_free_model(model);
  16039. return nullptr;
  16040. }
  16041. return model;
  16042. }
  16043. void llama_free_model(struct llama_model * model) {
  16044. delete model;
  16045. }
  16046. struct llama_context * llama_new_context_with_model(
  16047. struct llama_model * model,
  16048. struct llama_context_params params) {
  16049. if (!model) {
  16050. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  16051. return nullptr;
  16052. }
  16053. if (params.n_batch == 0 && params.n_ubatch == 0) {
  16054. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  16055. return nullptr;
  16056. }
  16057. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  16058. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  16059. return nullptr;
  16060. }
  16061. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  16062. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  16063. params.flash_attn = false;
  16064. }
  16065. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  16066. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  16067. params.flash_attn = false;
  16068. }
  16069. if (ggml_is_quantized(params.type_v) && !params.flash_attn) {
  16070. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  16071. return nullptr;
  16072. }
  16073. llama_context * ctx = new llama_context(*model);
  16074. const auto & hparams = model->hparams;
  16075. auto & cparams = ctx->cparams;
  16076. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  16077. cparams.n_threads = params.n_threads;
  16078. cparams.n_threads_batch = params.n_threads_batch;
  16079. cparams.yarn_ext_factor = params.yarn_ext_factor;
  16080. cparams.yarn_attn_factor = params.yarn_attn_factor;
  16081. cparams.yarn_beta_fast = params.yarn_beta_fast;
  16082. cparams.yarn_beta_slow = params.yarn_beta_slow;
  16083. cparams.defrag_thold = params.defrag_thold;
  16084. cparams.embeddings = params.embeddings;
  16085. cparams.offload_kqv = params.offload_kqv;
  16086. cparams.flash_attn = params.flash_attn;
  16087. cparams.no_perf = params.no_perf;
  16088. cparams.pooling_type = params.pooling_type;
  16089. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  16090. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  16091. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  16092. // this is necessary due to kv_self.n being padded later during inference
  16093. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  16094. // with causal attention, the batch size is limited by the context size
  16095. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  16096. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  16097. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  16098. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  16099. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  16100. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  16101. cparams.n_batch = GGML_KQ_MASK_PAD;
  16102. }
  16103. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  16104. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  16105. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  16106. hparams.n_ctx_train;
  16107. cparams.cb_eval = params.cb_eval;
  16108. cparams.cb_eval_user_data = params.cb_eval_user_data;
  16109. auto rope_scaling_type = params.rope_scaling_type;
  16110. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  16111. rope_scaling_type = hparams.rope_scaling_type_train;
  16112. }
  16113. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  16114. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  16115. }
  16116. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  16117. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  16118. }
  16119. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  16120. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16121. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  16122. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  16123. } else {
  16124. cparams.pooling_type = hparams.pooling_type;
  16125. }
  16126. }
  16127. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  16128. cparams.causal_attn = hparams.causal_attn;
  16129. } else {
  16130. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  16131. }
  16132. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  16133. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  16134. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  16135. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  16136. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  16137. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  16138. ctx->abort_callback = params.abort_callback;
  16139. ctx->abort_callback_data = params.abort_callback_data;
  16140. ctx->logits_all = params.logits_all;
  16141. // build worst-case graph for encoder if a model contains encoder
  16142. ctx->is_encoding = llama_model_has_encoder(model);
  16143. uint32_t kv_size = cparams.n_ctx;
  16144. ggml_type type_k = params.type_k;
  16145. ggml_type type_v = params.type_v;
  16146. // Mamba only needs a constant number of KV cache cells per sequence
  16147. if (llama_model_is_recurrent(model)) {
  16148. // Mamba needs at least as many KV cells as there are sequences kept at any time
  16149. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  16150. // it's probably best to keep as much precision as possible for the states
  16151. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  16152. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  16153. }
  16154. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  16155. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  16156. if (!hparams.vocab_only) {
  16157. // initialize backends
  16158. int main_gpu = model->main_gpu;
  16159. // with registry
  16160. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16161. if (main_gpu >= 0 && main_gpu < (int)model->devices.size()) {
  16162. ggml_backend_dev_t main_dev = model->devices[main_gpu];
  16163. ggml_backend_t backend = ggml_backend_dev_init(main_dev, nullptr);
  16164. if (backend == nullptr) {
  16165. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(main_dev));
  16166. llama_free(ctx);
  16167. return nullptr;
  16168. }
  16169. ctx->backends.push_back(backend);
  16170. }
  16171. } else {
  16172. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16173. for (auto * dev : model->devices) {
  16174. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  16175. if (backend == nullptr) {
  16176. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  16177. llama_free(ctx);
  16178. return nullptr;
  16179. }
  16180. ctx->backends.push_back(backend);
  16181. }
  16182. }
  16183. if (main_gpu >= (int)model->devices.size()) {
  16184. main_gpu -= (int)model->devices.size();
  16185. }
  16186. #if defined(GGML_USE_KOMPUTE)
  16187. if (model->n_gpu_layers > 0) {
  16188. auto * backend = ggml_backend_kompute_init(main_gpu);
  16189. if (backend == nullptr) {
  16190. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  16191. llama_free(ctx);
  16192. return nullptr;
  16193. }
  16194. ctx->backends.push_back(backend);
  16195. }
  16196. #elif defined(GGML_USE_CANN)
  16197. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  16198. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  16199. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  16200. ggml_backend_t backend = ggml_backend_cann_init(main_gpu);
  16201. if (backend == nullptr) {
  16202. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, main_gpu);
  16203. llama_free(ctx);
  16204. return nullptr;
  16205. }
  16206. ctx->backends.push_back(backend);
  16207. } else {
  16208. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  16209. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  16210. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  16211. ggml_backend_t backend = ggml_backend_cann_init(device);
  16212. if (backend == nullptr) {
  16213. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  16214. llama_free(ctx);
  16215. return nullptr;
  16216. }
  16217. ctx->backends.push_back(backend);
  16218. }
  16219. }
  16220. #endif
  16221. // add other backends (such as BLAS)
  16222. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  16223. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  16224. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
  16225. ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
  16226. if (backend == nullptr) {
  16227. LLAMA_LOG_ERROR("%s: failed to initialize %s backend\n", __func__, ggml_backend_dev_name(dev));
  16228. llama_free(ctx);
  16229. return nullptr;
  16230. }
  16231. ctx->backends.push_back(backend);
  16232. }
  16233. }
  16234. ctx->backend_cpu = ggml_backend_cpu_init();
  16235. if (ctx->backend_cpu == nullptr) {
  16236. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  16237. llama_free(ctx);
  16238. return nullptr;
  16239. }
  16240. ctx->backends.push_back(ctx->backend_cpu);
  16241. // create a list of the set_n_threads functions in the backends
  16242. for (auto * backend : ctx->backends) {
  16243. ggml_backend_dev_t dev = ggml_backend_get_device(backend);
  16244. ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
  16245. if (reg) {
  16246. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  16247. if (ggml_backend_set_n_threads_fn) {
  16248. ctx->set_n_threads_fns.emplace_back(backend, ggml_backend_set_n_threads_fn);
  16249. }
  16250. }
  16251. }
  16252. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  16253. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  16254. llama_free(ctx);
  16255. return nullptr;
  16256. }
  16257. {
  16258. size_t memory_size_k = 0;
  16259. size_t memory_size_v = 0;
  16260. for (auto & k : ctx->kv_self.k_l) {
  16261. memory_size_k += ggml_nbytes(k);
  16262. }
  16263. for (auto & v : ctx->kv_self.v_l) {
  16264. memory_size_v += ggml_nbytes(v);
  16265. }
  16266. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  16267. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  16268. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  16269. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  16270. }
  16271. // graph outputs buffer
  16272. {
  16273. // resized during inference when a batch uses more outputs
  16274. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  16275. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  16276. llama_free(ctx);
  16277. return nullptr;
  16278. }
  16279. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  16280. ggml_backend_buffer_name(ctx->buf_output),
  16281. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  16282. }
  16283. // scheduler and compute buffers
  16284. {
  16285. // buffer types used for the compute buffer of each backend
  16286. std::vector<ggml_backend_buffer_type_t> backend_buft;
  16287. for (auto * backend : ctx->backends) {
  16288. if (ggml_backend_is_cpu(backend)) {
  16289. // use host buffers for the CPU backend compute buffer
  16290. backend_buft.push_back(llama_default_buffer_type_cpu(*model, true));
  16291. } else {
  16292. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  16293. }
  16294. }
  16295. const size_t max_nodes = llama_model_max_nodes(*model);
  16296. // buffer used to store the computation graph and the tensor meta data
  16297. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  16298. // TODO: move these checks to ggml_backend_sched
  16299. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  16300. bool pipeline_parallel =
  16301. llama_get_device_count(*model) > 1 &&
  16302. model->n_gpu_layers > (int)model->hparams.n_layer &&
  16303. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  16304. params.offload_kqv;
  16305. // pipeline parallelism requires support for async compute and events in all devices
  16306. if (pipeline_parallel) {
  16307. for (auto * backend : ctx->backends) {
  16308. if (ggml_backend_is_cpu(backend)) {
  16309. // ignore CPU backend
  16310. continue;
  16311. }
  16312. auto * dev = ggml_backend_get_device(backend);
  16313. if (!dev) {
  16314. // backend is using old interface, not supported
  16315. pipeline_parallel = false;
  16316. break;
  16317. }
  16318. ggml_backend_dev_props props;
  16319. ggml_backend_dev_get_props(dev, &props);
  16320. if (!props.caps.async || !props.caps.events) {
  16321. // device does not support async compute or events
  16322. pipeline_parallel = false;
  16323. break;
  16324. }
  16325. }
  16326. }
  16327. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  16328. if (pipeline_parallel) {
  16329. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  16330. }
  16331. // build worst-case graph
  16332. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  16333. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  16334. 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
  16335. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  16336. ggml_cgraph * gf = llama_build_graph(*ctx, ubatch, true);
  16337. // initialize scheduler with the worst-case graph
  16338. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  16339. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  16340. llama_free(ctx);
  16341. return nullptr;
  16342. }
  16343. for (size_t i = 0; i < ctx->backends.size(); i++) {
  16344. ggml_backend_t backend = ctx->backends[i];
  16345. ggml_backend_buffer_type_t buft = backend_buft[i];
  16346. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  16347. if (size > 1) {
  16348. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  16349. ggml_backend_buft_name(buft),
  16350. size / 1024.0 / 1024.0);
  16351. }
  16352. }
  16353. // note: the number of splits during measure is higher than during inference due to the kv shift
  16354. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  16355. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, ggml_graph_n_nodes(gf));
  16356. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  16357. }
  16358. }
  16359. return ctx;
  16360. }
  16361. void llama_free(struct llama_context * ctx) {
  16362. delete ctx;
  16363. }
  16364. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  16365. return ctx->cparams.n_ctx;
  16366. }
  16367. uint32_t llama_n_batch(const struct llama_context * ctx) {
  16368. return ctx->cparams.n_batch;
  16369. }
  16370. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  16371. return ctx->cparams.n_ubatch;
  16372. }
  16373. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  16374. return ctx->kv_self.size;
  16375. }
  16376. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  16377. return model->vocab.type;
  16378. }
  16379. int32_t llama_n_vocab(const struct llama_model * model) {
  16380. return model->hparams.n_vocab;
  16381. }
  16382. int32_t llama_n_ctx_train(const struct llama_model * model) {
  16383. return model->hparams.n_ctx_train;
  16384. }
  16385. int32_t llama_n_embd(const struct llama_model * model) {
  16386. return model->hparams.n_embd;
  16387. }
  16388. int32_t llama_n_layer(const struct llama_model * model) {
  16389. return model->hparams.n_layer;
  16390. }
  16391. int32_t llama_n_head(const struct llama_model * model) {
  16392. return model->hparams.n_head();
  16393. }
  16394. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  16395. return &ctx->model;
  16396. }
  16397. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  16398. return ctx->cparams.pooling_type;
  16399. }
  16400. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  16401. switch (model->arch) {
  16402. // these models do not use RoPE
  16403. case LLM_ARCH_GPT2:
  16404. case LLM_ARCH_GPTJ:
  16405. case LLM_ARCH_MPT:
  16406. case LLM_ARCH_REFACT:
  16407. case LLM_ARCH_BLOOM:
  16408. case LLM_ARCH_MAMBA:
  16409. case LLM_ARCH_JINA_BERT_V2:
  16410. case LLM_ARCH_T5:
  16411. case LLM_ARCH_T5ENCODER:
  16412. case LLM_ARCH_JAIS:
  16413. case LLM_ARCH_RWKV6:
  16414. return LLAMA_ROPE_TYPE_NONE;
  16415. // use what we call a normal RoPE, operating on pairs of consecutive head values
  16416. case LLM_ARCH_LLAMA:
  16417. case LLM_ARCH_BAICHUAN:
  16418. case LLM_ARCH_STARCODER:
  16419. case LLM_ARCH_PLAMO:
  16420. case LLM_ARCH_ORION:
  16421. case LLM_ARCH_INTERNLM2:
  16422. case LLM_ARCH_MINICPM:
  16423. case LLM_ARCH_XVERSE:
  16424. case LLM_ARCH_COMMAND_R:
  16425. case LLM_ARCH_OLMO:
  16426. case LLM_ARCH_ARCTIC:
  16427. case LLM_ARCH_DEEPSEEK2:
  16428. case LLM_ARCH_CHATGLM:
  16429. case LLM_ARCH_GRANITE:
  16430. case LLM_ARCH_GRANITE_MOE:
  16431. case LLM_ARCH_CHAMELEON:
  16432. return LLAMA_ROPE_TYPE_NORM;
  16433. // the pairs of head values are offset by n_rot/2
  16434. case LLM_ARCH_FALCON:
  16435. case LLM_ARCH_GROK:
  16436. case LLM_ARCH_DBRX:
  16437. case LLM_ARCH_BERT:
  16438. case LLM_ARCH_NOMIC_BERT:
  16439. case LLM_ARCH_STABLELM:
  16440. case LLM_ARCH_BITNET:
  16441. case LLM_ARCH_QWEN:
  16442. case LLM_ARCH_QWEN2:
  16443. case LLM_ARCH_QWEN2MOE:
  16444. case LLM_ARCH_OLMOE:
  16445. case LLM_ARCH_PHI2:
  16446. case LLM_ARCH_PHI3:
  16447. case LLM_ARCH_GEMMA:
  16448. case LLM_ARCH_GEMMA2:
  16449. case LLM_ARCH_STARCODER2:
  16450. case LLM_ARCH_OPENELM:
  16451. case LLM_ARCH_GPTNEOX:
  16452. case LLM_ARCH_CODESHELL:
  16453. case LLM_ARCH_NEMOTRON:
  16454. case LLM_ARCH_EXAONE:
  16455. case LLM_ARCH_MINICPM3:
  16456. return LLAMA_ROPE_TYPE_NEOX;
  16457. // all model arches should be listed explicitly here
  16458. case LLM_ARCH_UNKNOWN:
  16459. GGML_ABORT("unknown architecture");
  16460. }
  16461. return LLAMA_ROPE_TYPE_NONE;
  16462. }
  16463. float llama_rope_freq_scale_train(const struct llama_model * model) {
  16464. return model->hparams.rope_freq_scale_train;
  16465. }
  16466. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  16467. const auto & it = model->gguf_kv.find(key);
  16468. if (it == model->gguf_kv.end()) {
  16469. if (buf_size > 0) {
  16470. buf[0] = '\0';
  16471. }
  16472. return -1;
  16473. }
  16474. return snprintf(buf, buf_size, "%s", it->second.c_str());
  16475. }
  16476. int32_t llama_model_meta_count(const struct llama_model * model) {
  16477. return (int)model->gguf_kv.size();
  16478. }
  16479. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  16480. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  16481. if (buf_size > 0) {
  16482. buf[0] = '\0';
  16483. }
  16484. return -1;
  16485. }
  16486. auto it = model->gguf_kv.begin();
  16487. std::advance(it, i);
  16488. return snprintf(buf, buf_size, "%s", it->first.c_str());
  16489. }
  16490. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  16491. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  16492. if (buf_size > 0) {
  16493. buf[0] = '\0';
  16494. }
  16495. return -1;
  16496. }
  16497. auto it = model->gguf_kv.begin();
  16498. std::advance(it, i);
  16499. return snprintf(buf, buf_size, "%s", it->second.c_str());
  16500. }
  16501. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  16502. return snprintf(buf, buf_size, "%s %s %s",
  16503. llama_model_arch_name(model->arch),
  16504. llama_model_type_name(model->type),
  16505. llama_model_ftype_name(model->ftype).c_str());
  16506. }
  16507. uint64_t llama_model_size(const struct llama_model * model) {
  16508. uint64_t size = 0;
  16509. for (const auto & it : model->tensors_by_name) {
  16510. size += ggml_nbytes(it.second);
  16511. }
  16512. return size;
  16513. }
  16514. uint64_t llama_model_n_params(const struct llama_model * model) {
  16515. uint64_t nparams = 0;
  16516. for (const auto & it : model->tensors_by_name) {
  16517. nparams += ggml_nelements(it.second);
  16518. }
  16519. return nparams;
  16520. }
  16521. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  16522. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  16523. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  16524. return it.first == name;
  16525. });
  16526. if (it == model->tensors_by_name.end()) {
  16527. return nullptr;
  16528. }
  16529. return it->second;
  16530. }
  16531. bool llama_model_has_encoder(const struct llama_model * model) {
  16532. switch (model->arch) {
  16533. case LLM_ARCH_T5: return true;
  16534. case LLM_ARCH_T5ENCODER: return true;
  16535. default: return false;
  16536. }
  16537. }
  16538. bool llama_model_has_decoder(const struct llama_model * model) {
  16539. switch (model->arch) {
  16540. case LLM_ARCH_T5ENCODER: return false;
  16541. default: return true;
  16542. }
  16543. }
  16544. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  16545. return model->hparams.dec_start_token_id;
  16546. }
  16547. bool llama_model_is_recurrent(const struct llama_model * model) {
  16548. switch (model->arch) {
  16549. case LLM_ARCH_MAMBA: return true;
  16550. case LLM_ARCH_RWKV6: return true;
  16551. default: return false;
  16552. }
  16553. }
  16554. uint32_t llama_model_quantize(
  16555. const char * fname_inp,
  16556. const char * fname_out,
  16557. const llama_model_quantize_params * params) {
  16558. try {
  16559. llama_model_quantize_internal(fname_inp, fname_out, params);
  16560. return 0;
  16561. } catch (const std::exception & err) {
  16562. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  16563. return 1;
  16564. }
  16565. }
  16566. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  16567. try {
  16568. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  16569. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  16570. return adapter;
  16571. } catch (const std::exception & err) {
  16572. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  16573. return nullptr;
  16574. }
  16575. }
  16576. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  16577. GGML_ASSERT(cvec.tensors.empty());
  16578. GGML_ASSERT(cvec.ctxs.empty());
  16579. GGML_ASSERT(cvec.bufs.empty());
  16580. // count layer buffer types
  16581. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  16582. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  16583. buft_layer_count[model.buft_layer[i].buft]++;
  16584. }
  16585. // allocate contexts
  16586. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  16587. for (auto & it : buft_layer_count) {
  16588. int n_layers = it.second;
  16589. struct ggml_init_params params = {
  16590. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  16591. /*.mem_buffer =*/ NULL,
  16592. /*.no_alloc =*/ true,
  16593. };
  16594. ggml_context * ctx = ggml_init(params);
  16595. if (!ctx) {
  16596. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  16597. return 1;
  16598. }
  16599. ctx_map[it.first] = ctx;
  16600. }
  16601. // make tensors
  16602. cvec.tensors.reserve(model.hparams.n_layer);
  16603. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  16604. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  16605. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  16606. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  16607. cvec.tensors.push_back(tensor);
  16608. }
  16609. // allocate tensors / buffers and zero
  16610. cvec.ctxs.reserve(ctx_map.size());
  16611. cvec.bufs.reserve(ctx_map.size());
  16612. for (auto it : ctx_map) {
  16613. ggml_backend_buffer_type_t buft = it.first;
  16614. ggml_context * ctx = it.second;
  16615. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  16616. if (!buf) {
  16617. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  16618. return false;
  16619. }
  16620. ggml_backend_buffer_clear(buf, 0);
  16621. cvec.ctxs.push_back(ctx);
  16622. cvec.bufs.push_back(buf);
  16623. }
  16624. return true;
  16625. }
  16626. 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) {
  16627. const llama_model & model = lctx->model;
  16628. llama_control_vector & cvec = lctx->cvec;
  16629. if (data == nullptr) {
  16630. // disable the current control vector (but leave allocated for later)
  16631. cvec.layer_start = -1;
  16632. cvec.layer_end = -1;
  16633. return 0;
  16634. }
  16635. if (n_embd != (int) model.hparams.n_embd) {
  16636. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  16637. return 1;
  16638. }
  16639. if (cvec.tensors.empty()) {
  16640. if (!llama_control_vector_init(cvec, model)) {
  16641. return 1;
  16642. }
  16643. }
  16644. cvec.layer_start = il_start;
  16645. cvec.layer_end = il_end;
  16646. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  16647. assert(cvec.tensors[il] != nullptr);
  16648. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  16649. if (off + n_embd <= len) {
  16650. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  16651. }
  16652. }
  16653. return 0;
  16654. }
  16655. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  16656. struct llama_kv_cache_view result = {
  16657. /*.n_cells = */ 0,
  16658. /*.n_seq_max = */ n_seq_max,
  16659. /*.token_count = */ 0,
  16660. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  16661. /*.max_contiguous = */ 0,
  16662. /*.max_contiguous_idx = */ -1,
  16663. /*.cells = */ nullptr,
  16664. /*.cells_sequences = */ nullptr,
  16665. };
  16666. return result;
  16667. }
  16668. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  16669. if (view->cells != nullptr) {
  16670. free(view->cells);
  16671. view->cells = nullptr;
  16672. }
  16673. if (view->cells_sequences != nullptr) {
  16674. free(view->cells_sequences);
  16675. view->cells_sequences = nullptr;
  16676. }
  16677. }
  16678. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  16679. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  16680. view->n_cells = int32_t(ctx->kv_self.size);
  16681. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  16682. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  16683. view->cells = (struct llama_kv_cache_view_cell *)p;
  16684. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  16685. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  16686. view->cells_sequences = (llama_seq_id *)p;
  16687. }
  16688. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  16689. llama_kv_cache_view_cell * c_curr = view->cells;
  16690. llama_seq_id * cs_curr = view->cells_sequences;
  16691. int32_t used_cells = 0;
  16692. int32_t token_count = 0;
  16693. int32_t curr_contig_idx = -1;
  16694. uint32_t max_contig = 0;
  16695. int32_t max_contig_idx = -1;
  16696. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  16697. const size_t curr_size = kv_cells[i].seq_id.size();
  16698. token_count += curr_size;
  16699. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  16700. if (curr_size > 0) {
  16701. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  16702. max_contig = i - curr_contig_idx;
  16703. max_contig_idx = curr_contig_idx;
  16704. }
  16705. curr_contig_idx = -1;
  16706. } else if (curr_contig_idx < 0) {
  16707. curr_contig_idx = i;
  16708. }
  16709. int seq_idx = 0;
  16710. for (const llama_seq_id it : kv_cells[i].seq_id) {
  16711. if (seq_idx >= view->n_seq_max) {
  16712. break;
  16713. }
  16714. cs_curr[seq_idx] = it;
  16715. seq_idx++;
  16716. }
  16717. if (seq_idx != 0) {
  16718. used_cells++;
  16719. }
  16720. for (; seq_idx < view->n_seq_max; seq_idx++) {
  16721. cs_curr[seq_idx] = -1;
  16722. }
  16723. }
  16724. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  16725. max_contig_idx = curr_contig_idx;
  16726. max_contig = kv_cells.size() - curr_contig_idx;
  16727. }
  16728. view->max_contiguous = max_contig;
  16729. view->max_contiguous_idx = max_contig_idx;
  16730. view->token_count = token_count;
  16731. view->used_cells = used_cells;
  16732. if (uint32_t(used_cells) != ctx->kv_self.used) {
  16733. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  16734. __func__, ctx->kv_self.used, used_cells);
  16735. }
  16736. }
  16737. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  16738. int result = 0;
  16739. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  16740. result += ctx->kv_self.cells[i].seq_id.size();
  16741. }
  16742. return result;
  16743. }
  16744. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  16745. return ctx->kv_self.used;
  16746. }
  16747. void llama_kv_cache_clear(struct llama_context * ctx) {
  16748. llama_kv_cache_clear(ctx->kv_self);
  16749. }
  16750. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  16751. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  16752. }
  16753. 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) {
  16754. if (seq_id_src == seq_id_dst) {
  16755. return;
  16756. }
  16757. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  16758. }
  16759. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  16760. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  16761. }
  16762. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  16763. if (delta == 0) {
  16764. return;
  16765. }
  16766. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  16767. }
  16768. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  16769. if (d == 1) {
  16770. return;
  16771. }
  16772. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  16773. }
  16774. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  16775. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  16776. }
  16777. void llama_kv_cache_defrag(struct llama_context * ctx) {
  16778. llama_kv_cache_defrag(ctx->kv_self);
  16779. }
  16780. void llama_kv_cache_update(struct llama_context * ctx) {
  16781. llama_kv_cache_update_internal(*ctx);
  16782. }
  16783. // deprecated
  16784. size_t llama_get_state_size(struct llama_context * ctx) {
  16785. return llama_state_get_size(ctx);
  16786. }
  16787. // deprecated
  16788. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  16789. return llama_state_get_data(ctx, dst, -1);
  16790. }
  16791. // deprecated
  16792. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  16793. return llama_state_set_data(ctx, src, -1);
  16794. }
  16795. // deprecated
  16796. 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) {
  16797. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  16798. }
  16799. // deprecated
  16800. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  16801. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  16802. }
  16803. // TODO: replace all non-fatal assertions with returned errors or exceptions
  16804. struct llama_data_write {
  16805. virtual void write(const void * src, size_t size) = 0;
  16806. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  16807. virtual size_t get_size_written() = 0;
  16808. virtual ~llama_data_write() = default;
  16809. void write_string(const std::string & str) {
  16810. uint32_t str_size = str.size();
  16811. write(&str_size, sizeof(str_size));
  16812. write(str.data(), str_size);
  16813. }
  16814. void write_model_info(const struct llama_context * ctx) {
  16815. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  16816. write_string(arch_str);
  16817. // TODO: add more model-specific info which should prevent loading the session file if not identical
  16818. }
  16819. //void write_rng(const std::mt19937 & rng) {
  16820. // std::ostringstream rng_ss;
  16821. // rng_ss << rng;
  16822. // const std::string & rng_str = rng_ss.str();
  16823. // write_string(rng_str);
  16824. //}
  16825. void write_output_ids(struct llama_context * ctx) {
  16826. llama_output_reorder(ctx);
  16827. const uint32_t n_outputs = ctx->n_outputs;
  16828. std::vector<int32_t> output_pos;
  16829. const size_t n_batch = ctx->cparams.n_batch;
  16830. const auto & output_ids = ctx->output_ids;
  16831. GGML_ASSERT(n_outputs <= ctx->output_size);
  16832. output_pos.resize(n_outputs);
  16833. // build a more compact representation of the output ids
  16834. for (size_t i = 0; i < n_batch; ++i) {
  16835. // map an output id to a position in the batch
  16836. int32_t pos = output_ids[i];
  16837. if (pos >= 0) {
  16838. GGML_ASSERT((uint32_t) pos < n_outputs);
  16839. output_pos[pos] = i;
  16840. }
  16841. }
  16842. write(&n_outputs, sizeof(n_outputs));
  16843. if (n_outputs) {
  16844. write(output_pos.data(), n_outputs * sizeof(int32_t));
  16845. }
  16846. }
  16847. void write_logits(const struct llama_context * ctx) {
  16848. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  16849. write(&logits_size, sizeof(logits_size));
  16850. if (logits_size) {
  16851. write(ctx->logits, logits_size * sizeof(float));
  16852. }
  16853. }
  16854. void write_embeddings(const struct llama_context * ctx) {
  16855. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  16856. write(&embeddings_size, sizeof(embeddings_size));
  16857. if (embeddings_size) {
  16858. write(ctx->embd, embeddings_size * sizeof(float));
  16859. }
  16860. }
  16861. 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) {
  16862. for (const auto & range : cell_ranges) {
  16863. for (uint32_t i = range.first; i < range.second; ++i) {
  16864. const auto & cell = kv_self.cells[i];
  16865. const llama_pos pos = cell.pos;
  16866. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  16867. write(&pos, sizeof(pos));
  16868. write(&n_seq_id, sizeof(n_seq_id));
  16869. if (n_seq_id) {
  16870. for (auto seq_id : cell.seq_id) {
  16871. write(&seq_id, sizeof(seq_id));
  16872. }
  16873. }
  16874. }
  16875. }
  16876. }
  16877. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  16878. const struct llama_kv_cache & kv_self = ctx->kv_self;
  16879. const struct llama_hparams & hparams = ctx->model.hparams;
  16880. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  16881. const uint32_t n_layer = hparams.n_layer;
  16882. write(&v_trans, sizeof(v_trans));
  16883. write(&n_layer, sizeof(n_layer));
  16884. std::vector<uint8_t> tmp_buf;
  16885. // Iterate and write all the keys first, each row is a cell
  16886. // Get whole range at a time
  16887. for (uint32_t il = 0; il < n_layer; ++il) {
  16888. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  16889. // Write key type
  16890. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  16891. write(&k_type_i, sizeof(k_type_i));
  16892. // Write row size of key
  16893. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  16894. write(&k_size_row, sizeof(k_size_row));
  16895. // Read each range of cells of k_size length each into tmp_buf and write out
  16896. for (const auto & range : cell_ranges) {
  16897. const size_t range_size = range.second - range.first;
  16898. const size_t buf_size = range_size * k_size_row;
  16899. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  16900. }
  16901. }
  16902. if (!kv_self.v_trans) {
  16903. for (uint32_t il = 0; il < n_layer; ++il) {
  16904. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  16905. // Write value type
  16906. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  16907. write(&v_type_i, sizeof(v_type_i));
  16908. // Write row size of value
  16909. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  16910. write(&v_size_row, sizeof(v_size_row));
  16911. // Read each range of cells of v_size length each into tmp_buf and write out
  16912. for (const auto & range : cell_ranges) {
  16913. const size_t range_size = range.second - range.first;
  16914. const size_t buf_size = range_size * v_size_row;
  16915. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  16916. }
  16917. }
  16918. } else {
  16919. // When v is transposed, we also need the element size and get the element ranges from each row
  16920. const uint32_t kv_size = kv_self.size;
  16921. for (uint32_t il = 0; il < n_layer; ++il) {
  16922. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  16923. // Write value type
  16924. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  16925. write(&v_type_i, sizeof(v_type_i));
  16926. // Write element size
  16927. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  16928. write(&v_size_el, sizeof(v_size_el));
  16929. // Write GQA embedding size
  16930. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  16931. // For each row, we get the element values of each cell
  16932. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  16933. // Read each range of cells of v_size_el length each into tmp_buf and write out
  16934. for (const auto & range : cell_ranges) {
  16935. const size_t range_size = range.second - range.first;
  16936. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  16937. const size_t buf_size = range_size * v_size_el;
  16938. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  16939. }
  16940. }
  16941. }
  16942. }
  16943. }
  16944. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  16945. const struct llama_kv_cache & kv_self = ctx->kv_self;
  16946. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  16947. uint32_t cell_count = 0;
  16948. // Count the number of cells with the specified seq_id
  16949. // Find all the ranges of cells with this seq id (or all, when -1)
  16950. uint32_t cell_range_begin = kv_self.size;
  16951. for (uint32_t i = 0; i < kv_self.size; ++i) {
  16952. const auto & cell = kv_self.cells[i];
  16953. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  16954. ++cell_count;
  16955. if (cell_range_begin == kv_self.size) {
  16956. cell_range_begin = i;
  16957. }
  16958. } else {
  16959. if (cell_range_begin != kv_self.size) {
  16960. cell_ranges.emplace_back(cell_range_begin, i);
  16961. cell_range_begin = kv_self.size;
  16962. }
  16963. }
  16964. }
  16965. if (cell_range_begin != kv_self.size) {
  16966. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  16967. }
  16968. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  16969. uint32_t cell_count_check = 0;
  16970. for (const auto & range : cell_ranges) {
  16971. cell_count_check += range.second - range.first;
  16972. }
  16973. GGML_ASSERT(cell_count == cell_count_check);
  16974. write(&cell_count, sizeof(cell_count));
  16975. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  16976. write_kv_cache_data(ctx, cell_ranges);
  16977. }
  16978. };
  16979. struct llama_data_read {
  16980. virtual const uint8_t * read(size_t size) = 0;
  16981. virtual void read_to(void * dst, size_t size) = 0;
  16982. virtual size_t get_size_read() = 0;
  16983. virtual ~llama_data_read() = default;
  16984. void read_string(std::string & str) {
  16985. uint32_t str_size;
  16986. read_to(&str_size, sizeof(str_size));
  16987. str.assign((const char *) read(str_size), str_size);
  16988. }
  16989. // validate model information
  16990. void read_model_info(const struct llama_context * ctx) {
  16991. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  16992. std::string arch_str;
  16993. read_string(arch_str);
  16994. if (cur_arch_str != arch_str) {
  16995. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  16996. }
  16997. // TODO: add more info which needs to be identical but which is not verified otherwise
  16998. }
  16999. //void read_rng(std::mt19937 & rng) {
  17000. // std::string rng_str;
  17001. // read_string(rng_str);
  17002. // std::istringstream rng_ss(rng_str);
  17003. // rng_ss >> rng;
  17004. // if (rng_ss.fail()) {
  17005. // throw std::runtime_error("failed to load RNG state");
  17006. // }
  17007. //}
  17008. void read_output_ids(struct llama_context * ctx) {
  17009. std::vector<int32_t> output_pos;
  17010. uint32_t n_outputs;
  17011. read_to(&n_outputs, sizeof(n_outputs));
  17012. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  17013. throw std::runtime_error("could not reserve outputs");
  17014. }
  17015. if (n_outputs) {
  17016. output_pos.resize(n_outputs);
  17017. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  17018. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  17019. int32_t id = output_pos[i];
  17020. if ((uint32_t) id >= ctx->cparams.n_batch) {
  17021. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  17022. }
  17023. ctx->output_ids[id] = i;
  17024. }
  17025. ctx->n_outputs = n_outputs;
  17026. }
  17027. }
  17028. void read_logits(struct llama_context * ctx) {
  17029. uint64_t logits_size;
  17030. read_to(&logits_size, sizeof(logits_size));
  17031. if (ctx->logits_size < logits_size) {
  17032. throw std::runtime_error("logits buffer too small");
  17033. }
  17034. if (logits_size) {
  17035. read_to(ctx->logits, logits_size * sizeof(float));
  17036. }
  17037. }
  17038. void read_embeddings(struct llama_context * ctx) {
  17039. uint64_t embeddings_size;
  17040. read_to(&embeddings_size, sizeof(embeddings_size));
  17041. if (ctx->embd_size < embeddings_size) {
  17042. throw std::runtime_error("embeddings buffer too small");
  17043. }
  17044. if (embeddings_size) {
  17045. read_to(ctx->embd, embeddings_size * sizeof(float));
  17046. }
  17047. }
  17048. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  17049. struct llama_kv_cache & kv_self = ctx->kv_self;
  17050. if (dest_seq_id != -1) {
  17051. // single sequence
  17052. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  17053. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  17054. batch.n_tokens = cell_count;
  17055. batch.n_seq_tokens = cell_count;
  17056. batch.n_seqs = 1;
  17057. for (uint32_t i = 0; i < cell_count; ++i) {
  17058. llama_pos pos;
  17059. uint32_t n_seq_id;
  17060. read_to(&pos, sizeof(pos));
  17061. read_to(&n_seq_id, sizeof(n_seq_id));
  17062. if (n_seq_id != 0) {
  17063. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  17064. return false;
  17065. }
  17066. batch.pos[i] = pos;
  17067. }
  17068. batch.n_seq_id[0] = 1;
  17069. batch.seq_id[0] = &dest_seq_id;
  17070. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  17071. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  17072. return false;
  17073. }
  17074. // 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)
  17075. // Assume that this is one contiguous block of cells
  17076. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  17077. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  17078. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  17079. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  17080. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  17081. } else {
  17082. // whole KV cache restore
  17083. if (cell_count > kv_self.size) {
  17084. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  17085. return false;
  17086. }
  17087. llama_kv_cache_clear(kv_self);
  17088. for (uint32_t i = 0; i < cell_count; ++i) {
  17089. llama_kv_cell & cell = kv_self.cells[i];
  17090. llama_pos pos;
  17091. uint32_t n_seq_id;
  17092. read_to(&pos, sizeof(pos));
  17093. read_to(&n_seq_id, sizeof(n_seq_id));
  17094. cell.pos = pos;
  17095. for (uint32_t j = 0; j < n_seq_id; ++j) {
  17096. llama_seq_id seq_id;
  17097. read_to(&seq_id, sizeof(seq_id));
  17098. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  17099. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  17100. return false;
  17101. }
  17102. cell.seq_id.insert(seq_id);
  17103. if (kv_self.recurrent) {
  17104. int32_t & tail = kv_self.cells[seq_id].tail;
  17105. if (tail != -1) {
  17106. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  17107. return false;
  17108. }
  17109. tail = i;
  17110. }
  17111. }
  17112. }
  17113. kv_self.head = 0;
  17114. kv_self.used = cell_count;
  17115. }
  17116. if (kv_self.recurrent) {
  17117. for (uint32_t i = 0; i < cell_count; ++i) {
  17118. uint32_t cell_id = kv_self.head + i;
  17119. // make sure the recurrent states will keep their restored state
  17120. kv_self.cells[cell_id].src = cell_id;
  17121. }
  17122. }
  17123. return true;
  17124. }
  17125. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  17126. const struct llama_hparams & hparams = ctx->model.hparams;
  17127. struct llama_kv_cache & kv_self = ctx->kv_self;
  17128. uint32_t v_trans;
  17129. uint32_t n_layer;
  17130. read_to(&v_trans, sizeof(v_trans));
  17131. read_to(&n_layer, sizeof(n_layer));
  17132. if (n_layer != hparams.n_layer) {
  17133. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  17134. return false;
  17135. }
  17136. if (cell_count > kv_self.size) {
  17137. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  17138. return false;
  17139. }
  17140. if (kv_self.v_trans != (bool) v_trans) {
  17141. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  17142. return false;
  17143. }
  17144. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  17145. for (uint32_t il = 0; il < n_layer; ++il) {
  17146. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  17147. // Read type of key
  17148. int32_t k_type_i_ref;
  17149. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  17150. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  17151. if (k_type_i != k_type_i_ref) {
  17152. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  17153. return false;
  17154. }
  17155. // Read row size of key
  17156. uint64_t k_size_row_ref;
  17157. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  17158. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  17159. if (k_size_row != k_size_row_ref) {
  17160. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  17161. return false;
  17162. }
  17163. if (cell_count) {
  17164. // Read and set the keys for the whole cell range
  17165. 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);
  17166. }
  17167. }
  17168. if (!kv_self.v_trans) {
  17169. for (uint32_t il = 0; il < n_layer; ++il) {
  17170. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17171. // Read type of value
  17172. int32_t v_type_i_ref;
  17173. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17174. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17175. if (v_type_i != v_type_i_ref) {
  17176. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17177. return false;
  17178. }
  17179. // Read row size of value
  17180. uint64_t v_size_row_ref;
  17181. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  17182. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  17183. if (v_size_row != v_size_row_ref) {
  17184. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  17185. return false;
  17186. }
  17187. if (cell_count) {
  17188. // Read and set the values for the whole cell range
  17189. 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);
  17190. }
  17191. }
  17192. } else {
  17193. // For each layer, read the values for each cell (transposed)
  17194. for (uint32_t il = 0; il < n_layer; ++il) {
  17195. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  17196. // Read type of value
  17197. int32_t v_type_i_ref;
  17198. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  17199. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  17200. if (v_type_i != v_type_i_ref) {
  17201. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  17202. return false;
  17203. }
  17204. // Read element size of value
  17205. uint32_t v_size_el_ref;
  17206. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  17207. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  17208. if (v_size_el != v_size_el_ref) {
  17209. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  17210. return false;
  17211. }
  17212. // Read GQA embedding size
  17213. uint32_t n_embd_v_gqa_ref;
  17214. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  17215. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  17216. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  17217. return false;
  17218. }
  17219. if (cell_count) {
  17220. // For each row in the transposed matrix, read the values for the whole cell range
  17221. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  17222. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  17223. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  17224. }
  17225. }
  17226. }
  17227. }
  17228. return true;
  17229. }
  17230. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  17231. uint32_t cell_count;
  17232. read_to(&cell_count, sizeof(cell_count));
  17233. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  17234. if (!res) {
  17235. if (seq_id == -1) {
  17236. llama_kv_cache_clear(ctx);
  17237. } else {
  17238. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  17239. }
  17240. throw std::runtime_error("failed to restore kv cache");
  17241. }
  17242. }
  17243. };
  17244. struct llama_data_write_dummy : llama_data_write {
  17245. size_t size_written = 0;
  17246. llama_data_write_dummy() {}
  17247. void write(const void * /* src */, size_t size) override {
  17248. size_written += size;
  17249. }
  17250. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  17251. size_written += size;
  17252. }
  17253. size_t get_size_written() override {
  17254. return size_written;
  17255. }
  17256. };
  17257. struct llama_data_write_buffer : llama_data_write {
  17258. uint8_t * ptr;
  17259. size_t buf_size = 0;
  17260. size_t size_written = 0;
  17261. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17262. void write(const void * src, size_t size) override {
  17263. if (size > buf_size) {
  17264. throw std::runtime_error("unexpectedly reached end of buffer");
  17265. }
  17266. memcpy(ptr, src, size);
  17267. ptr += size;
  17268. size_written += size;
  17269. buf_size -= size;
  17270. }
  17271. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17272. if (size > buf_size) {
  17273. throw std::runtime_error("unexpectedly reached end of buffer");
  17274. }
  17275. ggml_backend_tensor_get(tensor, ptr, offset, size);
  17276. ptr += size;
  17277. size_written += size;
  17278. buf_size -= size;
  17279. }
  17280. size_t get_size_written() override {
  17281. return size_written;
  17282. }
  17283. };
  17284. struct llama_data_read_buffer : llama_data_read {
  17285. const uint8_t * ptr;
  17286. size_t buf_size = 0;
  17287. size_t size_read = 0;
  17288. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  17289. const uint8_t * read(size_t size) override {
  17290. const uint8_t * base_ptr = ptr;
  17291. if (size > buf_size) {
  17292. throw std::runtime_error("unexpectedly reached end of buffer");
  17293. }
  17294. ptr += size;
  17295. size_read += size;
  17296. buf_size -= size;
  17297. return base_ptr;
  17298. }
  17299. void read_to(void * dst, size_t size) override {
  17300. memcpy(dst, read(size), size);
  17301. }
  17302. size_t get_size_read() override {
  17303. return size_read;
  17304. }
  17305. };
  17306. struct llama_data_write_file : llama_data_write {
  17307. llama_file * file;
  17308. size_t size_written = 0;
  17309. std::vector<uint8_t> temp_buffer;
  17310. llama_data_write_file(llama_file * f) : file(f) {}
  17311. void write(const void * src, size_t size) override {
  17312. file->write_raw(src, size);
  17313. size_written += size;
  17314. }
  17315. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  17316. temp_buffer.resize(size);
  17317. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  17318. write(temp_buffer.data(), temp_buffer.size());
  17319. }
  17320. size_t get_size_written() override {
  17321. return size_written;
  17322. }
  17323. };
  17324. struct llama_data_read_file : llama_data_read {
  17325. llama_file * file;
  17326. size_t size_read = 0;
  17327. std::vector<uint8_t> temp_buffer;
  17328. llama_data_read_file(llama_file * f) : file(f) {}
  17329. void read_to(void * dst, size_t size) override {
  17330. file->read_raw(dst, size);
  17331. size_read += size;
  17332. }
  17333. const uint8_t * read(size_t size) override {
  17334. temp_buffer.resize(size);
  17335. read_to(temp_buffer.data(), size);
  17336. return temp_buffer.data();
  17337. }
  17338. size_t get_size_read() override {
  17339. return size_read;
  17340. }
  17341. };
  17342. /** copy state data into either a buffer or file depending on the passed in context
  17343. *
  17344. * file context:
  17345. * llama_file file("/path", "wb");
  17346. * llama_data_write_file data_ctx(&file);
  17347. * llama_state_get_data_internal(ctx, data_ctx);
  17348. *
  17349. * buffer context:
  17350. * std::vector<uint8_t> buf(max_size, 0);
  17351. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  17352. * llama_state_get_data_internal(ctx, data_ctx);
  17353. *
  17354. */
  17355. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  17356. llama_synchronize(ctx);
  17357. data_ctx.write_model_info(ctx);
  17358. // copy outputs
  17359. data_ctx.write_output_ids(ctx);
  17360. data_ctx.write_logits(ctx);
  17361. data_ctx.write_embeddings(ctx);
  17362. data_ctx.write_kv_cache(ctx);
  17363. return data_ctx.get_size_written();
  17364. }
  17365. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  17366. llama_data_write_buffer data_ctx(dst, size);
  17367. try {
  17368. return llama_state_get_data_internal(ctx, data_ctx);
  17369. } catch (const std::exception & err) {
  17370. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  17371. return 0;
  17372. }
  17373. }
  17374. // Returns the *actual* size of the state.
  17375. // Intended to be used when saving to state to a buffer.
  17376. size_t llama_state_get_size(struct llama_context * ctx) {
  17377. llama_data_write_dummy data_ctx;
  17378. try {
  17379. return llama_state_get_data_internal(ctx, data_ctx);
  17380. } catch (const std::exception & err) {
  17381. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  17382. return 0;
  17383. }
  17384. }
  17385. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  17386. llama_synchronize(ctx);
  17387. data_ctx.read_model_info(ctx);
  17388. // set outputs
  17389. data_ctx.read_output_ids(ctx);
  17390. data_ctx.read_logits(ctx);
  17391. data_ctx.read_embeddings(ctx);
  17392. data_ctx.read_kv_cache(ctx);
  17393. return data_ctx.get_size_read();
  17394. }
  17395. // Sets the state reading from the specified source address
  17396. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  17397. llama_data_read_buffer data_ctx(src, size);
  17398. try {
  17399. return llama_state_set_data_internal(ctx, data_ctx);
  17400. } catch (const std::exception & err) {
  17401. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  17402. return 0;
  17403. }
  17404. }
  17405. 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) {
  17406. llama_file file(path_session, "rb");
  17407. // sanity checks
  17408. {
  17409. const uint32_t magic = file.read_u32();
  17410. const uint32_t version = file.read_u32();
  17411. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  17412. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  17413. return false;
  17414. }
  17415. }
  17416. // load the prompt
  17417. {
  17418. const uint32_t n_token_count = file.read_u32();
  17419. if (n_token_count > n_token_capacity) {
  17420. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  17421. return false;
  17422. }
  17423. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  17424. *n_token_count_out = n_token_count;
  17425. }
  17426. // restore the context state
  17427. {
  17428. const size_t n_state_size_cur = file.size - file.tell();
  17429. llama_data_read_file data_ctx(&file);
  17430. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  17431. if (n_read != n_state_size_cur) {
  17432. 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);
  17433. return false;
  17434. }
  17435. }
  17436. return true;
  17437. }
  17438. 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) {
  17439. try {
  17440. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  17441. } catch (const std::exception & err) {
  17442. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  17443. return false;
  17444. }
  17445. }
  17446. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17447. llama_file file(path_session, "wb");
  17448. file.write_u32(LLAMA_SESSION_MAGIC);
  17449. file.write_u32(LLAMA_SESSION_VERSION);
  17450. // save the prompt
  17451. file.write_u32((uint32_t) n_token_count);
  17452. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  17453. // save the context state using stream saving
  17454. llama_data_write_file data_ctx(&file);
  17455. llama_state_get_data_internal(ctx, data_ctx);
  17456. return true;
  17457. }
  17458. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  17459. try {
  17460. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  17461. } catch (const std::exception & err) {
  17462. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  17463. return false;
  17464. }
  17465. }
  17466. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  17467. llama_synchronize(ctx);
  17468. data_ctx.write_kv_cache(ctx, seq_id);
  17469. return data_ctx.get_size_written();
  17470. }
  17471. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  17472. llama_data_write_dummy data_ctx;
  17473. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  17474. }
  17475. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  17476. llama_data_write_buffer data_ctx(dst, size);
  17477. try {
  17478. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  17479. } catch (const std::exception & err) {
  17480. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  17481. return 0;
  17482. }
  17483. }
  17484. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  17485. llama_synchronize(ctx);
  17486. data_ctx.read_kv_cache(ctx, dest_seq_id);
  17487. return data_ctx.get_size_read();
  17488. }
  17489. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  17490. llama_data_read_buffer data_ctx(src, size);
  17491. try {
  17492. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  17493. } catch (const std::exception & err) {
  17494. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  17495. return 0;
  17496. }
  17497. }
  17498. 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) {
  17499. llama_file file(filepath, "wb");
  17500. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  17501. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  17502. // save the prompt
  17503. file.write_u32((uint32_t) n_token_count);
  17504. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  17505. // save the context state using stream saving
  17506. llama_data_write_file data_ctx(&file);
  17507. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  17508. const size_t res = file.tell();
  17509. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  17510. return res;
  17511. }
  17512. 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) {
  17513. llama_file file(filepath, "rb");
  17514. // version checks
  17515. {
  17516. const uint32_t magic = file.read_u32();
  17517. const uint32_t version = file.read_u32();
  17518. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  17519. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  17520. return 0;
  17521. }
  17522. }
  17523. // load the prompt
  17524. {
  17525. const uint32_t n_token_count = file.read_u32();
  17526. if (n_token_count > n_token_capacity) {
  17527. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  17528. return 0;
  17529. }
  17530. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  17531. *n_token_count_out = n_token_count;
  17532. }
  17533. // restore the context state
  17534. {
  17535. const size_t state_size = file.size - file.tell();
  17536. llama_data_read_file data_ctx(&file);
  17537. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  17538. if (!nread) {
  17539. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  17540. return 0;
  17541. }
  17542. GGML_ASSERT(nread <= state_size);
  17543. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  17544. }
  17545. return file.tell();
  17546. }
  17547. 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) {
  17548. try {
  17549. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  17550. } catch (const std::exception & err) {
  17551. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  17552. return 0;
  17553. }
  17554. }
  17555. 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) {
  17556. try {
  17557. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  17558. } catch (const std::exception & err) {
  17559. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  17560. return 0;
  17561. }
  17562. }
  17563. void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
  17564. ctx->cparams.n_threads = n_threads;
  17565. ctx->cparams.n_threads_batch = n_threads_batch;
  17566. }
  17567. int32_t llama_n_threads(struct llama_context * ctx) {
  17568. return ctx->cparams.n_threads;
  17569. }
  17570. int32_t llama_n_threads_batch(struct llama_context * ctx) {
  17571. return ctx->cparams.n_threads_batch;
  17572. }
  17573. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  17574. ctx->abort_callback = abort_callback;
  17575. ctx->abort_callback_data = abort_callback_data;
  17576. }
  17577. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  17578. ctx->cparams.embeddings = embeddings;
  17579. }
  17580. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  17581. ctx->cparams.causal_attn = causal_attn;
  17582. }
  17583. struct llama_batch llama_batch_get_one(
  17584. llama_token * tokens,
  17585. int32_t n_tokens) {
  17586. return {
  17587. /*n_tokens =*/ n_tokens,
  17588. /*tokens =*/ tokens,
  17589. /*embd =*/ nullptr,
  17590. /*pos =*/ nullptr,
  17591. /*n_seq_id =*/ nullptr,
  17592. /*seq_id =*/ nullptr,
  17593. /*logits =*/ nullptr,
  17594. };
  17595. }
  17596. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  17597. llama_batch batch = {
  17598. /*n_tokens =*/ 0,
  17599. /*tokens =*/ nullptr,
  17600. /*embd =*/ nullptr,
  17601. /*pos =*/ nullptr,
  17602. /*n_seq_id =*/ nullptr,
  17603. /*seq_id =*/ nullptr,
  17604. /*logits =*/ nullptr,
  17605. };
  17606. if (embd) {
  17607. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  17608. } else {
  17609. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  17610. }
  17611. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  17612. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  17613. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  17614. for (int i = 0; i < n_tokens_alloc; ++i) {
  17615. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  17616. }
  17617. batch.seq_id[n_tokens_alloc] = nullptr;
  17618. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  17619. return batch;
  17620. }
  17621. void llama_batch_free(struct llama_batch batch) {
  17622. if (batch.token) free(batch.token);
  17623. if (batch.embd) free(batch.embd);
  17624. if (batch.pos) free(batch.pos);
  17625. if (batch.n_seq_id) free(batch.n_seq_id);
  17626. if (batch.seq_id) {
  17627. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  17628. free(batch.seq_id[i]);
  17629. }
  17630. free(batch.seq_id);
  17631. }
  17632. if (batch.logits) free(batch.logits);
  17633. }
  17634. // temporary allocate memory for the input batch if needed
  17635. static const llama_seq_id batch_default_seq_id = 0;
  17636. struct llama_batch_allocr {
  17637. std::array<llama_seq_id, 1> seq_id_0 = {batch_default_seq_id};
  17638. std::vector<llama_pos> pos;
  17639. std::vector<int32_t> n_seq_id;
  17640. std::vector<llama_seq_id *> seq_id;
  17641. std::vector<int8_t> logits;
  17642. struct llama_batch batch;
  17643. // optionally fulfill the batch returned by llama_batch_get_one
  17644. llama_batch_allocr(struct llama_context * ctx, struct llama_batch in_batch) {
  17645. batch = in_batch;
  17646. if (!batch.pos) {
  17647. // determine the last position in KV cache
  17648. llama_pos last_pos = -1;
  17649. for (const auto & cell : ctx->kv_self.cells) {
  17650. if (cell.has_seq_id(batch_default_seq_id)) {
  17651. last_pos = std::max(last_pos, cell.pos);
  17652. }
  17653. }
  17654. last_pos++; // next position
  17655. pos.resize(batch.n_tokens);
  17656. for (int32_t i = 0; i < batch.n_tokens; i++) {
  17657. pos[i] = i+last_pos;
  17658. }
  17659. batch.pos = pos.data();
  17660. }
  17661. if (!batch.n_seq_id) {
  17662. n_seq_id.resize(batch.n_tokens);
  17663. for (int32_t i = 0; i < batch.n_tokens; i++) {
  17664. n_seq_id[i] = seq_id_0.size();
  17665. }
  17666. batch.n_seq_id = n_seq_id.data();
  17667. }
  17668. if (!batch.seq_id) {
  17669. seq_id.resize(batch.n_tokens + 1);
  17670. seq_id[batch.n_tokens] = NULL;
  17671. for (int32_t i = 0; i < batch.n_tokens; i++) {
  17672. seq_id[i] = seq_id_0.data();
  17673. }
  17674. batch.seq_id = seq_id.data();
  17675. }
  17676. if (!batch.logits) {
  17677. logits.resize(batch.n_tokens);
  17678. logits[logits.size() - 1] = true;
  17679. batch.logits = logits.data();
  17680. }
  17681. }
  17682. };
  17683. int32_t llama_encode(
  17684. struct llama_context * ctx,
  17685. struct llama_batch batch) {
  17686. llama_batch_allocr batch_allocr(ctx, batch);
  17687. const int ret = llama_encode_internal(*ctx, batch_allocr.batch);
  17688. if (ret != 0) {
  17689. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  17690. }
  17691. return ret;
  17692. }
  17693. int32_t llama_decode(
  17694. struct llama_context * ctx,
  17695. struct llama_batch batch) {
  17696. llama_batch_allocr batch_allocr(ctx, batch);
  17697. const int ret = llama_decode_internal(*ctx, batch_allocr.batch);
  17698. if (ret != 0) {
  17699. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  17700. }
  17701. return ret;
  17702. }
  17703. void llama_synchronize(struct llama_context * ctx) {
  17704. ggml_backend_sched_synchronize(ctx->sched);
  17705. // FIXME: if multiple single tokens are evaluated without a synchronization,
  17706. // the stats will be added to the prompt evaluation stats
  17707. // this should only happen when using batch size 1 to evaluate a batch
  17708. // add the evaluation to the stats
  17709. if (ctx->n_queued_tokens == 1) {
  17710. if (!ctx->cparams.no_perf) {
  17711. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  17712. }
  17713. ctx->n_eval++;
  17714. } else if (ctx->n_queued_tokens > 1) {
  17715. if (!ctx->cparams.no_perf) {
  17716. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  17717. }
  17718. ctx->n_p_eval += ctx->n_queued_tokens;
  17719. }
  17720. // get a more accurate load time, upon first eval
  17721. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  17722. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  17723. ctx->has_evaluated_once = true;
  17724. }
  17725. ctx->n_queued_tokens = 0;
  17726. ctx->t_compute_start_us = 0;
  17727. }
  17728. float * llama_get_logits(struct llama_context * ctx) {
  17729. llama_synchronize(ctx);
  17730. // reorder logits for backward compatibility
  17731. // TODO: maybe deprecate this
  17732. llama_output_reorder(ctx);
  17733. return ctx->logits;
  17734. }
  17735. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  17736. int32_t j = -1;
  17737. llama_synchronize(ctx);
  17738. try {
  17739. if (ctx->logits == nullptr) {
  17740. throw std::runtime_error("no logits");
  17741. }
  17742. if (i < 0) {
  17743. j = ctx->n_outputs + i;
  17744. if (j < 0) {
  17745. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  17746. }
  17747. } else if ((size_t) i >= ctx->output_ids.size()) {
  17748. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  17749. } else {
  17750. j = ctx->output_ids[i];
  17751. }
  17752. if (j < 0) {
  17753. throw std::runtime_error(format("batch.logits[%d] != true", i));
  17754. }
  17755. if (j >= ctx->n_outputs) {
  17756. // This should not happen
  17757. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  17758. }
  17759. return ctx->logits + j*ctx->model.hparams.n_vocab;
  17760. } catch (const std::exception & err) {
  17761. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  17762. #ifndef NDEBUG
  17763. GGML_ABORT("fatal error");
  17764. #else
  17765. return nullptr;
  17766. #endif
  17767. }
  17768. }
  17769. float * llama_get_embeddings(struct llama_context * ctx) {
  17770. llama_synchronize(ctx);
  17771. // reorder embeddings for backward compatibility
  17772. // TODO: maybe deprecate this
  17773. llama_output_reorder(ctx);
  17774. return ctx->embd;
  17775. }
  17776. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  17777. int32_t j = -1;
  17778. llama_synchronize(ctx);
  17779. try {
  17780. if (ctx->embd == nullptr) {
  17781. throw std::runtime_error("no embeddings");
  17782. }
  17783. if (i < 0) {
  17784. j = ctx->n_outputs + i;
  17785. if (j < 0) {
  17786. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  17787. }
  17788. } else if ((size_t) i >= ctx->output_ids.size()) {
  17789. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  17790. } else {
  17791. j = ctx->output_ids[i];
  17792. }
  17793. if (j < 0) {
  17794. throw std::runtime_error(format("batch.logits[%d] != true", i));
  17795. }
  17796. if (j >= ctx->n_outputs) {
  17797. // This should not happen
  17798. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  17799. }
  17800. return ctx->embd + j*ctx->model.hparams.n_embd;
  17801. } catch (const std::exception & err) {
  17802. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  17803. #ifndef NDEBUG
  17804. GGML_ABORT("fatal error");
  17805. #else
  17806. return nullptr;
  17807. #endif
  17808. }
  17809. }
  17810. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  17811. llama_synchronize(ctx);
  17812. auto it = ctx->embd_seq.find(seq_id);
  17813. if (it == ctx->embd_seq.end()) {
  17814. return nullptr;
  17815. }
  17816. return it->second.data();
  17817. }
  17818. //
  17819. // vocab
  17820. //
  17821. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  17822. return llama_token_get_text_impl(model->vocab, token);
  17823. }
  17824. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  17825. return llama_token_get_score_impl(model->vocab, token);
  17826. }
  17827. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  17828. return llama_token_get_attr_impl(model->vocab, token);
  17829. }
  17830. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  17831. return llama_token_is_eog_impl(model->vocab, token);
  17832. }
  17833. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  17834. return llama_token_is_control_impl(model->vocab, token);
  17835. }
  17836. llama_token llama_token_bos(const struct llama_model * model) {
  17837. return llama_token_bos_impl(model->vocab);
  17838. }
  17839. llama_token llama_token_eos(const struct llama_model * model) {
  17840. return llama_token_eos_impl(model->vocab);
  17841. }
  17842. llama_token llama_token_eot(const struct llama_model * model) {
  17843. return llama_token_eot_impl(model->vocab);
  17844. }
  17845. llama_token llama_token_cls(const struct llama_model * model) {
  17846. return llama_token_cls_impl(model->vocab);
  17847. }
  17848. llama_token llama_token_sep(const struct llama_model * model) {
  17849. return llama_token_sep_impl(model->vocab);
  17850. }
  17851. llama_token llama_token_nl (const struct llama_model * model) {
  17852. return llama_token_nl_impl(model->vocab);
  17853. }
  17854. llama_token llama_token_pad(const struct llama_model * model) {
  17855. return llama_token_pad_impl(model->vocab);
  17856. }
  17857. bool llama_add_bos_token(const struct llama_model * model) {
  17858. return llama_add_bos_token_impl(model->vocab);
  17859. }
  17860. bool llama_add_eos_token(const struct llama_model * model) {
  17861. return llama_add_eos_token_impl(model->vocab);
  17862. }
  17863. llama_token llama_token_prefix(const struct llama_model * model) {
  17864. return llama_token_prefix_impl(model->vocab);
  17865. }
  17866. llama_token llama_token_middle(const struct llama_model * model) {
  17867. return llama_token_middle_impl(model->vocab);
  17868. }
  17869. llama_token llama_token_suffix(const struct llama_model * model) {
  17870. return llama_token_suffix_impl(model->vocab);
  17871. }
  17872. llama_token llama_token_fim_pre(const struct llama_model * model) {
  17873. return llama_token_fim_pre_impl(model->vocab);
  17874. }
  17875. llama_token llama_token_fim_suf(const struct llama_model * model) {
  17876. return llama_token_fim_suf_impl(model->vocab);
  17877. }
  17878. llama_token llama_token_fim_mid(const struct llama_model * model) {
  17879. return llama_token_fim_mid_impl(model->vocab);
  17880. }
  17881. llama_token llama_token_fim_pad(const struct llama_model * model) {
  17882. return llama_token_fim_pad_impl(model->vocab);
  17883. }
  17884. llama_token llama_token_fim_rep(const struct llama_model * model) {
  17885. return llama_token_fim_rep_impl(model->vocab);
  17886. }
  17887. llama_token llama_token_fim_sep(const struct llama_model * model) {
  17888. return llama_token_fim_sep_impl(model->vocab);
  17889. }
  17890. //
  17891. // tokenization
  17892. //
  17893. int32_t llama_tokenize(
  17894. const struct llama_model * model,
  17895. const char * text,
  17896. int32_t text_len,
  17897. llama_token * tokens,
  17898. int32_t n_tokens_max,
  17899. bool add_special,
  17900. bool parse_special) {
  17901. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  17902. }
  17903. int32_t llama_token_to_piece(
  17904. const struct llama_model * model,
  17905. llama_token token,
  17906. char * buf,
  17907. int32_t length,
  17908. int32_t lstrip,
  17909. bool special) {
  17910. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  17911. }
  17912. int32_t llama_detokenize(
  17913. const struct llama_model * model,
  17914. const llama_token * tokens,
  17915. int32_t n_tokens,
  17916. char * text,
  17917. int32_t text_len_max,
  17918. bool remove_special,
  17919. bool unparse_special) {
  17920. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  17921. }
  17922. //
  17923. // chat templates
  17924. //
  17925. // Simple version of "llama_apply_chat_template" that only works with strings
  17926. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  17927. static int32_t llama_chat_apply_template_internal(
  17928. const std::string & tmpl,
  17929. const std::vector<const llama_chat_message *> & chat,
  17930. std::string & dest, bool add_ass) {
  17931. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  17932. std::stringstream ss;
  17933. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  17934. return tmpl.find(haystack) != std::string::npos;
  17935. };
  17936. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  17937. // chatml template
  17938. for (auto message : chat) {
  17939. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  17940. }
  17941. if (add_ass) {
  17942. ss << "<|im_start|>assistant\n";
  17943. }
  17944. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  17945. // llama2 template and its variants
  17946. // [variant] support system message
  17947. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  17948. // [variant] space before + after response
  17949. bool space_around_response = tmpl_contains("' ' + eos_token");
  17950. // [variant] add BOS inside history
  17951. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  17952. // [variant] trim spaces from the input message
  17953. bool strip_message = tmpl_contains("content.strip()");
  17954. // construct the prompt
  17955. bool is_inside_turn = true; // skip BOS at the beginning
  17956. ss << "[INST] ";
  17957. for (auto message : chat) {
  17958. std::string content = strip_message ? trim(message->content) : message->content;
  17959. std::string role(message->role);
  17960. if (!is_inside_turn) {
  17961. is_inside_turn = true;
  17962. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  17963. }
  17964. if (role == "system") {
  17965. if (support_system_message) {
  17966. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  17967. } else {
  17968. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  17969. ss << content << "\n";
  17970. }
  17971. } else if (role == "user") {
  17972. ss << content << " [/INST]";
  17973. } else {
  17974. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  17975. is_inside_turn = false;
  17976. }
  17977. }
  17978. // llama2 templates seem to not care about "add_generation_prompt"
  17979. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  17980. // Phi 3
  17981. for (auto message : chat) {
  17982. std::string role(message->role);
  17983. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  17984. }
  17985. if (add_ass) {
  17986. ss << "<|assistant|>\n";
  17987. }
  17988. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  17989. // zephyr template
  17990. for (auto message : chat) {
  17991. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  17992. }
  17993. if (add_ass) {
  17994. ss << "<|assistant|>\n";
  17995. }
  17996. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  17997. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  17998. for (auto message : chat) {
  17999. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  18000. ss << bos << message->role << "\n" << message->content << "</s>\n";
  18001. }
  18002. if (add_ass) {
  18003. ss << "<s>assistant\n";
  18004. }
  18005. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  18006. // google/gemma-7b-it
  18007. std::string system_prompt = "";
  18008. for (auto message : chat) {
  18009. std::string role(message->role);
  18010. if (role == "system") {
  18011. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  18012. system_prompt = trim(message->content);
  18013. continue;
  18014. }
  18015. // in gemma, "assistant" is "model"
  18016. role = role == "assistant" ? "model" : message->role;
  18017. ss << "<start_of_turn>" << role << "\n";
  18018. if (!system_prompt.empty() && role != "model") {
  18019. ss << system_prompt << "\n\n";
  18020. system_prompt = "";
  18021. }
  18022. ss << trim(message->content) << "<end_of_turn>\n";
  18023. }
  18024. if (add_ass) {
  18025. ss << "<start_of_turn>model\n";
  18026. }
  18027. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  18028. // OrionStarAI/Orion-14B-Chat
  18029. std::string system_prompt = "";
  18030. for (auto message : chat) {
  18031. std::string role(message->role);
  18032. if (role == "system") {
  18033. // there is no system message support, we will merge it with user prompt
  18034. system_prompt = message->content;
  18035. continue;
  18036. } else if (role == "user") {
  18037. ss << "Human: ";
  18038. if (!system_prompt.empty()) {
  18039. ss << system_prompt << "\n\n";
  18040. system_prompt = "";
  18041. }
  18042. ss << message->content << "\n\nAssistant: </s>";
  18043. } else {
  18044. ss << message->content << "</s>";
  18045. }
  18046. }
  18047. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  18048. // openchat/openchat-3.5-0106,
  18049. for (auto message : chat) {
  18050. std::string role(message->role);
  18051. if (role == "system") {
  18052. ss << message->content << "<|end_of_turn|>";
  18053. } else {
  18054. role[0] = toupper(role[0]);
  18055. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  18056. }
  18057. }
  18058. if (add_ass) {
  18059. ss << "GPT4 Correct Assistant:";
  18060. }
  18061. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  18062. // eachadea/vicuna-13b-1.1 (and Orca variant)
  18063. for (auto message : chat) {
  18064. std::string role(message->role);
  18065. if (role == "system") {
  18066. // Orca-Vicuna variant uses a system prefix
  18067. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  18068. ss << "SYSTEM: " << message->content << "\n";
  18069. } else {
  18070. ss << message->content << "\n\n";
  18071. }
  18072. } else if (role == "user") {
  18073. ss << "USER: " << message->content << "\n";
  18074. } else if (role == "assistant") {
  18075. ss << "ASSISTANT: " << message->content << "</s>\n";
  18076. }
  18077. }
  18078. if (add_ass) {
  18079. ss << "ASSISTANT:";
  18080. }
  18081. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  18082. // deepseek-ai/deepseek-coder-33b-instruct
  18083. for (auto message : chat) {
  18084. std::string role(message->role);
  18085. if (role == "system") {
  18086. ss << message->content;
  18087. } else if (role == "user") {
  18088. ss << "### Instruction:\n" << message->content << "\n";
  18089. } else if (role == "assistant") {
  18090. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  18091. }
  18092. }
  18093. if (add_ass) {
  18094. ss << "### Response:\n";
  18095. }
  18096. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  18097. // CohereForAI/c4ai-command-r-plus
  18098. for (auto message : chat) {
  18099. std::string role(message->role);
  18100. if (role == "system") {
  18101. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18102. } else if (role == "user") {
  18103. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18104. } else if (role == "assistant") {
  18105. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  18106. }
  18107. }
  18108. if (add_ass) {
  18109. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  18110. }
  18111. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  18112. // Llama 3
  18113. for (auto message : chat) {
  18114. std::string role(message->role);
  18115. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  18116. }
  18117. if (add_ass) {
  18118. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  18119. }
  18120. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  18121. // chatglm3-6b
  18122. ss << "[gMASK]" << "sop";
  18123. for (auto message : chat) {
  18124. std::string role(message->role);
  18125. ss << "<|" << role << "|>" << "\n " << message->content;
  18126. }
  18127. if (add_ass) {
  18128. ss << "<|assistant|>";
  18129. }
  18130. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  18131. ss << "[gMASK]" << "<sop>";
  18132. for (auto message : chat) {
  18133. std::string role(message->role);
  18134. ss << "<|" << role << "|>" << "\n" << message->content;
  18135. }
  18136. if (add_ass) {
  18137. ss << "<|assistant|>";
  18138. }
  18139. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  18140. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  18141. for (auto message : chat) {
  18142. std::string role(message->role);
  18143. if (role == "user") {
  18144. ss << LU8("<用户>");
  18145. ss << trim(message->content);
  18146. ss << "<AI>";
  18147. } else {
  18148. ss << trim(message->content);
  18149. }
  18150. }
  18151. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  18152. // DeepSeek-V2
  18153. for (auto message : chat) {
  18154. std::string role(message->role);
  18155. if (role == "system") {
  18156. ss << message->content << "\n\n";
  18157. } else if (role == "user") {
  18158. ss << "User: " << message->content << "\n\n";
  18159. } else if (role == "assistant") {
  18160. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  18161. }
  18162. }
  18163. if (add_ass) {
  18164. ss << "Assistant:";
  18165. }
  18166. } else if (tmpl == "exaone3" || (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]"))) {
  18167. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  18168. // EXAONE-3.0-7.8B-Instruct
  18169. for (auto message : chat) {
  18170. std::string role(message->role);
  18171. if (role == "system") {
  18172. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  18173. } else if (role == "user") {
  18174. ss << "[|user|]" << trim(message->content) << "\n";
  18175. } else if (role == "assistant") {
  18176. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  18177. }
  18178. }
  18179. if (add_ass) {
  18180. ss << "[|assistant|]";
  18181. }
  18182. } else {
  18183. // template not supported
  18184. return -1;
  18185. }
  18186. dest = ss.str();
  18187. return dest.size();
  18188. }
  18189. int32_t llama_chat_apply_template(
  18190. const struct llama_model * model,
  18191. const char * tmpl,
  18192. const struct llama_chat_message * chat,
  18193. size_t n_msg,
  18194. bool add_ass,
  18195. char * buf,
  18196. int32_t length) {
  18197. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  18198. if (tmpl == nullptr) {
  18199. GGML_ASSERT(model != nullptr);
  18200. // load template from model
  18201. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  18202. std::string template_key = "tokenizer.chat_template";
  18203. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  18204. if (res < 0) {
  18205. // worst case: there is no information about template, we will use chatml by default
  18206. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  18207. } else {
  18208. curr_tmpl = std::string(model_template.data(), model_template.size());
  18209. }
  18210. }
  18211. // format the chat to string
  18212. std::vector<const llama_chat_message *> chat_vec;
  18213. chat_vec.resize(n_msg);
  18214. for (size_t i = 0; i < n_msg; i++) {
  18215. chat_vec[i] = &chat[i];
  18216. }
  18217. std::string formatted_chat;
  18218. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  18219. if (res < 0) {
  18220. return res;
  18221. }
  18222. if (buf && length > 0) {
  18223. strncpy(buf, formatted_chat.c_str(), length);
  18224. }
  18225. return res;
  18226. }
  18227. //
  18228. // sampling
  18229. //
  18230. // TODO: remove indirection when vocab becomes accesible in llama-sampling.cpp
  18231. struct llama_sampler * llama_sampler_init_grammar(const struct llama_model * model, const char * grammar_str, const char * grammar_root) {
  18232. return llama_sampler_init_grammar_impl(model->vocab, grammar_str, grammar_root);
  18233. }
  18234. struct llama_sampler * llama_sampler_init_infill(const struct llama_model * model) {
  18235. return llama_sampler_init_infill_impl(model->vocab);
  18236. }
  18237. //
  18238. // model split
  18239. //
  18240. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  18241. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  18242. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  18243. return strlen(split_path);
  18244. }
  18245. return 0;
  18246. }
  18247. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  18248. std::string str_split_path(split_path);
  18249. char postfix[32];
  18250. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  18251. std::string str_postfix(postfix);
  18252. // check if dest ends with postfix
  18253. int size_prefix = str_split_path.size() - str_postfix.size();
  18254. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  18255. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  18256. return size_prefix;
  18257. }
  18258. return 0;
  18259. }
  18260. const char * llama_print_system_info(void) {
  18261. static std::string s;
  18262. s = "";
  18263. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  18264. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  18265. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  18266. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  18267. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  18268. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  18269. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  18270. s += "AMX_INT8 = " + std::to_string(ggml_cpu_has_amx_int8()) + " | ";
  18271. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  18272. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  18273. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  18274. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  18275. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  18276. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  18277. s += "RISCV_VECT = " + std::to_string(ggml_cpu_has_riscv_v()) + " | ";
  18278. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  18279. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  18280. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  18281. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  18282. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  18283. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  18284. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  18285. return s.c_str();
  18286. }
  18287. struct llama_perf_context_data llama_perf_context(const struct llama_context * ctx) {
  18288. struct llama_perf_context_data data = {};
  18289. if (ctx == nullptr) {
  18290. return data;
  18291. }
  18292. data.t_start_ms = 1e-3 * ctx->t_start_us;
  18293. data.t_load_ms = 1e-3 * ctx->t_load_us;
  18294. data.t_p_eval_ms = 1e-3 * ctx->t_p_eval_us;
  18295. data.t_eval_ms = 1e-3 * ctx->t_eval_us;
  18296. data.n_p_eval = std::max(1, ctx->n_p_eval);
  18297. data.n_eval = std::max(1, ctx->n_eval);
  18298. return data;
  18299. }
  18300. void llama_perf_context_print(const struct llama_context * ctx) {
  18301. const auto data = llama_perf_context(ctx);
  18302. const double t_end_ms = 1e-3 * ggml_time_us();
  18303. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, data.t_load_ms);
  18304. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  18305. __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);
  18306. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  18307. __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
  18308. 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));
  18309. }
  18310. void llama_perf_context_reset(struct llama_context * ctx) {
  18311. ctx->t_start_us = ggml_time_us();
  18312. ctx->t_eval_us = ctx->n_eval = 0;
  18313. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  18314. }
  18315. void llama_perf_dump_yaml(FILE * stream, const llama_context * ctx) {
  18316. fprintf(stream, "\n");
  18317. fprintf(stream, "###########\n");
  18318. fprintf(stream, "# Timings #\n");
  18319. fprintf(stream, "###########\n");
  18320. fprintf(stream, "\n");
  18321. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  18322. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  18323. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  18324. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  18325. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  18326. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  18327. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  18328. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  18329. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  18330. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  18331. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  18332. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  18333. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  18334. }
  18335. // For internal test use
  18336. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  18337. struct llama_context * ctx
  18338. ) {
  18339. return ctx->model.tensors_by_name;
  18340. }
  18341. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  18342. ggml_log_set(log_callback, user_data);
  18343. g_logger_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  18344. g_logger_state.log_callback_user_data = user_data;
  18345. }
  18346. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  18347. va_list args_copy;
  18348. va_copy(args_copy, args);
  18349. char buffer[128];
  18350. int len = vsnprintf(buffer, 128, format, args);
  18351. if (len < 128) {
  18352. g_logger_state.log_callback(level, buffer, g_logger_state.log_callback_user_data);
  18353. } else {
  18354. char * buffer2 = new char[len + 1];
  18355. vsnprintf(buffer2, len + 1, format, args_copy);
  18356. buffer2[len] = 0;
  18357. g_logger_state.log_callback(level, buffer2, g_logger_state.log_callback_user_data);
  18358. delete[] buffer2;
  18359. }
  18360. va_end(args_copy);
  18361. }
  18362. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  18363. va_list args;
  18364. va_start(args, format);
  18365. llama_log_internal_v(level, format, args);
  18366. va_end(args);
  18367. }
  18368. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  18369. (void) level;
  18370. (void) user_data;
  18371. fputs(text, stderr);
  18372. fflush(stderr);
  18373. }