llama.cpp 789 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162
  1. #include "llama-impl.h"
  2. #include "llama-vocab.h"
  3. #include "llama-grammar.h"
  4. #include "llama-sampling.h"
  5. #include "unicode.h"
  6. #include "ggml.h"
  7. #include "ggml-alloc.h"
  8. #include "ggml-backend.h"
  9. #ifdef GGML_USE_RPC
  10. # include "ggml-rpc.h"
  11. #endif
  12. #ifdef GGML_USE_CUDA
  13. # include "ggml-cuda.h"
  14. #elif defined(GGML_USE_VULKAN)
  15. # include "ggml-vulkan.h"
  16. #elif defined(GGML_USE_SYCL)
  17. # include "ggml-sycl.h"
  18. #elif defined(GGML_USE_KOMPUTE)
  19. # include "ggml-kompute.h"
  20. #elif defined(GGML_USE_CANN)
  21. # include "ggml-cann.h"
  22. #endif
  23. #ifdef GGML_USE_BLAS
  24. # include "ggml-blas.h"
  25. #endif
  26. #ifdef GGML_USE_METAL
  27. # include "ggml-metal.h"
  28. #endif
  29. // TODO: replace with ggml API call
  30. #define QK_K 256
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #if __cplusplus >= 202000L
  55. #define LU8(x) (const char*)(u8##x)
  56. #else
  57. #define LU8(x) u8##x
  58. #endif
  59. #include <algorithm>
  60. #include <array>
  61. #include <cassert>
  62. #include <cctype>
  63. #include <cfloat>
  64. #include <cinttypes>
  65. #include <climits>
  66. #include <cmath>
  67. #include <cstdarg>
  68. #include <cstddef>
  69. #include <cstdint>
  70. #include <cstdio>
  71. #include <cstring>
  72. #include <ctime>
  73. #include <fstream>
  74. #include <functional>
  75. #include <future>
  76. #include <initializer_list>
  77. #include <locale>
  78. #include <map>
  79. #include <memory>
  80. #include <mutex>
  81. #include <numeric>
  82. #include <set>
  83. #include <sstream>
  84. #include <thread>
  85. #include <type_traits>
  86. #include <unordered_map>
  87. #if defined(_MSC_VER)
  88. #pragma warning(disable: 4244 4267) // possible loss of data
  89. #endif
  90. // bump if necessary
  91. #define LLAMA_MAX_LAYERS 512
  92. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  93. //
  94. // helpers
  95. //
  96. // trim whitespace from the beginning and end of a string
  97. static std::string trim(const std::string & str) {
  98. size_t start = 0;
  99. size_t end = str.size();
  100. while (start < end && isspace(str[start])) {
  101. start += 1;
  102. }
  103. while (end > start && isspace(str[end - 1])) {
  104. end -= 1;
  105. }
  106. return str.substr(start, end - start);
  107. }
  108. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  109. std::string result;
  110. for (size_t pos = 0; ; pos += search.length()) {
  111. auto new_pos = s.find(search, pos);
  112. if (new_pos == std::string::npos) {
  113. result += s.substr(pos, s.size() - pos);
  114. break;
  115. }
  116. result += s.substr(pos, new_pos - pos) + replace;
  117. pos = new_pos;
  118. }
  119. s = std::move(result);
  120. }
  121. static bool is_float_close(float a, float b, float abs_tol) {
  122. // Check for non-negative tolerance
  123. if (abs_tol < 0.0) {
  124. throw std::invalid_argument("Tolerance must be non-negative");
  125. }
  126. // Exact equality check
  127. if (a == b) {
  128. return true;
  129. }
  130. // Check for infinities
  131. if (std::isinf(a) || std::isinf(b)) {
  132. return false;
  133. }
  134. // Regular comparison using the provided absolute tolerance
  135. return std::fabs(b - a) <= abs_tol;
  136. }
  137. static void zeros(std::ofstream & file, size_t n) {
  138. char zero = 0;
  139. for (size_t i = 0; i < n; ++i) {
  140. file.write(&zero, 1);
  141. }
  142. }
  143. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  144. static std::string format(const char * fmt, ...) {
  145. va_list ap;
  146. va_list ap2;
  147. va_start(ap, fmt);
  148. va_copy(ap2, ap);
  149. int size = vsnprintf(NULL, 0, fmt, ap);
  150. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  151. std::vector<char> buf(size + 1);
  152. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  153. GGML_ASSERT(size2 == size);
  154. va_end(ap2);
  155. va_end(ap);
  156. return std::string(buf.data(), size);
  157. }
  158. //
  159. // gguf constants (sync with gguf.py)
  160. //
  161. enum llm_arch {
  162. LLM_ARCH_LLAMA,
  163. LLM_ARCH_FALCON,
  164. LLM_ARCH_BAICHUAN,
  165. LLM_ARCH_GROK,
  166. LLM_ARCH_GPT2,
  167. LLM_ARCH_GPTJ,
  168. LLM_ARCH_GPTNEOX,
  169. LLM_ARCH_MPT,
  170. LLM_ARCH_STARCODER,
  171. LLM_ARCH_REFACT,
  172. LLM_ARCH_BERT,
  173. LLM_ARCH_NOMIC_BERT,
  174. LLM_ARCH_JINA_BERT_V2,
  175. LLM_ARCH_BLOOM,
  176. LLM_ARCH_STABLELM,
  177. LLM_ARCH_QWEN,
  178. LLM_ARCH_QWEN2,
  179. LLM_ARCH_QWEN2MOE,
  180. LLM_ARCH_PHI2,
  181. LLM_ARCH_PHI3,
  182. LLM_ARCH_PLAMO,
  183. LLM_ARCH_CODESHELL,
  184. LLM_ARCH_ORION,
  185. LLM_ARCH_INTERNLM2,
  186. LLM_ARCH_MINICPM,
  187. LLM_ARCH_GEMMA,
  188. LLM_ARCH_GEMMA2,
  189. LLM_ARCH_STARCODER2,
  190. LLM_ARCH_MAMBA,
  191. LLM_ARCH_XVERSE,
  192. LLM_ARCH_COMMAND_R,
  193. LLM_ARCH_DBRX,
  194. LLM_ARCH_OLMO,
  195. LLM_ARCH_OPENELM,
  196. LLM_ARCH_ARCTIC,
  197. LLM_ARCH_DEEPSEEK2,
  198. LLM_ARCH_CHATGLM,
  199. LLM_ARCH_BITNET,
  200. LLM_ARCH_T5,
  201. LLM_ARCH_JAIS,
  202. LLM_ARCH_UNKNOWN,
  203. };
  204. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  205. { LLM_ARCH_LLAMA, "llama" },
  206. { LLM_ARCH_FALCON, "falcon" },
  207. { LLM_ARCH_GROK, "grok" },
  208. { LLM_ARCH_GPT2, "gpt2" },
  209. { LLM_ARCH_GPTJ, "gptj" },
  210. { LLM_ARCH_GPTNEOX, "gptneox" },
  211. { LLM_ARCH_MPT, "mpt" },
  212. { LLM_ARCH_BAICHUAN, "baichuan" },
  213. { LLM_ARCH_STARCODER, "starcoder" },
  214. { LLM_ARCH_REFACT, "refact" },
  215. { LLM_ARCH_BERT, "bert" },
  216. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  217. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  218. { LLM_ARCH_BLOOM, "bloom" },
  219. { LLM_ARCH_STABLELM, "stablelm" },
  220. { LLM_ARCH_QWEN, "qwen" },
  221. { LLM_ARCH_QWEN2, "qwen2" },
  222. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  223. { LLM_ARCH_PHI2, "phi2" },
  224. { LLM_ARCH_PHI3, "phi3" },
  225. { LLM_ARCH_PLAMO, "plamo" },
  226. { LLM_ARCH_CODESHELL, "codeshell" },
  227. { LLM_ARCH_ORION, "orion" },
  228. { LLM_ARCH_INTERNLM2, "internlm2" },
  229. { LLM_ARCH_MINICPM, "minicpm" },
  230. { LLM_ARCH_GEMMA, "gemma" },
  231. { LLM_ARCH_GEMMA2, "gemma2" },
  232. { LLM_ARCH_STARCODER2, "starcoder2" },
  233. { LLM_ARCH_MAMBA, "mamba" },
  234. { LLM_ARCH_XVERSE, "xverse" },
  235. { LLM_ARCH_COMMAND_R, "command-r" },
  236. { LLM_ARCH_DBRX, "dbrx" },
  237. { LLM_ARCH_OLMO, "olmo" },
  238. { LLM_ARCH_OPENELM, "openelm" },
  239. { LLM_ARCH_ARCTIC, "arctic" },
  240. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  241. { LLM_ARCH_CHATGLM, "chatglm" },
  242. { LLM_ARCH_BITNET, "bitnet" },
  243. { LLM_ARCH_T5, "t5" },
  244. { LLM_ARCH_JAIS, "jais" },
  245. { LLM_ARCH_UNKNOWN, "(unknown)" },
  246. };
  247. enum llm_kv {
  248. LLM_KV_GENERAL_TYPE,
  249. LLM_KV_GENERAL_ARCHITECTURE,
  250. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  251. LLM_KV_GENERAL_ALIGNMENT,
  252. LLM_KV_GENERAL_NAME,
  253. LLM_KV_GENERAL_AUTHOR,
  254. LLM_KV_GENERAL_VERSION,
  255. LLM_KV_GENERAL_URL,
  256. LLM_KV_GENERAL_DESCRIPTION,
  257. LLM_KV_GENERAL_LICENSE,
  258. LLM_KV_GENERAL_SOURCE_URL,
  259. LLM_KV_GENERAL_SOURCE_HF_REPO,
  260. LLM_KV_VOCAB_SIZE,
  261. LLM_KV_CONTEXT_LENGTH,
  262. LLM_KV_EMBEDDING_LENGTH,
  263. LLM_KV_BLOCK_COUNT,
  264. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  265. LLM_KV_FEED_FORWARD_LENGTH,
  266. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  267. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  268. LLM_KV_USE_PARALLEL_RESIDUAL,
  269. LLM_KV_TENSOR_DATA_LAYOUT,
  270. LLM_KV_EXPERT_COUNT,
  271. LLM_KV_EXPERT_USED_COUNT,
  272. LLM_KV_EXPERT_SHARED_COUNT,
  273. LLM_KV_EXPERT_WEIGHTS_SCALE,
  274. LLM_KV_POOLING_TYPE,
  275. LLM_KV_LOGIT_SCALE,
  276. LLM_KV_DECODER_START_TOKEN_ID,
  277. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  278. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  279. LLM_KV_ATTENTION_HEAD_COUNT,
  280. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  281. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  282. LLM_KV_ATTENTION_CLAMP_KQV,
  283. LLM_KV_ATTENTION_KEY_LENGTH,
  284. LLM_KV_ATTENTION_VALUE_LENGTH,
  285. LLM_KV_ATTENTION_LAYERNORM_EPS,
  286. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  287. LLM_KV_ATTENTION_CAUSAL,
  288. LLM_KV_ATTENTION_Q_LORA_RANK,
  289. LLM_KV_ATTENTION_KV_LORA_RANK,
  290. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  291. LLM_KV_ATTENTION_SLIDING_WINDOW,
  292. LLM_KV_ROPE_DIMENSION_COUNT,
  293. LLM_KV_ROPE_FREQ_BASE,
  294. LLM_KV_ROPE_SCALE_LINEAR,
  295. LLM_KV_ROPE_SCALING_TYPE,
  296. LLM_KV_ROPE_SCALING_FACTOR,
  297. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  298. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  299. LLM_KV_ROPE_SCALING_FINETUNED,
  300. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  301. LLM_KV_SPLIT_NO,
  302. LLM_KV_SPLIT_COUNT,
  303. LLM_KV_SPLIT_TENSORS_COUNT,
  304. LLM_KV_SSM_INNER_SIZE,
  305. LLM_KV_SSM_CONV_KERNEL,
  306. LLM_KV_SSM_STATE_SIZE,
  307. LLM_KV_SSM_TIME_STEP_RANK,
  308. LLM_KV_TOKENIZER_MODEL,
  309. LLM_KV_TOKENIZER_PRE,
  310. LLM_KV_TOKENIZER_LIST,
  311. LLM_KV_TOKENIZER_TOKEN_TYPE,
  312. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  313. LLM_KV_TOKENIZER_SCORES,
  314. LLM_KV_TOKENIZER_MERGES,
  315. LLM_KV_TOKENIZER_BOS_ID,
  316. LLM_KV_TOKENIZER_EOS_ID,
  317. LLM_KV_TOKENIZER_UNK_ID,
  318. LLM_KV_TOKENIZER_SEP_ID,
  319. LLM_KV_TOKENIZER_PAD_ID,
  320. LLM_KV_TOKENIZER_CLS_ID,
  321. LLM_KV_TOKENIZER_MASK_ID,
  322. LLM_KV_TOKENIZER_ADD_BOS,
  323. LLM_KV_TOKENIZER_ADD_EOS,
  324. LLM_KV_TOKENIZER_ADD_PREFIX,
  325. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  326. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  327. LLM_KV_TOKENIZER_HF_JSON,
  328. LLM_KV_TOKENIZER_RWKV,
  329. LLM_KV_TOKENIZER_PREFIX_ID,
  330. LLM_KV_TOKENIZER_SUFFIX_ID,
  331. LLM_KV_TOKENIZER_MIDDLE_ID,
  332. LLM_KV_TOKENIZER_EOT_ID,
  333. LLM_KV_ADAPTER_TYPE,
  334. LLM_KV_ADAPTER_LORA_ALPHA,
  335. };
  336. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  337. { LLM_KV_GENERAL_TYPE, "general.type" },
  338. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  339. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  340. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  341. { LLM_KV_GENERAL_NAME, "general.name" },
  342. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  343. { LLM_KV_GENERAL_VERSION, "general.version" },
  344. { LLM_KV_GENERAL_URL, "general.url" },
  345. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  346. { LLM_KV_GENERAL_LICENSE, "general.license" },
  347. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  348. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  349. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  350. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  351. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  352. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  353. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  354. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  355. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  356. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  357. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  358. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  359. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  360. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  361. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  362. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  363. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  364. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  365. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  366. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  367. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  368. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  369. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  370. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  371. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  372. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  373. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  374. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  375. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  376. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  377. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  378. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  379. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  380. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  381. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  382. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  383. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  384. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  385. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  386. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  387. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  388. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  389. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  390. { LLM_KV_SPLIT_NO, "split.no" },
  391. { LLM_KV_SPLIT_COUNT, "split.count" },
  392. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  393. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  394. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  395. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  396. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  397. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  398. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  399. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  400. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  401. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  402. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  403. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  404. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  405. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  406. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  407. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  408. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  409. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  410. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  411. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  412. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  413. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  414. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  415. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  416. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  417. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  418. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  419. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  420. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  421. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  422. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  423. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  424. };
  425. struct LLM_KV {
  426. LLM_KV(llm_arch arch) : arch(arch) {}
  427. llm_arch arch;
  428. std::string operator()(llm_kv kv) const {
  429. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  430. }
  431. };
  432. enum llm_tensor {
  433. LLM_TENSOR_TOKEN_EMBD,
  434. LLM_TENSOR_TOKEN_EMBD_NORM,
  435. LLM_TENSOR_TOKEN_TYPES,
  436. LLM_TENSOR_POS_EMBD,
  437. LLM_TENSOR_OUTPUT,
  438. LLM_TENSOR_OUTPUT_NORM,
  439. LLM_TENSOR_ROPE_FREQS,
  440. LLM_TENSOR_ROPE_FACTORS_LONG,
  441. LLM_TENSOR_ROPE_FACTORS_SHORT,
  442. LLM_TENSOR_ATTN_Q,
  443. LLM_TENSOR_ATTN_K,
  444. LLM_TENSOR_ATTN_V,
  445. LLM_TENSOR_ATTN_QKV,
  446. LLM_TENSOR_ATTN_OUT,
  447. LLM_TENSOR_ATTN_NORM,
  448. LLM_TENSOR_ATTN_NORM_2,
  449. LLM_TENSOR_ATTN_OUT_NORM,
  450. LLM_TENSOR_ATTN_POST_NORM,
  451. LLM_TENSOR_ATTN_ROT_EMBD,
  452. LLM_TENSOR_FFN_GATE_INP,
  453. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  454. LLM_TENSOR_FFN_NORM,
  455. LLM_TENSOR_FFN_POST_NORM,
  456. LLM_TENSOR_FFN_GATE,
  457. LLM_TENSOR_FFN_DOWN,
  458. LLM_TENSOR_FFN_UP,
  459. LLM_TENSOR_FFN_ACT,
  460. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  461. LLM_TENSOR_FFN_GATE_EXP,
  462. LLM_TENSOR_FFN_UP_EXP,
  463. LLM_TENSOR_FFN_NORM_EXPS,
  464. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  465. LLM_TENSOR_FFN_GATE_EXPS,
  466. LLM_TENSOR_FFN_UP_EXPS,
  467. LLM_TENSOR_FFN_DOWN_SHEXP,
  468. LLM_TENSOR_FFN_GATE_SHEXP,
  469. LLM_TENSOR_FFN_UP_SHEXP,
  470. LLM_TENSOR_ATTN_Q_NORM,
  471. LLM_TENSOR_ATTN_K_NORM,
  472. LLM_TENSOR_LAYER_OUT_NORM,
  473. LLM_TENSOR_SSM_IN,
  474. LLM_TENSOR_SSM_CONV1D,
  475. LLM_TENSOR_SSM_X,
  476. LLM_TENSOR_SSM_DT,
  477. LLM_TENSOR_SSM_A,
  478. LLM_TENSOR_SSM_D,
  479. LLM_TENSOR_SSM_OUT,
  480. LLM_TENSOR_ATTN_Q_A,
  481. LLM_TENSOR_ATTN_Q_B,
  482. LLM_TENSOR_ATTN_KV_A_MQA,
  483. LLM_TENSOR_ATTN_KV_B,
  484. LLM_TENSOR_ATTN_Q_A_NORM,
  485. LLM_TENSOR_ATTN_KV_A_NORM,
  486. LLM_TENSOR_ATTN_SUB_NORM,
  487. LLM_TENSOR_FFN_SUB_NORM,
  488. LLM_TENSOR_DEC_ATTN_NORM,
  489. LLM_TENSOR_DEC_ATTN_Q,
  490. LLM_TENSOR_DEC_ATTN_K,
  491. LLM_TENSOR_DEC_ATTN_V,
  492. LLM_TENSOR_DEC_ATTN_OUT,
  493. LLM_TENSOR_DEC_ATTN_REL_B,
  494. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  495. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  496. LLM_TENSOR_DEC_CROSS_ATTN_K,
  497. LLM_TENSOR_DEC_CROSS_ATTN_V,
  498. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  499. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  500. LLM_TENSOR_DEC_FFN_NORM,
  501. LLM_TENSOR_DEC_FFN_GATE,
  502. LLM_TENSOR_DEC_FFN_DOWN,
  503. LLM_TENSOR_DEC_FFN_UP,
  504. LLM_TENSOR_DEC_OUTPUT_NORM,
  505. LLM_TENSOR_ENC_ATTN_NORM,
  506. LLM_TENSOR_ENC_ATTN_Q,
  507. LLM_TENSOR_ENC_ATTN_K,
  508. LLM_TENSOR_ENC_ATTN_V,
  509. LLM_TENSOR_ENC_ATTN_OUT,
  510. LLM_TENSOR_ENC_ATTN_REL_B,
  511. LLM_TENSOR_ENC_FFN_NORM,
  512. LLM_TENSOR_ENC_FFN_GATE,
  513. LLM_TENSOR_ENC_FFN_DOWN,
  514. LLM_TENSOR_ENC_FFN_UP,
  515. LLM_TENSOR_ENC_OUTPUT_NORM,
  516. };
  517. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  518. {
  519. LLM_ARCH_LLAMA,
  520. {
  521. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  522. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  523. { LLM_TENSOR_OUTPUT, "output" },
  524. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  525. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  526. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  527. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  528. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  529. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  530. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  531. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  532. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  533. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  534. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  535. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  536. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  537. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  538. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  539. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  540. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  541. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  542. },
  543. },
  544. {
  545. LLM_ARCH_BAICHUAN,
  546. {
  547. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  548. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  549. { LLM_TENSOR_OUTPUT, "output" },
  550. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  551. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  552. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  553. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  554. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  555. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  556. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  557. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  558. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  561. },
  562. },
  563. {
  564. LLM_ARCH_FALCON,
  565. {
  566. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  567. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  568. { LLM_TENSOR_OUTPUT, "output" },
  569. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  570. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  571. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  572. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  573. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  574. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  575. },
  576. },
  577. {
  578. LLM_ARCH_GROK,
  579. {
  580. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  581. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  582. { LLM_TENSOR_OUTPUT, "output" },
  583. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  584. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  585. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  586. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  587. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  588. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  589. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  590. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  591. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  592. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  593. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  594. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  595. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  596. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  597. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  598. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  599. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  600. },
  601. },
  602. {
  603. LLM_ARCH_GPT2,
  604. {
  605. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  606. { LLM_TENSOR_POS_EMBD, "position_embd" },
  607. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  608. { LLM_TENSOR_OUTPUT, "output" },
  609. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  610. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  611. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  612. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  613. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  614. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  615. },
  616. },
  617. {
  618. LLM_ARCH_GPTJ,
  619. {
  620. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  621. },
  622. },
  623. {
  624. LLM_ARCH_GPTNEOX,
  625. {
  626. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  627. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  628. { LLM_TENSOR_OUTPUT, "output" },
  629. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  630. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  631. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  632. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  633. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  634. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  635. },
  636. },
  637. {
  638. LLM_ARCH_MPT,
  639. {
  640. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  641. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  642. { LLM_TENSOR_OUTPUT, "output"},
  643. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  644. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  645. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  646. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  647. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  648. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  649. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  650. { LLM_TENSOR_POS_EMBD, "position_embd" },
  651. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  652. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  653. },
  654. },
  655. {
  656. LLM_ARCH_STARCODER,
  657. {
  658. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  659. { LLM_TENSOR_POS_EMBD, "position_embd" },
  660. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  661. { LLM_TENSOR_OUTPUT, "output" },
  662. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  663. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  664. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  665. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  666. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  667. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  668. },
  669. },
  670. {
  671. LLM_ARCH_REFACT,
  672. {
  673. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  674. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  675. { LLM_TENSOR_OUTPUT, "output" },
  676. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  677. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  678. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  679. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  680. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  681. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  682. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  683. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  684. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  685. },
  686. },
  687. {
  688. LLM_ARCH_BERT,
  689. {
  690. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  691. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  692. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  693. { LLM_TENSOR_POS_EMBD, "position_embd" },
  694. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  695. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  696. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  697. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  698. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  699. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  700. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  701. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  702. },
  703. },
  704. {
  705. LLM_ARCH_NOMIC_BERT,
  706. {
  707. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  708. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  709. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  710. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  711. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  712. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  713. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  714. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  715. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  716. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  717. },
  718. },
  719. {
  720. LLM_ARCH_JINA_BERT_V2,
  721. {
  722. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  723. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  724. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  725. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  726. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  727. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  728. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  729. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  730. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  731. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  732. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  733. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  734. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  735. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  736. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  737. },
  738. },
  739. {
  740. LLM_ARCH_BLOOM,
  741. {
  742. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  743. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  744. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  745. { LLM_TENSOR_OUTPUT, "output" },
  746. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  747. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  748. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  749. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  750. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  751. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  752. },
  753. },
  754. {
  755. LLM_ARCH_STABLELM,
  756. {
  757. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  758. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  759. { LLM_TENSOR_OUTPUT, "output" },
  760. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  761. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  762. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  763. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  764. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  765. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  766. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  767. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  768. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  769. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  770. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  771. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  772. },
  773. },
  774. {
  775. LLM_ARCH_QWEN,
  776. {
  777. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  778. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  779. { LLM_TENSOR_OUTPUT, "output" },
  780. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  781. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  782. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  783. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  784. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  785. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  786. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  787. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  788. },
  789. },
  790. {
  791. LLM_ARCH_QWEN2,
  792. {
  793. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  794. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  795. { LLM_TENSOR_OUTPUT, "output" },
  796. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  797. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  798. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  799. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  800. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  801. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  802. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  803. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  804. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  805. },
  806. },
  807. {
  808. LLM_ARCH_QWEN2MOE,
  809. {
  810. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  811. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  812. { LLM_TENSOR_OUTPUT, "output" },
  813. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  814. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  815. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  816. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  817. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  818. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  819. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  820. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  821. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  822. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  823. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  824. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  825. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  826. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  827. },
  828. },
  829. {
  830. LLM_ARCH_PHI2,
  831. {
  832. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  833. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  834. { LLM_TENSOR_OUTPUT, "output" },
  835. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  836. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  837. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  838. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  839. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  840. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  841. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  842. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  843. },
  844. },
  845. {
  846. LLM_ARCH_PHI3,
  847. {
  848. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  849. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  850. { LLM_TENSOR_OUTPUT, "output" },
  851. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  852. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  853. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  854. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  855. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  856. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  857. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  858. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  859. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  860. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  861. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  862. },
  863. },
  864. {
  865. LLM_ARCH_PLAMO,
  866. {
  867. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  868. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  869. { LLM_TENSOR_OUTPUT, "output" },
  870. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  871. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  872. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  873. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  874. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  875. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  876. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  877. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  878. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  879. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  880. },
  881. },
  882. {
  883. LLM_ARCH_CODESHELL,
  884. {
  885. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  886. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  887. { LLM_TENSOR_OUTPUT, "output" },
  888. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  889. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  890. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  891. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  892. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  893. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  894. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  895. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  896. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  897. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  898. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  899. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  900. },
  901. },
  902. {
  903. LLM_ARCH_ORION,
  904. {
  905. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  906. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  907. { LLM_TENSOR_OUTPUT, "output" },
  908. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  909. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  910. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  911. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  912. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  913. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  914. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  915. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  916. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  917. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  918. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  919. },
  920. },
  921. {
  922. LLM_ARCH_INTERNLM2,
  923. {
  924. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  925. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  926. { LLM_TENSOR_OUTPUT, "output" },
  927. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  928. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  929. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  930. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  931. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  932. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  933. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  934. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  935. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  936. },
  937. },
  938. {
  939. LLM_ARCH_MINICPM,
  940. {
  941. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  942. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  943. { LLM_TENSOR_OUTPUT, "output" },
  944. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  945. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  946. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  947. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  948. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  949. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  950. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  951. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  952. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  953. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  954. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  955. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  956. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  957. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  958. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  959. },
  960. },
  961. {
  962. LLM_ARCH_GEMMA,
  963. {
  964. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  965. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  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_FFN_NORM, "blk.%d.ffn_norm" },
  972. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  973. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  974. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  975. },
  976. },
  977. {
  978. LLM_ARCH_GEMMA2,
  979. {
  980. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  981. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  982. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  983. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  984. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  985. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  986. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  987. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  988. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  989. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  990. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  991. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  992. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  993. },
  994. },
  995. {
  996. LLM_ARCH_STARCODER2,
  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_NORM, "blk.%d.ffn_norm" },
  1009. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1010. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1011. },
  1012. },
  1013. {
  1014. LLM_ARCH_MAMBA,
  1015. {
  1016. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1017. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1018. { LLM_TENSOR_OUTPUT, "output" },
  1019. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1020. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1021. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1022. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1023. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1024. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1025. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1026. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1027. },
  1028. },
  1029. {
  1030. LLM_ARCH_XVERSE,
  1031. {
  1032. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1033. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1034. { LLM_TENSOR_OUTPUT, "output" },
  1035. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1036. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1037. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1038. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1039. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1040. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1041. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1042. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1043. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1044. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1045. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1046. },
  1047. },
  1048. {
  1049. LLM_ARCH_COMMAND_R,
  1050. {
  1051. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1052. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1053. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1054. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1055. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1056. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1057. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1058. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1059. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1060. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1061. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1062. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1063. },
  1064. },
  1065. {
  1066. LLM_ARCH_DBRX,
  1067. {
  1068. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1069. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1070. { LLM_TENSOR_OUTPUT, "output" },
  1071. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1072. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1073. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1074. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1075. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1076. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1077. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1078. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1079. },
  1080. },
  1081. {
  1082. LLM_ARCH_OLMO,
  1083. {
  1084. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1085. { LLM_TENSOR_OUTPUT, "output" },
  1086. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1087. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1088. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1089. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1090. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1091. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1092. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1093. },
  1094. },
  1095. {
  1096. LLM_ARCH_OPENELM,
  1097. {
  1098. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1099. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1100. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1101. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1102. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1103. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1104. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1105. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1106. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1107. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1108. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1109. },
  1110. },
  1111. {
  1112. LLM_ARCH_ARCTIC,
  1113. {
  1114. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1115. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1116. { LLM_TENSOR_OUTPUT, "output" },
  1117. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1118. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1119. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1120. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1121. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1122. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1123. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1124. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1125. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1126. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1127. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1128. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1129. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1130. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1131. },
  1132. },
  1133. {
  1134. LLM_ARCH_DEEPSEEK2,
  1135. {
  1136. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1137. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1138. { LLM_TENSOR_OUTPUT, "output" },
  1139. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1140. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1141. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1142. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1143. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1144. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1145. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1146. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1147. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1148. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1149. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1150. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1151. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1152. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1153. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1154. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1155. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1156. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1157. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1158. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1159. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1160. },
  1161. },
  1162. {
  1163. LLM_ARCH_CHATGLM,
  1164. {
  1165. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1166. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1167. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1168. { LLM_TENSOR_OUTPUT, "output" },
  1169. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1170. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1171. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1172. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1173. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1174. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1175. },
  1176. },
  1177. {
  1178. LLM_ARCH_BITNET,
  1179. {
  1180. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1181. { LLM_TENSOR_OUTPUT_NORM, "output_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_NORM, "blk.%d.attn_norm" },
  1187. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1188. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1189. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1190. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1191. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1192. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1193. },
  1194. },
  1195. {
  1196. LLM_ARCH_T5,
  1197. {
  1198. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1199. { LLM_TENSOR_OUTPUT, "output" },
  1200. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1201. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1202. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1203. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1204. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1205. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1206. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1207. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1208. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1209. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1210. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1211. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1212. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1213. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1214. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1215. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1216. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1217. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1218. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1219. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1220. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1221. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1222. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1223. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1224. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1225. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1226. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1227. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1228. },
  1229. },
  1230. {
  1231. LLM_ARCH_JAIS,
  1232. {
  1233. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1234. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1235. { LLM_TENSOR_OUTPUT, "output" },
  1236. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1237. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1238. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1239. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1240. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1241. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1242. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1243. },
  1244. },
  1245. {
  1246. LLM_ARCH_UNKNOWN,
  1247. {
  1248. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1249. },
  1250. },
  1251. };
  1252. static llm_arch llm_arch_from_string(const std::string & name) {
  1253. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1254. if (kv.second == name) {
  1255. return kv.first;
  1256. }
  1257. }
  1258. return LLM_ARCH_UNKNOWN;
  1259. }
  1260. // helper to handle gguf constants
  1261. // usage:
  1262. //
  1263. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1264. //
  1265. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1266. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1267. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1268. //
  1269. struct LLM_TN {
  1270. LLM_TN(llm_arch arch) : arch(arch) {}
  1271. llm_arch arch;
  1272. std::string operator()(llm_tensor tensor) const {
  1273. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1274. return "__missing__";
  1275. }
  1276. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1277. }
  1278. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1279. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1280. return "__missing__";
  1281. }
  1282. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1283. }
  1284. std::string operator()(llm_tensor tensor, int bid) const {
  1285. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1286. return "__missing__";
  1287. }
  1288. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1289. }
  1290. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1291. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1292. return "__missing__";
  1293. }
  1294. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1295. }
  1296. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1297. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1298. return "__missing__";
  1299. }
  1300. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1301. }
  1302. };
  1303. //
  1304. // gguf helpers
  1305. //
  1306. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1307. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1308. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1309. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1310. };
  1311. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1312. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1313. if (kv.second == name) {
  1314. return (llama_rope_scaling_type) kv.first;
  1315. }
  1316. }
  1317. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1318. }
  1319. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1320. switch (type) {
  1321. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1322. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1323. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1324. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1325. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1326. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1327. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1328. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1329. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1330. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1331. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1332. default: return format("unknown type %d", type);
  1333. }
  1334. }
  1335. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1336. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1337. switch (type) {
  1338. case GGUF_TYPE_STRING:
  1339. return gguf_get_val_str(ctx_gguf, i);
  1340. case GGUF_TYPE_ARRAY:
  1341. {
  1342. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1343. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1344. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1345. std::stringstream ss;
  1346. ss << "[";
  1347. for (int j = 0; j < arr_n; j++) {
  1348. if (arr_type == GGUF_TYPE_STRING) {
  1349. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1350. // escape quotes
  1351. replace_all(val, "\\", "\\\\");
  1352. replace_all(val, "\"", "\\\"");
  1353. ss << '"' << val << '"';
  1354. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1355. ss << "???";
  1356. } else {
  1357. ss << gguf_data_to_str(arr_type, data, j);
  1358. }
  1359. if (j < arr_n - 1) {
  1360. ss << ", ";
  1361. }
  1362. }
  1363. ss << "]";
  1364. return ss.str();
  1365. }
  1366. default:
  1367. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1368. }
  1369. }
  1370. //
  1371. // llama helpers
  1372. //
  1373. #if defined(_WIN32)
  1374. static std::string llama_format_win_err(DWORD err) {
  1375. LPSTR buf;
  1376. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1377. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1378. if (!size) {
  1379. return "FormatMessageA failed";
  1380. }
  1381. std::string ret(buf, size);
  1382. LocalFree(buf);
  1383. return ret;
  1384. }
  1385. #endif
  1386. template <typename T>
  1387. struct no_init {
  1388. T value;
  1389. no_init() { /* do nothing */ }
  1390. };
  1391. struct llama_file {
  1392. #if defined(_WIN32)
  1393. // use FILE * so we don't have to re-open the file to mmap
  1394. FILE * fp;
  1395. HANDLE fp_win32;
  1396. size_t size;
  1397. private:
  1398. std::string GetErrorMessageWin32(DWORD error_code) const {
  1399. std::string ret;
  1400. LPSTR lpMsgBuf = NULL;
  1401. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1402. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1403. if (!bufLen) {
  1404. ret = format("Win32 error code: %s", error_code);
  1405. } else {
  1406. ret = lpMsgBuf;
  1407. LocalFree(lpMsgBuf);
  1408. }
  1409. return ret;
  1410. }
  1411. public:
  1412. llama_file(const char * fname, const char * mode) {
  1413. fp = ggml_fopen(fname, mode);
  1414. if (fp == NULL) {
  1415. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1416. }
  1417. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1418. seek(0, SEEK_END);
  1419. size = tell();
  1420. seek(0, SEEK_SET);
  1421. }
  1422. size_t tell() const {
  1423. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1424. LARGE_INTEGER li;
  1425. li.QuadPart = 0;
  1426. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1427. if (!ret) {
  1428. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1429. }
  1430. return li.QuadPart;
  1431. }
  1432. void seek(size_t offset, int whence) const {
  1433. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1434. // Still, keep static asserts to avoid failures in the future.
  1435. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1436. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1437. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1438. LARGE_INTEGER li;
  1439. li.QuadPart = offset;
  1440. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1441. if (!ret) {
  1442. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1443. }
  1444. }
  1445. void read_raw(void * ptr, size_t len) const {
  1446. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1447. // use the Win32 API to do file io instead of the C/C++ library functions.
  1448. // There are conditions under which ReadFile cannot read chunks >64MB.
  1449. // Thus split the operation into smaller chunks if len exceeds this limit.
  1450. size_t bytes_read = 0;
  1451. while (bytes_read < len) {
  1452. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1453. DWORD chunk_read = 0;
  1454. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1455. if (!result) {
  1456. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1457. }
  1458. if (chunk_read < chunk_size || chunk_read == 0) {
  1459. throw std::runtime_error("unexpectedly reached end of file");
  1460. }
  1461. bytes_read += chunk_read;
  1462. } ;
  1463. }
  1464. uint32_t read_u32() const {
  1465. uint32_t val;
  1466. read_raw(&val, sizeof(val));
  1467. return val;
  1468. }
  1469. void write_raw(const void * ptr, size_t len) const {
  1470. // There are conditions under which WriteFile cannot write chunks >64MB.
  1471. // Thus split the operation into smaller chunks if len exceeds this limit.
  1472. size_t bytes_written = 0;
  1473. while (bytes_written < len) {
  1474. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1475. DWORD chunk_written = 0;
  1476. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1477. if (!result) {
  1478. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1479. }
  1480. if (chunk_written < chunk_size || chunk_written == 0) {
  1481. throw std::runtime_error("unexpectedly failed to write bytes");
  1482. }
  1483. bytes_written += chunk_written;
  1484. }
  1485. }
  1486. void write_u32(std::uint32_t val) const {
  1487. write_raw(&val, sizeof(val));
  1488. }
  1489. ~llama_file() {
  1490. if (fp) {
  1491. std::fclose(fp);
  1492. }
  1493. }
  1494. #else
  1495. // use FILE * so we don't have to re-open the file to mmap
  1496. FILE * fp;
  1497. size_t size;
  1498. llama_file(const char * fname, const char * mode) {
  1499. fp = ggml_fopen(fname, mode);
  1500. if (fp == NULL) {
  1501. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1502. }
  1503. seek(0, SEEK_END);
  1504. size = tell();
  1505. seek(0, SEEK_SET);
  1506. }
  1507. size_t tell() const {
  1508. #ifdef _WIN32
  1509. __int64 ret = _ftelli64(fp);
  1510. #else
  1511. long ret = std::ftell(fp);
  1512. #endif
  1513. if (ret == -1) {
  1514. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1515. }
  1516. return (size_t) ret;
  1517. }
  1518. void seek(size_t offset, int whence) const {
  1519. #ifdef _WIN32
  1520. int ret = _fseeki64(fp, (__int64) offset, whence);
  1521. #else
  1522. int ret = std::fseek(fp, (long) offset, whence);
  1523. #endif
  1524. if (ret != 0) {
  1525. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1526. }
  1527. }
  1528. void read_raw(void * ptr, size_t len) const {
  1529. if (len == 0) {
  1530. return;
  1531. }
  1532. errno = 0;
  1533. std::size_t ret = std::fread(ptr, len, 1, fp);
  1534. if (ferror(fp)) {
  1535. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1536. }
  1537. if (ret != 1) {
  1538. throw std::runtime_error("unexpectedly reached end of file");
  1539. }
  1540. }
  1541. uint32_t read_u32() const {
  1542. uint32_t ret;
  1543. read_raw(&ret, sizeof(ret));
  1544. return ret;
  1545. }
  1546. void write_raw(const void * ptr, size_t len) const {
  1547. if (len == 0) {
  1548. return;
  1549. }
  1550. errno = 0;
  1551. size_t ret = std::fwrite(ptr, len, 1, fp);
  1552. if (ret != 1) {
  1553. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1554. }
  1555. }
  1556. void write_u32(std::uint32_t val) const {
  1557. write_raw(&val, sizeof(val));
  1558. }
  1559. ~llama_file() {
  1560. if (fp) {
  1561. std::fclose(fp);
  1562. }
  1563. }
  1564. #endif
  1565. };
  1566. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1567. struct llama_mmap {
  1568. void * addr;
  1569. size_t size;
  1570. llama_mmap(const llama_mmap &) = delete;
  1571. #ifdef _POSIX_MAPPED_FILES
  1572. static constexpr bool SUPPORTED = true;
  1573. // list of mapped fragments (first_offset, last_offset)
  1574. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1575. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1576. size = file->size;
  1577. int fd = fileno(file->fp);
  1578. int flags = MAP_SHARED;
  1579. // prefetch/readahead impairs performance on NUMA systems
  1580. if (numa) { prefetch = 0; }
  1581. #ifdef __linux__
  1582. // advise the kernel to read the file sequentially (increases readahead)
  1583. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1584. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1585. strerror(errno));
  1586. }
  1587. if (prefetch) { flags |= MAP_POPULATE; }
  1588. #endif
  1589. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1590. if (addr == MAP_FAILED) { // NOLINT
  1591. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1592. }
  1593. if (prefetch > 0) {
  1594. // advise the kernel to preload the mapped memory
  1595. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1596. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1597. strerror(errno));
  1598. }
  1599. }
  1600. if (numa) {
  1601. // advise the kernel not to use readahead
  1602. // (because the next page might not belong on the same node)
  1603. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1604. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1605. strerror(errno));
  1606. }
  1607. }
  1608. // initialize list of mapped_fragments
  1609. mapped_fragments.emplace_back(0, file->size);
  1610. }
  1611. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1612. // align first to the next page
  1613. size_t offset_in_page = *first & (page_size - 1);
  1614. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1615. *first += offset_to_page;
  1616. // align last to the previous page
  1617. *last = *last & ~(page_size - 1);
  1618. if (*last <= *first) {
  1619. *last = *first;
  1620. }
  1621. }
  1622. // partially unmap the file in the range [first, last)
  1623. void unmap_fragment(size_t first, size_t last) {
  1624. // note: this function must not be called multiple times with overlapping ranges
  1625. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1626. int page_size = sysconf(_SC_PAGESIZE);
  1627. align_range(&first, &last, page_size);
  1628. size_t len = last - first;
  1629. if (len == 0) {
  1630. return;
  1631. }
  1632. GGML_ASSERT(first % page_size == 0);
  1633. GGML_ASSERT(last % page_size == 0);
  1634. GGML_ASSERT(last > first);
  1635. void * next_page_start = (uint8_t *) addr + first;
  1636. // unmap the range
  1637. if (munmap(next_page_start, len)) {
  1638. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1639. }
  1640. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1641. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1642. for (const auto & frag : mapped_fragments) {
  1643. if (frag.first < first && frag.second > last) {
  1644. // the range is in the middle of the fragment, split it
  1645. new_mapped_fragments.emplace_back(frag.first, first);
  1646. new_mapped_fragments.emplace_back(last, frag.second);
  1647. } else if (frag.first < first && frag.second > first) {
  1648. // the range starts in the middle of the fragment
  1649. new_mapped_fragments.emplace_back(frag.first, first);
  1650. } else if (frag.first < last && frag.second > last) {
  1651. // the range ends in the middle of the fragment
  1652. new_mapped_fragments.emplace_back(last, frag.second);
  1653. } else if (frag.first >= first && frag.second <= last) {
  1654. // the range covers the entire fragment
  1655. } else {
  1656. // the range is outside the fragment
  1657. new_mapped_fragments.push_back(frag);
  1658. }
  1659. }
  1660. mapped_fragments = std::move(new_mapped_fragments);
  1661. }
  1662. ~llama_mmap() {
  1663. for (const auto & frag : mapped_fragments) {
  1664. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1665. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1666. }
  1667. }
  1668. }
  1669. #elif defined(_WIN32)
  1670. static constexpr bool SUPPORTED = true;
  1671. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1672. GGML_UNUSED(numa);
  1673. size = file->size;
  1674. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1675. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1676. if (hMapping == NULL) {
  1677. DWORD error = GetLastError();
  1678. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1679. }
  1680. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1681. DWORD error = GetLastError();
  1682. CloseHandle(hMapping);
  1683. if (addr == NULL) {
  1684. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1685. }
  1686. if (prefetch > 0) {
  1687. #if _WIN32_WINNT >= 0x602
  1688. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1689. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1690. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1691. // may fail on pre-Windows 8 systems
  1692. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1693. if (pPrefetchVirtualMemory) {
  1694. // advise the kernel to preload the mapped memory
  1695. WIN32_MEMORY_RANGE_ENTRY range;
  1696. range.VirtualAddress = addr;
  1697. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1698. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1699. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1700. llama_format_win_err(GetLastError()).c_str());
  1701. }
  1702. }
  1703. #else
  1704. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1705. #endif
  1706. }
  1707. }
  1708. void unmap_fragment(size_t first, size_t last) {
  1709. // not supported
  1710. GGML_UNUSED(first);
  1711. GGML_UNUSED(last);
  1712. }
  1713. ~llama_mmap() {
  1714. if (!UnmapViewOfFile(addr)) {
  1715. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1716. llama_format_win_err(GetLastError()).c_str());
  1717. }
  1718. }
  1719. #else
  1720. static constexpr bool SUPPORTED = false;
  1721. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1722. GGML_UNUSED(file);
  1723. GGML_UNUSED(prefetch);
  1724. GGML_UNUSED(numa);
  1725. throw std::runtime_error("mmap not supported");
  1726. }
  1727. void unmap_fragment(size_t first, size_t last) {
  1728. GGML_UNUSED(first);
  1729. GGML_UNUSED(last);
  1730. throw std::runtime_error("mmap not supported");
  1731. }
  1732. #endif
  1733. };
  1734. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1735. // Represents some region of memory being locked using mlock or VirtualLock;
  1736. // will automatically unlock on destruction.
  1737. struct llama_mlock {
  1738. void * addr = NULL;
  1739. size_t size = 0;
  1740. bool failed_already = false;
  1741. llama_mlock() {}
  1742. llama_mlock(const llama_mlock &) = delete;
  1743. ~llama_mlock() {
  1744. if (size) {
  1745. raw_unlock(addr, size);
  1746. }
  1747. }
  1748. void init(void * ptr) {
  1749. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1750. addr = ptr;
  1751. }
  1752. void grow_to(size_t target_size) {
  1753. GGML_ASSERT(addr);
  1754. if (failed_already) {
  1755. return;
  1756. }
  1757. size_t granularity = lock_granularity();
  1758. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1759. if (target_size > size) {
  1760. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1761. size = target_size;
  1762. } else {
  1763. failed_already = true;
  1764. }
  1765. }
  1766. }
  1767. #ifdef _POSIX_MEMLOCK_RANGE
  1768. static constexpr bool SUPPORTED = true;
  1769. static size_t lock_granularity() {
  1770. return (size_t) sysconf(_SC_PAGESIZE);
  1771. }
  1772. #ifdef __APPLE__
  1773. #define MLOCK_SUGGESTION \
  1774. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1775. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1776. #else
  1777. #define MLOCK_SUGGESTION \
  1778. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1779. #endif
  1780. bool raw_lock(const void * addr, size_t size) const {
  1781. if (!mlock(addr, size)) {
  1782. return true;
  1783. }
  1784. char* errmsg = std::strerror(errno);
  1785. bool suggest = (errno == ENOMEM);
  1786. // Check if the resource limit is fine after all
  1787. struct rlimit lock_limit;
  1788. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1789. suggest = false;
  1790. }
  1791. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1792. suggest = false;
  1793. }
  1794. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1795. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1796. return false;
  1797. }
  1798. #undef MLOCK_SUGGESTION
  1799. static void raw_unlock(void * addr, size_t size) {
  1800. if (munlock(addr, size)) {
  1801. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1802. }
  1803. }
  1804. #elif defined(_WIN32)
  1805. static constexpr bool SUPPORTED = true;
  1806. static size_t lock_granularity() {
  1807. SYSTEM_INFO si;
  1808. GetSystemInfo(&si);
  1809. return (size_t) si.dwPageSize;
  1810. }
  1811. bool raw_lock(void * ptr, size_t len) const {
  1812. for (int tries = 1; ; tries++) {
  1813. if (VirtualLock(ptr, len)) {
  1814. return true;
  1815. }
  1816. if (tries == 2) {
  1817. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1818. len, size, llama_format_win_err(GetLastError()).c_str());
  1819. return false;
  1820. }
  1821. // It failed but this was only the first try; increase the working
  1822. // set size and try again.
  1823. SIZE_T min_ws_size, max_ws_size;
  1824. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1825. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1826. llama_format_win_err(GetLastError()).c_str());
  1827. return false;
  1828. }
  1829. // Per MSDN: "The maximum number of pages that a process can lock
  1830. // is equal to the number of pages in its minimum working set minus
  1831. // a small overhead."
  1832. // Hopefully a megabyte is enough overhead:
  1833. size_t increment = len + 1048576;
  1834. // The minimum must be <= the maximum, so we need to increase both:
  1835. min_ws_size += increment;
  1836. max_ws_size += increment;
  1837. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1838. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1839. llama_format_win_err(GetLastError()).c_str());
  1840. return false;
  1841. }
  1842. }
  1843. }
  1844. static void raw_unlock(void * ptr, size_t len) {
  1845. if (!VirtualUnlock(ptr, len)) {
  1846. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1847. llama_format_win_err(GetLastError()).c_str());
  1848. }
  1849. }
  1850. #else
  1851. static constexpr bool SUPPORTED = false;
  1852. static size_t lock_granularity() {
  1853. return (size_t) 65536;
  1854. }
  1855. bool raw_lock(const void * addr, size_t len) const {
  1856. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1857. return false;
  1858. }
  1859. static void raw_unlock(const void * addr, size_t len) {}
  1860. #endif
  1861. };
  1862. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1863. // NOTE: avoid ever using this except for building the token_to_piece caches
  1864. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  1865. std::string piece;
  1866. piece.resize(piece.capacity()); // using string internal cache
  1867. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1868. if (n_chars < 0) {
  1869. piece.resize(-n_chars);
  1870. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1871. GGML_ASSERT(check == -n_chars);
  1872. }
  1873. else {
  1874. piece.resize(n_chars);
  1875. }
  1876. return piece;
  1877. }
  1878. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1879. ggml_backend_buffer_type_t buft = nullptr;
  1880. #if defined(GGML_USE_CUDA)
  1881. // host buffers should only be used when data is expected to be copied to/from the GPU
  1882. if (host_buffer) {
  1883. buft = ggml_backend_cuda_host_buffer_type();
  1884. }
  1885. #elif defined(GGML_USE_SYCL)
  1886. if (host_buffer) {
  1887. buft = ggml_backend_sycl_host_buffer_type();
  1888. }
  1889. #elif defined(GGML_USE_CPU_HBM)
  1890. buft = ggml_backend_cpu_hbm_buffer_type();
  1891. #elif defined(GGML_USE_VULKAN)
  1892. if (host_buffer) {
  1893. buft = ggml_backend_vk_host_buffer_type();
  1894. }
  1895. #endif
  1896. if (buft == nullptr) {
  1897. buft = ggml_backend_cpu_buffer_type();
  1898. }
  1899. return buft;
  1900. GGML_UNUSED(host_buffer);
  1901. }
  1902. //
  1903. // globals
  1904. //
  1905. struct llama_state {
  1906. llama_state() {
  1907. #ifdef GGML_USE_METAL
  1908. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1909. #elif defined(GGML_USE_CUDA)
  1910. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1911. #elif defined(GGML_USE_CANN)
  1912. ggml_backend_cann_log_set_callback(log_callback, log_callback_user_data);
  1913. #endif
  1914. }
  1915. // We save the log callback globally
  1916. ggml_log_callback log_callback = llama_log_callback_default;
  1917. void * log_callback_user_data = nullptr;
  1918. };
  1919. static llama_state g_state;
  1920. // available llama models
  1921. enum e_model {
  1922. MODEL_UNKNOWN,
  1923. MODEL_14M,
  1924. MODEL_17M,
  1925. MODEL_22M,
  1926. MODEL_33M,
  1927. MODEL_60M,
  1928. MODEL_70M,
  1929. MODEL_80M,
  1930. MODEL_109M,
  1931. MODEL_137M,
  1932. MODEL_160M,
  1933. MODEL_220M,
  1934. MODEL_250M,
  1935. MODEL_270M,
  1936. MODEL_335M,
  1937. MODEL_410M,
  1938. MODEL_450M,
  1939. MODEL_770M,
  1940. MODEL_780M,
  1941. MODEL_0_5B,
  1942. MODEL_1B,
  1943. MODEL_1_3B,
  1944. MODEL_1_4B,
  1945. MODEL_2B,
  1946. MODEL_2_8B,
  1947. MODEL_3B,
  1948. MODEL_4B,
  1949. MODEL_6B,
  1950. MODEL_6_9B,
  1951. MODEL_7B,
  1952. MODEL_8B,
  1953. MODEL_9B,
  1954. MODEL_11B,
  1955. MODEL_12B,
  1956. MODEL_13B,
  1957. MODEL_14B,
  1958. MODEL_15B,
  1959. MODEL_16B,
  1960. MODEL_20B,
  1961. MODEL_30B,
  1962. MODEL_34B,
  1963. MODEL_35B,
  1964. MODEL_40B,
  1965. MODEL_65B,
  1966. MODEL_70B,
  1967. MODEL_236B,
  1968. MODEL_314B,
  1969. MODEL_SMALL,
  1970. MODEL_MEDIUM,
  1971. MODEL_LARGE,
  1972. MODEL_XL,
  1973. MODEL_A2_7B,
  1974. MODEL_8x7B,
  1975. MODEL_8x22B,
  1976. MODEL_16x12B,
  1977. MODEL_10B_128x3_66B,
  1978. MODEL_57B_A14B,
  1979. MODEL_27B,
  1980. };
  1981. static const size_t kiB = 1024;
  1982. static const size_t MiB = 1024*kiB;
  1983. static const size_t GiB = 1024*MiB;
  1984. struct llama_hparams {
  1985. bool vocab_only;
  1986. bool rope_finetuned;
  1987. bool use_par_res;
  1988. uint32_t n_vocab;
  1989. uint32_t n_ctx_train; // context size the model was trained on
  1990. uint32_t n_embd;
  1991. uint32_t n_layer;
  1992. uint32_t n_rot;
  1993. uint32_t n_swa = 0; // sliding window attention (SWA)
  1994. 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
  1995. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1996. uint32_t n_expert = 0;
  1997. uint32_t n_expert_used = 0;
  1998. uint32_t n_vocab_type = 0; // for BERT-style token types
  1999. uint32_t n_rel_attn_bkts = 0;
  2000. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2001. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2002. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2003. uint32_t n_layer_dense_lead = 0;
  2004. uint32_t n_lora_q = 0;
  2005. uint32_t n_lora_kv = 0;
  2006. uint32_t n_ff_exp = 0;
  2007. uint32_t n_ff_shexp = 0;
  2008. uint32_t n_expert_shared = 0;
  2009. float expert_weights_scale = 0.0;
  2010. float f_norm_eps;
  2011. float f_norm_rms_eps;
  2012. float f_attn_logit_softcapping = 50.0f;
  2013. float f_final_logit_softcapping = 30.0f;
  2014. float rope_attn_factor = 1.0f;
  2015. float rope_freq_base_train;
  2016. float rope_freq_scale_train;
  2017. uint32_t n_ctx_orig_yarn;
  2018. float rope_yarn_log_mul;
  2019. // for State Space Models
  2020. uint32_t ssm_d_conv = 0;
  2021. uint32_t ssm_d_inner = 0;
  2022. uint32_t ssm_d_state = 0;
  2023. uint32_t ssm_dt_rank = 0;
  2024. float f_clamp_kqv = 0.0f;
  2025. float f_max_alibi_bias = 0.0f;
  2026. float f_logit_scale = 0.0f;
  2027. bool causal_attn = true;
  2028. bool use_alibi = false;
  2029. bool attn_soft_cap = false;
  2030. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2031. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2032. llama_token dec_start_token_id = -1;
  2033. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2034. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2035. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2036. bool operator!=(const llama_hparams & other) const {
  2037. if (this->vocab_only != other.vocab_only) return true;
  2038. if (this->n_vocab != other.n_vocab) return true;
  2039. if (this->n_ctx_train != other.n_ctx_train) return true;
  2040. if (this->n_embd != other.n_embd) return true;
  2041. if (this->n_layer != other.n_layer) return true;
  2042. if (this->n_rot != other.n_rot) return true;
  2043. if (this->n_swa != other.n_swa) return true;
  2044. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2045. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2046. if (this->n_expert != other.n_expert) return true;
  2047. if (this->n_expert_used != other.n_expert_used) return true;
  2048. if (this->n_head_arr != other.n_head_arr) return true;
  2049. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2050. if (this->n_ff_arr != other.n_ff_arr) return true;
  2051. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2052. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2053. if (this->n_lora_q != other.n_lora_q) return true;
  2054. if (this->n_lora_kv != other.n_lora_kv) return true;
  2055. if (this->n_ff_exp != other.n_ff_exp) return true;
  2056. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2057. if (this->n_expert_shared != other.n_expert_shared) return true;
  2058. if (this->rope_finetuned != other.rope_finetuned) return true;
  2059. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2060. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2061. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2062. if (this->ssm_d_state != other.ssm_d_state) return true;
  2063. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2064. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2065. const float EPSILON = 1e-9f;
  2066. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2067. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2068. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2069. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2070. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2071. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2072. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2073. return false;
  2074. }
  2075. uint32_t n_head(uint32_t il = 0) const {
  2076. if (il < n_layer) {
  2077. return n_head_arr[il];
  2078. }
  2079. GGML_ABORT("fatal error");
  2080. }
  2081. uint32_t n_head_kv(uint32_t il = 0) const {
  2082. if (il < n_layer) {
  2083. return n_head_kv_arr[il];
  2084. }
  2085. GGML_ABORT("fatal error");
  2086. }
  2087. uint32_t n_ff(uint32_t il = 0) const {
  2088. if (il < n_layer) {
  2089. return n_ff_arr[il];
  2090. }
  2091. GGML_ABORT("fatal error");
  2092. }
  2093. uint32_t n_gqa(uint32_t il = 0) const {
  2094. const uint32_t n_head = this->n_head(il);
  2095. const uint32_t n_head_kv = this->n_head_kv(il);
  2096. if (n_head_kv == 0) {
  2097. return 0;
  2098. }
  2099. return n_head/n_head_kv;
  2100. }
  2101. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2102. const uint32_t n_head_kv = this->n_head_kv(il);
  2103. return n_embd_head_k * n_head_kv;
  2104. }
  2105. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2106. const uint32_t n_head_kv = this->n_head_kv(il);
  2107. return n_embd_head_v * n_head_kv;
  2108. }
  2109. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2110. // corresponds to Mamba's conv_states size
  2111. // TODO: maybe support other convolution strides than 1
  2112. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2113. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2114. }
  2115. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2116. // corresponds to Mamba's ssm_states size
  2117. return ssm_d_state * ssm_d_inner;
  2118. }
  2119. };
  2120. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2121. struct llama_cparams {
  2122. uint32_t n_ctx; // context size used during inference
  2123. uint32_t n_batch;
  2124. uint32_t n_ubatch;
  2125. uint32_t n_seq_max;
  2126. uint32_t n_threads; // number of threads to use for generation
  2127. uint32_t n_threads_batch; // number of threads to use for batch processing
  2128. float rope_freq_base;
  2129. float rope_freq_scale;
  2130. uint32_t n_ctx_orig_yarn;
  2131. // These hyperparameters are not exposed in GGUF, because all
  2132. // existing YaRN models use the same values for them.
  2133. float yarn_ext_factor;
  2134. float yarn_attn_factor;
  2135. float yarn_beta_fast;
  2136. float yarn_beta_slow;
  2137. float defrag_thold;
  2138. bool embeddings;
  2139. bool causal_attn;
  2140. bool offload_kqv;
  2141. bool flash_attn;
  2142. enum llama_pooling_type pooling_type;
  2143. ggml_backend_sched_eval_callback cb_eval;
  2144. void * cb_eval_user_data;
  2145. };
  2146. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2147. struct llama_layer {
  2148. // normalization
  2149. struct ggml_tensor * attn_norm;
  2150. struct ggml_tensor * attn_norm_b;
  2151. struct ggml_tensor * attn_norm_2;
  2152. struct ggml_tensor * attn_norm_2_b;
  2153. struct ggml_tensor * attn_q_norm;
  2154. struct ggml_tensor * attn_q_norm_b;
  2155. struct ggml_tensor * attn_k_norm;
  2156. struct ggml_tensor * attn_k_norm_b;
  2157. struct ggml_tensor * attn_out_norm;
  2158. struct ggml_tensor * attn_out_norm_b;
  2159. struct ggml_tensor * attn_q_a_norm;
  2160. struct ggml_tensor * attn_kv_a_norm;
  2161. struct ggml_tensor * attn_sub_norm;
  2162. struct ggml_tensor * attn_post_norm;
  2163. struct ggml_tensor * ffn_sub_norm;
  2164. struct ggml_tensor * attn_norm_cross;
  2165. struct ggml_tensor * attn_norm_enc;
  2166. // attention
  2167. struct ggml_tensor * wq;
  2168. struct ggml_tensor * wk;
  2169. struct ggml_tensor * wv;
  2170. struct ggml_tensor * wo;
  2171. struct ggml_tensor * wqkv;
  2172. struct ggml_tensor * wq_a;
  2173. struct ggml_tensor * wq_b;
  2174. struct ggml_tensor * wkv_a_mqa;
  2175. struct ggml_tensor * wkv_b;
  2176. struct ggml_tensor * wq_cross;
  2177. struct ggml_tensor * wk_cross;
  2178. struct ggml_tensor * wv_cross;
  2179. struct ggml_tensor * wo_cross;
  2180. struct ggml_tensor * wq_enc;
  2181. struct ggml_tensor * wk_enc;
  2182. struct ggml_tensor * wv_enc;
  2183. struct ggml_tensor * wo_enc;
  2184. // attention bias
  2185. struct ggml_tensor * bq;
  2186. struct ggml_tensor * bk;
  2187. struct ggml_tensor * bv;
  2188. struct ggml_tensor * bo;
  2189. struct ggml_tensor * bqkv;
  2190. // relative position bias
  2191. struct ggml_tensor * attn_rel_b;
  2192. struct ggml_tensor * attn_rel_b_enc;
  2193. struct ggml_tensor * attn_rel_b_cross;
  2194. // normalization
  2195. struct ggml_tensor * ffn_norm;
  2196. struct ggml_tensor * ffn_norm_b;
  2197. struct ggml_tensor * ffn_post_norm;
  2198. struct ggml_tensor * layer_out_norm;
  2199. struct ggml_tensor * layer_out_norm_b;
  2200. struct ggml_tensor * ffn_norm_exps;
  2201. struct ggml_tensor * ffn_norm_enc;
  2202. // ff
  2203. struct ggml_tensor * ffn_gate; // w1
  2204. struct ggml_tensor * ffn_down; // w2
  2205. struct ggml_tensor * ffn_up; // w3
  2206. struct ggml_tensor * ffn_gate_enc;
  2207. struct ggml_tensor * ffn_down_enc;
  2208. struct ggml_tensor * ffn_up_enc;
  2209. // ff MoE
  2210. struct ggml_tensor * ffn_gate_inp;
  2211. struct ggml_tensor * ffn_gate_exps;
  2212. struct ggml_tensor * ffn_down_exps;
  2213. struct ggml_tensor * ffn_up_exps ;
  2214. // ff shared expert (shexp)
  2215. struct ggml_tensor * ffn_gate_inp_shexp;
  2216. struct ggml_tensor * ffn_gate_shexp;
  2217. struct ggml_tensor * ffn_down_shexp;
  2218. struct ggml_tensor * ffn_up_shexp;
  2219. // ff bias
  2220. struct ggml_tensor * ffn_gate_b = nullptr;
  2221. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2222. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2223. struct ggml_tensor * ffn_act;
  2224. // mamba proj
  2225. struct ggml_tensor * ssm_in;
  2226. struct ggml_tensor * ssm_x;
  2227. struct ggml_tensor * ssm_dt;
  2228. struct ggml_tensor * ssm_out;
  2229. // mamba
  2230. struct ggml_tensor * ssm_conv1d;
  2231. struct ggml_tensor * ssm_a;
  2232. struct ggml_tensor * ssm_d;
  2233. // mamba bias
  2234. struct ggml_tensor * ssm_conv1d_b;
  2235. struct ggml_tensor * ssm_dt_b;
  2236. // long rope factors
  2237. struct ggml_tensor * rope_long = nullptr;
  2238. struct ggml_tensor * rope_short = nullptr;
  2239. struct ggml_tensor * rope_freqs = nullptr;
  2240. // bitnet scale
  2241. struct ggml_tensor * wq_scale;
  2242. struct ggml_tensor * wk_scale;
  2243. struct ggml_tensor * wv_scale;
  2244. struct ggml_tensor * wo_scale;
  2245. struct ggml_tensor * ffn_gate_scale;
  2246. struct ggml_tensor * ffn_up_scale;
  2247. struct ggml_tensor * ffn_down_scale;
  2248. };
  2249. struct llama_kv_cell {
  2250. llama_pos pos = -1;
  2251. llama_pos delta = 0;
  2252. int32_t src = 0; // used by recurrent state models to copy states
  2253. std::set<llama_seq_id> seq_id;
  2254. bool has_seq_id(const llama_seq_id & id) const {
  2255. return seq_id.find(id) != seq_id.end();
  2256. }
  2257. bool is_empty() const {
  2258. return seq_id.empty();
  2259. }
  2260. bool is_same_seq(const llama_kv_cell & other) const {
  2261. return seq_id == other.seq_id;
  2262. }
  2263. };
  2264. // ring-buffer of cached KV data
  2265. struct llama_kv_cache {
  2266. bool has_shift = false;
  2267. bool do_defrag = false;
  2268. bool do_copy = false;
  2269. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2270. bool v_trans = true; // the value tensor is transposed
  2271. // Note: The value of head isn't only used to optimize searching
  2272. // for a free KV slot. llama_decode_internal also uses it, so it
  2273. // cannot be freely changed after a slot has been allocated.
  2274. uint32_t head = 0;
  2275. uint32_t size = 0;
  2276. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2277. // computed before each graph build
  2278. uint32_t n = 0;
  2279. ggml_type type_k = GGML_TYPE_F16;
  2280. ggml_type type_v = GGML_TYPE_F16;
  2281. std::vector<llama_kv_cell> cells;
  2282. std::vector<struct ggml_tensor *> k_l; // per layer
  2283. std::vector<struct ggml_tensor *> v_l;
  2284. std::vector<struct ggml_context *> ctxs;
  2285. std::vector<ggml_backend_buffer_t> bufs;
  2286. size_t total_size() const {
  2287. size_t size = 0;
  2288. for (ggml_backend_buffer_t buf : bufs) {
  2289. size += ggml_backend_buffer_get_size(buf);
  2290. }
  2291. return size;
  2292. }
  2293. ~llama_kv_cache() {
  2294. for (struct ggml_context * ctx : ctxs) {
  2295. ggml_free(ctx);
  2296. }
  2297. for (ggml_backend_buffer_t buf : bufs) {
  2298. ggml_backend_buffer_free(buf);
  2299. }
  2300. }
  2301. };
  2302. struct llama_control_vector {
  2303. std::vector<struct ggml_tensor *> tensors; // per layer
  2304. std::vector<struct ggml_context *> ctxs;
  2305. std::vector<ggml_backend_buffer_t> bufs;
  2306. int32_t layer_start = -1;
  2307. int32_t layer_end = -1;
  2308. struct ggml_tensor * tensor_for(int il) const {
  2309. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2310. return nullptr;
  2311. }
  2312. return tensors[il];
  2313. }
  2314. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2315. ggml_tensor * layer_dir = tensor_for(il);
  2316. if (layer_dir != nullptr) {
  2317. cur = ggml_add(ctx, cur, layer_dir);
  2318. }
  2319. return cur;
  2320. }
  2321. ~llama_control_vector() {
  2322. for (struct ggml_context * ctx : ctxs) {
  2323. ggml_free(ctx);
  2324. }
  2325. for (ggml_backend_buffer_t buf : bufs) {
  2326. ggml_backend_buffer_free(buf);
  2327. }
  2328. }
  2329. };
  2330. struct llama_model {
  2331. e_model type = MODEL_UNKNOWN;
  2332. llm_arch arch = LLM_ARCH_UNKNOWN;
  2333. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2334. std::string name = "n/a";
  2335. llama_hparams hparams = {};
  2336. llama_vocab vocab;
  2337. struct ggml_tensor * tok_embd;
  2338. struct ggml_tensor * type_embd;
  2339. struct ggml_tensor * pos_embd;
  2340. struct ggml_tensor * tok_norm;
  2341. struct ggml_tensor * tok_norm_b;
  2342. struct ggml_tensor * output_norm;
  2343. struct ggml_tensor * output_norm_b;
  2344. struct ggml_tensor * output;
  2345. struct ggml_tensor * output_b;
  2346. struct ggml_tensor * output_norm_enc;
  2347. std::vector<llama_layer> layers;
  2348. llama_split_mode split_mode;
  2349. int main_gpu;
  2350. int n_gpu_layers;
  2351. std::vector<std::string> rpc_servers;
  2352. // gguf metadata
  2353. std::unordered_map<std::string, std::string> gguf_kv;
  2354. // layer -> buffer type mapping
  2355. struct layer_buft {
  2356. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2357. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2358. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2359. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2360. ggml_backend_buffer_type_t buft; // everything else
  2361. };
  2362. layer_buft buft_input;
  2363. layer_buft buft_output;
  2364. std::vector<layer_buft> buft_layer;
  2365. // contexts where the model tensors metadata is stored
  2366. std::vector<struct ggml_context *> ctxs;
  2367. // the model memory buffers for the tensor data
  2368. std::vector<ggml_backend_buffer_t> bufs;
  2369. // model memory mapped files
  2370. llama_mmaps mappings;
  2371. // objects representing data potentially being locked in memory
  2372. llama_mlocks mlock_bufs;
  2373. llama_mlocks mlock_mmaps;
  2374. // for quantize-stats only
  2375. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2376. int64_t t_load_us = 0;
  2377. int64_t t_start_us = 0;
  2378. // keep track of loaded lora adapters
  2379. std::set<struct llama_lora_adapter *> lora_adapters;
  2380. ~llama_model() {
  2381. for (struct ggml_context * ctx : ctxs) {
  2382. ggml_free(ctx);
  2383. }
  2384. for (ggml_backend_buffer_t buf : bufs) {
  2385. #ifdef GGML_USE_CUDA
  2386. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2387. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2388. }
  2389. #endif
  2390. ggml_backend_buffer_free(buf);
  2391. }
  2392. while (!lora_adapters.empty()) {
  2393. llama_lora_adapter_free(*lora_adapters.begin());
  2394. }
  2395. }
  2396. };
  2397. struct llama_context {
  2398. llama_context(const llama_model & model)
  2399. : model(model)
  2400. , sampling(llama_n_vocab(&model))
  2401. , t_start_us(model.t_start_us)
  2402. , t_load_us(model.t_load_us) {}
  2403. ~llama_context() {
  2404. ggml_backend_sched_free(sched);
  2405. for (ggml_backend_t backend : backends) {
  2406. ggml_backend_free(backend);
  2407. }
  2408. ggml_backend_buffer_free(buf_output);
  2409. }
  2410. const struct llama_model & model;
  2411. struct llama_cparams cparams;
  2412. struct llama_sampling sampling;
  2413. struct llama_kv_cache kv_self;
  2414. struct llama_control_vector cvec;
  2415. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  2416. std::vector<ggml_backend_t> backends;
  2417. #ifdef GGML_USE_METAL
  2418. ggml_backend_t backend_metal = nullptr;
  2419. #endif
  2420. #ifdef GGML_USE_BLAS
  2421. ggml_backend_t backend_blas = nullptr;
  2422. #endif
  2423. ggml_backend_t backend_cpu = nullptr;
  2424. bool has_evaluated_once = false;
  2425. int64_t t_start_us;
  2426. int64_t t_load_us;
  2427. int64_t t_p_eval_us = 0;
  2428. int64_t t_eval_us = 0;
  2429. int64_t t_compute_start_us = 0;
  2430. int64_t n_queued_tokens = 0;
  2431. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  2432. int32_t n_eval = 0; // number of eval calls
  2433. // host buffer for the model output (logits and embeddings)
  2434. ggml_backend_buffer_t buf_output = nullptr;
  2435. // decode output (2-dimensional array: [n_outputs][n_vocab])
  2436. size_t logits_size = 0; // capacity (of floats) for logits
  2437. float * logits = nullptr;
  2438. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  2439. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  2440. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  2441. bool logits_all = false;
  2442. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  2443. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  2444. size_t embd_size = 0; // capacity (of floats) for embeddings
  2445. float * embd = nullptr;
  2446. // sequence embeddings output (map of [n_embd] vectors)
  2447. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2448. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2449. // whether we are computing encoder output or decoder output
  2450. bool is_encoding = false;
  2451. // output of the encoder part of the encoder-decoder models
  2452. std::vector<float> embd_enc;
  2453. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  2454. // memory buffers used to evaluate the model
  2455. std::vector<uint8_t> buf_compute_meta;
  2456. ggml_backend_sched_t sched = nullptr;
  2457. ggml_abort_callback abort_callback = nullptr;
  2458. void * abort_callback_data = nullptr;
  2459. // input tensors
  2460. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2461. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2462. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2463. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2464. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2465. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  2466. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2467. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2468. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2469. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2470. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2471. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2472. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  2473. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  2474. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  2475. };
  2476. struct llama_lora_weight {
  2477. struct ggml_tensor * a = nullptr;
  2478. struct ggml_tensor * b = nullptr;
  2479. llama_lora_weight() = default;
  2480. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  2481. };
  2482. struct llama_lora_adapter {
  2483. struct llama_model * base_model;
  2484. // map tensor name to lora_a_b
  2485. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  2486. std::vector<struct ggml_context *> ctxs;
  2487. std::vector<ggml_backend_buffer_t> bufs;
  2488. float alpha;
  2489. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  2490. base_model->lora_adapters.insert(this);
  2491. }
  2492. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  2493. std::string name(w->name);
  2494. auto pos = ab_map.find(name);
  2495. if (ab_map.find(name) != ab_map.end()) {
  2496. return &pos->second;
  2497. }
  2498. return nullptr;
  2499. }
  2500. ~llama_lora_adapter() {
  2501. for (struct ggml_context * ctx : ctxs) {
  2502. ggml_free(ctx);
  2503. }
  2504. for (ggml_backend_buffer_t buf : bufs) {
  2505. ggml_backend_buffer_free(buf);
  2506. }
  2507. auto pos = base_model->lora_adapters.find(this);
  2508. if (pos != base_model->lora_adapters.end()) {
  2509. base_model->lora_adapters.erase(pos);
  2510. }
  2511. }
  2512. };
  2513. static size_t llama_get_device_count(const llama_model & model) {
  2514. size_t count = 1;
  2515. #if defined(GGML_USE_CUDA)
  2516. count = ggml_backend_cuda_get_device_count();
  2517. #elif defined(GGML_USE_SYCL)
  2518. count = ggml_backend_sycl_get_device_count();
  2519. #elif defined(GGML_USE_VULKAN)
  2520. count = ggml_backend_vk_get_device_count();
  2521. #elif defined(GGML_USE_CANN)
  2522. return ggml_backend_cann_get_device_count();
  2523. #endif
  2524. #if defined(GGML_USE_RPC)
  2525. count += model.rpc_servers.size();
  2526. #endif
  2527. return count;
  2528. GGML_UNUSED(model);
  2529. }
  2530. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2531. ggml_backend_buffer_type_t buft = nullptr;
  2532. #if defined(GGML_USE_RPC)
  2533. int dev_count = (int)llama_get_device_count(model);
  2534. int rpc_count = (int)model.rpc_servers.size();
  2535. if (gpu >= dev_count - rpc_count) {
  2536. const char * endpoint = model.rpc_servers[gpu - dev_count + rpc_count].c_str();
  2537. return ggml_backend_rpc_buffer_type(endpoint);
  2538. }
  2539. #endif
  2540. #if defined(GGML_USE_METAL)
  2541. buft = ggml_backend_metal_buffer_type();
  2542. #elif defined(GGML_USE_CUDA)
  2543. buft = ggml_backend_cuda_buffer_type(gpu);
  2544. #elif defined(GGML_USE_VULKAN)
  2545. buft = ggml_backend_vk_buffer_type(gpu);
  2546. #elif defined(GGML_USE_SYCL)
  2547. buft = ggml_backend_sycl_buffer_type(gpu);
  2548. #elif defined(GGML_USE_KOMPUTE)
  2549. buft = ggml_backend_kompute_buffer_type(gpu);
  2550. if (buft == nullptr) {
  2551. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2552. }
  2553. #elif defined(GGML_USE_CANN)
  2554. buft = ggml_backend_cann_buffer_type(gpu);
  2555. #endif
  2556. if (buft == nullptr) {
  2557. buft = llama_default_buffer_type_cpu(true);
  2558. }
  2559. return buft;
  2560. GGML_UNUSED(model);
  2561. GGML_UNUSED(gpu);
  2562. }
  2563. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2564. ggml_backend_buffer_type_t buft = nullptr;
  2565. #ifdef GGML_USE_CUDA
  2566. if (ggml_backend_cuda_get_device_count() > 1) {
  2567. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2568. }
  2569. #endif
  2570. #ifdef GGML_USE_SYCL
  2571. if (ggml_backend_sycl_get_device_count() > 1) {
  2572. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2573. }
  2574. #endif
  2575. if (buft == nullptr) {
  2576. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2577. }
  2578. return buft;
  2579. GGML_UNUSED(tensor_split);
  2580. }
  2581. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2582. #if defined(GGML_USE_RPC)
  2583. int dev_count = (int)llama_get_device_count(model);
  2584. int rpc_count = (int)model.rpc_servers.size();
  2585. if (device >= dev_count - rpc_count) {
  2586. size_t total;
  2587. size_t free;
  2588. const char * endpoint = model.rpc_servers[device - dev_count + rpc_count].c_str();
  2589. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  2590. return free;
  2591. }
  2592. #endif
  2593. #if defined(GGML_USE_CUDA)
  2594. size_t total;
  2595. size_t free;
  2596. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2597. return free;
  2598. #elif defined(GGML_USE_SYCL)
  2599. size_t total;
  2600. size_t free;
  2601. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2602. return free;
  2603. #elif defined(GGML_USE_VULKAN)
  2604. size_t total;
  2605. size_t free;
  2606. ggml_backend_vk_get_device_memory(device, &free, &total);
  2607. return free;
  2608. #elif defined(GGML_USE_CANN)
  2609. size_t total;
  2610. size_t free;
  2611. ggml_backend_cann_get_device_memory(device, &free, &total);
  2612. return free;
  2613. #else
  2614. return 1;
  2615. #endif
  2616. GGML_UNUSED(model);
  2617. GGML_UNUSED(device);
  2618. }
  2619. //
  2620. // kv cache helpers
  2621. //
  2622. static bool llama_kv_cache_init(
  2623. struct llama_kv_cache & cache,
  2624. const llama_context * ctx,
  2625. ggml_type type_k,
  2626. ggml_type type_v,
  2627. uint32_t kv_size,
  2628. bool offload) {
  2629. const llama_model & model = ctx->model;
  2630. const llama_cparams & cparams = ctx->cparams;
  2631. const struct llama_hparams & hparams = model.hparams;
  2632. const int64_t n_layer = hparams.n_layer;
  2633. cache.has_shift = false;
  2634. // TODO: find a nicer way to add other recurrent model architectures
  2635. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2636. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  2637. cache.head = 0;
  2638. cache.size = kv_size;
  2639. cache.used = 0;
  2640. cache.type_k = type_k;
  2641. cache.type_v = type_v;
  2642. cache.cells.clear();
  2643. cache.cells.resize(kv_size);
  2644. if (cache.recurrent) {
  2645. // init state copy sources
  2646. for (uint32_t i = 0; i < cache.size; ++i) {
  2647. cache.cells[i].src = i;
  2648. }
  2649. }
  2650. // count used buffer types
  2651. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2652. if (offload) {
  2653. for (int64_t i = 0; i < n_layer; ++i) {
  2654. buft_layer_count[model.buft_layer[i].buft]++;
  2655. }
  2656. } else {
  2657. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2658. }
  2659. // create a context for each buffer type
  2660. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2661. for (auto & it : buft_layer_count) {
  2662. int n_layers = it.second;
  2663. struct ggml_init_params params = {
  2664. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2665. /*.mem_buffer =*/ NULL,
  2666. /*.no_alloc =*/ true,
  2667. };
  2668. ggml_context * ctx = ggml_init(params);
  2669. if (!ctx) {
  2670. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2671. return false;
  2672. }
  2673. ctx_map[it.first] = ctx;
  2674. cache.ctxs.push_back(ctx);
  2675. }
  2676. cache.k_l.reserve(n_layer);
  2677. cache.v_l.reserve(n_layer);
  2678. for (int i = 0; i < (int) n_layer; i++) {
  2679. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  2680. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  2681. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2682. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2683. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2684. ggml_format_name(k, "cache_k_l%d", i);
  2685. ggml_format_name(v, "cache_v_l%d", i);
  2686. cache.k_l.push_back(k);
  2687. cache.v_l.push_back(v);
  2688. }
  2689. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2690. for (auto it : ctx_map) {
  2691. ggml_backend_buffer_type_t buft = it.first;
  2692. ggml_context * ctx = it.second;
  2693. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2694. if (!buf) {
  2695. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2696. return false;
  2697. }
  2698. ggml_backend_buffer_clear(buf, 0);
  2699. 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);
  2700. cache.bufs.push_back(buf);
  2701. }
  2702. return true;
  2703. }
  2704. // find an empty slot of size "n_tokens" in the cache
  2705. // updates the cache head
  2706. // Note: On success, it's important that cache.head points
  2707. // to the first cell of the slot.
  2708. static bool llama_kv_cache_find_slot(
  2709. struct llama_kv_cache & cache,
  2710. const struct llama_batch & batch) {
  2711. const uint32_t n_tokens = batch.n_tokens;
  2712. if (cache.recurrent) {
  2713. // For recurrent state architectures (like Mamba),
  2714. // each KV cache cell can store the state for a whole sequence.
  2715. llama_seq_id min = cache.size - 1;
  2716. llama_seq_id max = 0;
  2717. for (uint32_t i = 0; i < n_tokens; ++i) {
  2718. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2719. llama_seq_id seq_id = batch.seq_id[i][j];
  2720. // make sure it's a valid seq_id
  2721. if ((uint32_t) seq_id < cache.size) {
  2722. if (seq_id > max) {
  2723. max = seq_id;
  2724. }
  2725. if (seq_id < min) {
  2726. min = seq_id;
  2727. }
  2728. // Assuming the tokens are in-order
  2729. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2730. // What should happen when the pos backtracks or skips a value?
  2731. // Clearing the state mid-batch would require special-casing which isn't done.
  2732. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2733. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2734. }
  2735. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2736. cache.used += 1;
  2737. }
  2738. cache.cells[seq_id].pos = batch.pos[i];
  2739. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2740. } else {
  2741. // too big seq_id
  2742. // TODO: would it be possible to resize the KV cache size instead?
  2743. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2744. return false;
  2745. }
  2746. }
  2747. }
  2748. // allow getting the range of used cells, from head to head + n
  2749. cache.head = min;
  2750. cache.n = max - min + 1;
  2751. // sanity check
  2752. return max >= min;
  2753. }
  2754. // otherwise, one cell per token.
  2755. if (n_tokens > cache.size) {
  2756. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  2757. return false;
  2758. }
  2759. uint32_t n_tested = 0;
  2760. while (true) {
  2761. if (cache.head + n_tokens > cache.size) {
  2762. n_tested += cache.size - cache.head;
  2763. cache.head = 0;
  2764. continue;
  2765. }
  2766. bool found = true;
  2767. for (uint32_t i = 0; i < n_tokens; i++) {
  2768. if (cache.cells[cache.head + i].pos >= 0) {
  2769. found = false;
  2770. cache.head += i + 1;
  2771. n_tested += i + 1;
  2772. break;
  2773. }
  2774. }
  2775. if (found) {
  2776. break;
  2777. }
  2778. if (n_tested >= cache.size) {
  2779. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2780. return false;
  2781. }
  2782. }
  2783. for (uint32_t i = 0; i < n_tokens; i++) {
  2784. cache.cells[cache.head + i].pos = batch.pos[i];
  2785. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2786. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2787. }
  2788. }
  2789. cache.used += n_tokens;
  2790. return true;
  2791. }
  2792. // find how many cells are currently in use
  2793. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2794. for (uint32_t i = cache.size; i > 0; --i) {
  2795. const llama_kv_cell & cell = cache.cells[i - 1];
  2796. if (cell.pos >= 0 && !cell.is_empty()) {
  2797. return i;
  2798. }
  2799. }
  2800. return 0;
  2801. }
  2802. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2803. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2804. cache.cells[i].pos = -1;
  2805. cache.cells[i].seq_id.clear();
  2806. }
  2807. cache.head = 0;
  2808. cache.used = 0;
  2809. for (auto & buf : cache.bufs) {
  2810. ggml_backend_buffer_clear(buf, 0);
  2811. }
  2812. }
  2813. static bool llama_kv_cache_seq_rm(
  2814. struct llama_kv_cache & cache,
  2815. llama_seq_id seq_id,
  2816. llama_pos p0,
  2817. llama_pos p1) {
  2818. uint32_t new_head = cache.size;
  2819. if (p0 < 0) p0 = 0;
  2820. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2821. // models like Mamba can't have a state partially erased
  2822. if (cache.recurrent) {
  2823. if (seq_id >= (int64_t) cache.size) {
  2824. // could be fatal
  2825. return false;
  2826. }
  2827. if (0 <= seq_id) {
  2828. // partial intersection is invalid
  2829. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2830. return false;
  2831. }
  2832. } else {
  2833. // seq_id is negative, then the range should include everything or nothing
  2834. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2835. return false;
  2836. }
  2837. }
  2838. }
  2839. for (uint32_t i = 0; i < cache.size; ++i) {
  2840. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2841. if (seq_id < 0) {
  2842. cache.cells[i].seq_id.clear();
  2843. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2844. cache.cells[i].seq_id.erase(seq_id);
  2845. } else {
  2846. continue;
  2847. }
  2848. if (cache.cells[i].is_empty()) {
  2849. // keep count of the number of used cells
  2850. if (cache.cells[i].pos >= 0) cache.used--;
  2851. cache.cells[i].pos = -1;
  2852. if (new_head == cache.size) new_head = i;
  2853. }
  2854. }
  2855. }
  2856. // If we freed up a slot, set head to it so searching can start there.
  2857. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2858. return true;
  2859. }
  2860. static void llama_kv_cache_seq_cp(
  2861. struct llama_kv_cache & cache,
  2862. llama_seq_id seq_id_src,
  2863. llama_seq_id seq_id_dst,
  2864. llama_pos p0,
  2865. llama_pos p1) {
  2866. if (p0 < 0) p0 = 0;
  2867. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2868. if (cache.recurrent) {
  2869. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2870. seq_id_src = cache.cells[seq_id_src].src;
  2871. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2872. // intent to "copy from"
  2873. // supports copy chains thanks to taking the source of the source
  2874. cache.cells[seq_id_dst].src = seq_id_src;
  2875. // preserve the "keep or clear" status of the copied sequence
  2876. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2877. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2878. } else {
  2879. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2880. }
  2881. cache.do_copy = true;
  2882. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2883. }
  2884. return;
  2885. }
  2886. // otherwise, this is the KV cache of a Transformer-like model
  2887. cache.head = 0;
  2888. for (uint32_t i = 0; i < cache.size; ++i) {
  2889. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2890. cache.cells[i].seq_id.insert(seq_id_dst);
  2891. }
  2892. }
  2893. }
  2894. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2895. uint32_t new_head = cache.size;
  2896. for (uint32_t i = 0; i < cache.size; ++i) {
  2897. if (!cache.cells[i].has_seq_id(seq_id)) {
  2898. if (cache.cells[i].pos >= 0) cache.used--;
  2899. cache.cells[i].pos = -1;
  2900. cache.cells[i].seq_id.clear();
  2901. if (new_head == cache.size) new_head = i;
  2902. } else {
  2903. cache.cells[i].seq_id.clear();
  2904. cache.cells[i].seq_id.insert(seq_id);
  2905. }
  2906. }
  2907. // If we freed up a slot, set head to it so searching can start there.
  2908. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2909. }
  2910. static void llama_kv_cache_seq_add(
  2911. struct llama_kv_cache & cache,
  2912. llama_seq_id seq_id,
  2913. llama_pos p0,
  2914. llama_pos p1,
  2915. llama_pos delta) {
  2916. uint32_t new_head = cache.size;
  2917. if (p0 < 0) p0 = 0;
  2918. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2919. // If there is no range then return early to avoid looping over the cache.
  2920. if (p0 == p1) return;
  2921. if (cache.recurrent) {
  2922. // for Mamba-like models, only the pos needs to be shifted
  2923. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2924. llama_kv_cell & cell = cache.cells[seq_id];
  2925. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2926. cell.pos += delta;
  2927. }
  2928. }
  2929. return;
  2930. }
  2931. for (uint32_t i = 0; i < cache.size; ++i) {
  2932. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2933. cache.has_shift = true;
  2934. cache.cells[i].pos += delta;
  2935. cache.cells[i].delta += delta;
  2936. if (cache.cells[i].pos < 0) {
  2937. if (!cache.cells[i].is_empty()) {
  2938. cache.used--;
  2939. }
  2940. cache.cells[i].pos = -1;
  2941. cache.cells[i].seq_id.clear();
  2942. if (new_head == cache.size) {
  2943. new_head = i;
  2944. }
  2945. }
  2946. }
  2947. }
  2948. // If we freed up a slot, set head to it so searching can start there.
  2949. // Otherwise we just start the next search from the beginning.
  2950. cache.head = new_head != cache.size ? new_head : 0;
  2951. }
  2952. static void llama_kv_cache_seq_div(
  2953. struct llama_kv_cache & cache,
  2954. llama_seq_id seq_id,
  2955. llama_pos p0,
  2956. llama_pos p1,
  2957. int d) {
  2958. if (p0 < 0) p0 = 0;
  2959. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2960. // If there is no range then return early to avoid looping over the cache.
  2961. if (p0 == p1) return;
  2962. if (cache.recurrent) {
  2963. // for Mamba-like models, only the pos needs to be changed
  2964. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2965. llama_kv_cell & cell = cache.cells[seq_id];
  2966. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2967. cell.pos /= d;
  2968. }
  2969. }
  2970. return;
  2971. }
  2972. for (uint32_t i = 0; i < cache.size; ++i) {
  2973. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2974. cache.has_shift = true;
  2975. {
  2976. llama_pos p_old = cache.cells[i].pos;
  2977. cache.cells[i].pos /= d;
  2978. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2979. }
  2980. }
  2981. }
  2982. }
  2983. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2984. llama_pos result = 0;
  2985. for (uint32_t i = 0; i < cache.size; ++i) {
  2986. if (cache.cells[i].has_seq_id(seq_id)) {
  2987. result = std::max(result, cache.cells[i].pos);
  2988. }
  2989. }
  2990. return result;
  2991. }
  2992. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2993. cache.do_defrag = true;
  2994. }
  2995. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  2996. // the FA kernels require padding to avoid extra runtime boundary checks
  2997. return cparams.flash_attn ? 256u : 32u;
  2998. }
  2999. //
  3000. // model loading and saving
  3001. //
  3002. enum llama_fver {
  3003. GGUF_FILE_VERSION_V1 = 1,
  3004. GGUF_FILE_VERSION_V2 = 2,
  3005. GGUF_FILE_VERSION_V3 = 3,
  3006. };
  3007. static const char * llama_file_version_name(llama_fver version) {
  3008. switch (version) {
  3009. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3010. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3011. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3012. }
  3013. return "unknown";
  3014. }
  3015. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3016. char buf[256];
  3017. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3018. for (size_t i = 1; i < ne.size(); i++) {
  3019. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3020. }
  3021. return buf;
  3022. }
  3023. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3024. char buf[256];
  3025. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3026. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3027. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3028. }
  3029. return buf;
  3030. }
  3031. namespace GGUFMeta {
  3032. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3033. struct GKV_Base_Type {
  3034. static constexpr gguf_type gt = gt_;
  3035. static T getter(const gguf_context * ctx, const int kid) {
  3036. return gfun(ctx, kid);
  3037. }
  3038. };
  3039. template<typename T> struct GKV_Base;
  3040. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3041. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3042. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3043. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3044. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3045. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3046. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3047. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3048. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3049. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3050. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3051. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3052. template<> struct GKV_Base<std::string> {
  3053. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3054. static std::string getter(const gguf_context * ctx, const int kid) {
  3055. return gguf_get_val_str(ctx, kid);
  3056. }
  3057. };
  3058. struct ArrayInfo {
  3059. const gguf_type gt;
  3060. const size_t length;
  3061. const void * data;
  3062. };
  3063. template<> struct GKV_Base<ArrayInfo> {
  3064. public:
  3065. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3066. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3067. return ArrayInfo {
  3068. gguf_get_arr_type(ctx, k),
  3069. size_t(gguf_get_arr_n(ctx, k)),
  3070. gguf_get_arr_data(ctx, k),
  3071. };
  3072. }
  3073. };
  3074. template<typename T>
  3075. class GKV : public GKV_Base<T> {
  3076. GKV() = delete;
  3077. public:
  3078. static T get_kv(const gguf_context * ctx, const int k) {
  3079. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3080. if (kt != GKV::gt) {
  3081. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3082. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3083. }
  3084. return GKV::getter(ctx, k);
  3085. }
  3086. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3087. switch (ty) {
  3088. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3089. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3090. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3091. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3092. }
  3093. return "unknown";
  3094. }
  3095. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3096. if (!ovrd) { return false; }
  3097. if (ovrd->tag == expected_type) {
  3098. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3099. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3100. switch (ovrd->tag) {
  3101. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3102. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3103. } break;
  3104. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3105. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3106. } break;
  3107. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3108. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3109. } break;
  3110. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3111. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  3112. } break;
  3113. default:
  3114. // Shouldn't be possible to end up here, but just in case...
  3115. throw std::runtime_error(
  3116. format("Unsupported attempt to override %s type for metadata key %s\n",
  3117. override_type_to_str(ovrd->tag), ovrd->key));
  3118. }
  3119. return true;
  3120. }
  3121. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  3122. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  3123. return false;
  3124. }
  3125. template<typename OT>
  3126. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  3127. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3128. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  3129. target = ovrd->val_bool;
  3130. return true;
  3131. }
  3132. return false;
  3133. }
  3134. template<typename OT>
  3135. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  3136. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3137. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  3138. target = ovrd->val_i64;
  3139. return true;
  3140. }
  3141. return false;
  3142. }
  3143. template<typename OT>
  3144. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  3145. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3146. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  3147. target = ovrd->val_f64;
  3148. return true;
  3149. }
  3150. return false;
  3151. }
  3152. template<typename OT>
  3153. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  3154. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3155. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  3156. target = ovrd->val_str;
  3157. return true;
  3158. }
  3159. return false;
  3160. }
  3161. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3162. if (try_override<T>(target, ovrd)) {
  3163. return true;
  3164. }
  3165. if (k < 0) { return false; }
  3166. target = get_kv(ctx, k);
  3167. return true;
  3168. }
  3169. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3170. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  3171. }
  3172. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3173. return set(ctx, key.c_str(), target, ovrd);
  3174. }
  3175. };
  3176. }
  3177. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  3178. // TODO: update when needed or think of some clever automatic way to do this
  3179. static size_t llama_model_max_nodes(const llama_model & /*model*/) {
  3180. //if (model.arch == LLM_ARCH_LLAMA && model.hparams.n_layer > ??) { // llama-3 405B
  3181. // return 32768;
  3182. //}
  3183. return 8192;
  3184. }
  3185. struct llama_model_loader {
  3186. int n_kv = 0;
  3187. int n_tensors = 0;
  3188. int n_created = 0;
  3189. int64_t n_elements = 0;
  3190. size_t n_bytes = 0;
  3191. bool use_mmap = false;
  3192. bool check_tensors;
  3193. llama_files files;
  3194. llama_ftype ftype;
  3195. llama_fver fver;
  3196. llama_mmaps mappings;
  3197. // Holds information on a model weight
  3198. struct llama_tensor_weight {
  3199. uint16_t idx; // source file index
  3200. size_t offs; // tensor data offset in the original file
  3201. ggml_tensor * tensor;
  3202. 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) {
  3203. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  3204. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  3205. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  3206. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  3207. }
  3208. }
  3209. };
  3210. std::vector<llama_tensor_weight> weights;
  3211. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  3212. struct gguf_context * meta = NULL;
  3213. std::vector<ggml_context *> contexts;
  3214. std::string arch_name;
  3215. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  3216. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  3217. int trace = 0;
  3218. if (getenv("LLAMA_TRACE")) {
  3219. trace = atoi(getenv("LLAMA_TRACE"));
  3220. }
  3221. if (param_overrides_p != nullptr) {
  3222. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  3223. kv_overrides.insert({std::string(p->key), *p});
  3224. }
  3225. }
  3226. struct ggml_context * ctx = NULL;
  3227. struct gguf_init_params params = {
  3228. /*.no_alloc = */ true,
  3229. /*.ctx = */ &ctx,
  3230. };
  3231. meta = gguf_init_from_file(fname.c_str(), params);
  3232. if (!meta) {
  3233. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  3234. }
  3235. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  3236. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  3237. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  3238. contexts.emplace_back(ctx);
  3239. // Save tensors data offset of the main file.
  3240. // For subsidiary files, `meta` tensor data offset must not be used,
  3241. // so we build a unified tensors index for weights.
  3242. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3243. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  3244. }
  3245. uint16_t n_split = 0;
  3246. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  3247. // Load additional GGML contexts
  3248. if (n_split > 1) {
  3249. uint16_t idx = 0;
  3250. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  3251. if (idx != 0) {
  3252. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  3253. }
  3254. char split_prefix[PATH_MAX] = {0};
  3255. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  3256. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  3257. }
  3258. if (trace > 0) {
  3259. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  3260. }
  3261. char split_path[PATH_MAX] = {0};
  3262. for (idx = 1; idx < n_split; idx++) {
  3263. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  3264. struct gguf_init_params split_params = {
  3265. /*.no_alloc = */ true,
  3266. /*.ctx = */ &ctx,
  3267. };
  3268. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  3269. if (!ctx_gguf) {
  3270. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  3271. }
  3272. files.emplace_back(new llama_file(split_path, "rb"));
  3273. contexts.emplace_back(ctx);
  3274. // Save tensors data offset info of the shard.
  3275. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3276. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  3277. }
  3278. gguf_free(ctx_gguf);
  3279. }
  3280. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  3281. // sanity check
  3282. {
  3283. const int n_tensors_loaded = (int) weights.size();
  3284. if (n_tensors != n_tensors_loaded) {
  3285. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  3286. }
  3287. }
  3288. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  3289. }
  3290. n_kv = gguf_get_n_kv(meta);
  3291. n_tensors = weights.size();
  3292. fver = (enum llama_fver) gguf_get_version(meta);
  3293. std::set<std::string> tensor_names;
  3294. for (auto & w : weights) {
  3295. n_elements += ggml_nelements(w.tensor);
  3296. n_bytes += ggml_nbytes(w.tensor);
  3297. // make sure there is no duplicated tensor names
  3298. const std::string name(w.tensor->name);
  3299. auto found = tensor_names.find(name);
  3300. if (found != tensor_names.end()) {
  3301. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  3302. }
  3303. tensor_names.insert(name);
  3304. }
  3305. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  3306. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  3307. // determine file type based on the number of tensors for each quantization and print meta data
  3308. // TODO: make optional
  3309. {
  3310. std::map<enum ggml_type, uint32_t> n_type;
  3311. uint32_t n_type_max = 0;
  3312. enum ggml_type type_max = GGML_TYPE_F32;
  3313. for (int i = 0; i < n_tensors; i++) {
  3314. const ggml_tensor * tensor = weights.at(i).tensor;
  3315. enum ggml_type type = tensor->type;
  3316. n_type[type]++;
  3317. if (n_type_max < n_type[type]) {
  3318. n_type_max = n_type[type];
  3319. type_max = type;
  3320. }
  3321. if (trace > 0) {
  3322. const uint16_t sid = weights.at(i).idx;
  3323. 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());
  3324. }
  3325. }
  3326. switch (type_max) {
  3327. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  3328. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  3329. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  3330. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  3331. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  3332. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  3333. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  3334. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  3335. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  3336. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  3337. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  3338. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  3339. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  3340. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  3341. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  3342. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  3343. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  3344. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  3345. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  3346. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  3347. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  3348. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  3349. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  3350. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  3351. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  3352. default:
  3353. {
  3354. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  3355. ftype = LLAMA_FTYPE_ALL_F32;
  3356. } break;
  3357. }
  3358. // this is a way to mark that we have "guessed" the file type
  3359. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  3360. {
  3361. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  3362. if (kid >= 0) {
  3363. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  3364. }
  3365. }
  3366. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  3367. for (int i = 0; i < n_kv; i++) {
  3368. const char * name = gguf_get_key(meta, i);
  3369. const enum gguf_type type = gguf_get_kv_type(meta, i);
  3370. const std::string type_name =
  3371. type == GGUF_TYPE_ARRAY
  3372. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  3373. : gguf_type_name(type);
  3374. std::string value = gguf_kv_to_str(meta, i);
  3375. const size_t MAX_VALUE_LEN = 40;
  3376. if (value.size() > MAX_VALUE_LEN) {
  3377. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  3378. }
  3379. replace_all(value, "\n", "\\n");
  3380. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  3381. }
  3382. // print type counts
  3383. for (auto & kv : n_type) {
  3384. if (kv.second == 0) {
  3385. continue;
  3386. }
  3387. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  3388. }
  3389. }
  3390. if (!llama_mmap::SUPPORTED) {
  3391. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  3392. use_mmap = false;
  3393. }
  3394. this->use_mmap = use_mmap;
  3395. this->check_tensors = check_tensors;
  3396. }
  3397. ~llama_model_loader() {
  3398. if (meta) {
  3399. gguf_free(meta);
  3400. }
  3401. for (auto * ctx : contexts) {
  3402. ggml_free(ctx);
  3403. }
  3404. }
  3405. template<typename T>
  3406. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3407. get_arr_n(const std::string & key, T & result, const bool required = true) {
  3408. const int kid = gguf_find_key(meta, key.c_str());
  3409. if (kid < 0) {
  3410. if (required) {
  3411. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3412. }
  3413. return false;
  3414. }
  3415. struct GGUFMeta::ArrayInfo arr_info =
  3416. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3417. result = arr_info.length;
  3418. return true;
  3419. }
  3420. template<typename T>
  3421. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3422. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  3423. return get_arr_n(llm_kv(kid), result, required);
  3424. }
  3425. template<typename T>
  3426. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  3427. const int kid = gguf_find_key(meta, key.c_str());
  3428. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3429. if (required) {
  3430. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3431. }
  3432. return false;
  3433. }
  3434. struct GGUFMeta::ArrayInfo arr_info =
  3435. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3436. switch (arr_info.gt) {
  3437. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3438. case GGUF_TYPE_INT32: GGML_ASSERT(
  3439. (std::is_same<T, int32_t>::value) ||
  3440. (std::is_same<T, uint32_t>::value)); break;
  3441. default:
  3442. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3443. }
  3444. result.resize(arr_info.length);
  3445. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  3446. return true;
  3447. }
  3448. template<typename T, size_t N_MAX>
  3449. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  3450. const int kid = gguf_find_key(meta, key.c_str());
  3451. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3452. if (required) {
  3453. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3454. }
  3455. return false;
  3456. }
  3457. struct GGUFMeta::ArrayInfo arr_info =
  3458. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3459. switch (arr_info.gt) {
  3460. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3461. case GGUF_TYPE_INT32: GGML_ASSERT(
  3462. (std::is_same<T, int32_t>::value) ||
  3463. (std::is_same<T, uint32_t>::value)); break;
  3464. default:
  3465. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3466. }
  3467. if (arr_info.length > N_MAX) {
  3468. 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));
  3469. }
  3470. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  3471. return true;
  3472. }
  3473. template<typename T>
  3474. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  3475. return get_arr(llm_kv(kid), result, required);
  3476. }
  3477. template<typename T>
  3478. bool get_key(const std::string & key, T & result, const bool required = true) {
  3479. auto it = kv_overrides.find(key);
  3480. const struct llama_model_kv_override * override =
  3481. it != kv_overrides.end() ? &it->second : nullptr;
  3482. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  3483. if (required && !found) {
  3484. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3485. }
  3486. return found;
  3487. }
  3488. template<typename T>
  3489. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  3490. return get_key(llm_kv(kid), result, required);
  3491. }
  3492. // get array of n <= N_MAX elements, or a single element repeated n times
  3493. template<typename T, size_t N_MAX>
  3494. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  3495. const int kid = gguf_find_key(meta, key.c_str());
  3496. if (kid < 0) {
  3497. if (required) {
  3498. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3499. }
  3500. return false;
  3501. }
  3502. if (n > N_MAX) {
  3503. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  3504. }
  3505. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  3506. struct GGUFMeta::ArrayInfo arr_info =
  3507. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3508. if (n != arr_info.length) {
  3509. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  3510. }
  3511. return get_arr(key, result, required);
  3512. } else {
  3513. T value;
  3514. bool ok = get_key(key, value, required);
  3515. if (!ok) {
  3516. return false;
  3517. }
  3518. for (uint32_t i = 0; i < n; i++) {
  3519. result[i] = value;
  3520. }
  3521. return true;
  3522. }
  3523. }
  3524. template<typename T>
  3525. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  3526. return get_key_or_arr(llm_kv(kid), result, n, required);
  3527. }
  3528. std::string get_arch_name() const {
  3529. return arch_name;
  3530. }
  3531. enum llm_arch get_arch() const {
  3532. return llm_kv.arch;
  3533. }
  3534. const char * get_tensor_name(int i) const {
  3535. return weights.at(i).tensor->name;
  3536. }
  3537. const llama_tensor_weight * get_weight(const char * name) const {
  3538. for (const auto & weight : weights) {
  3539. if (strcmp(name, weight.tensor->name) == 0) {
  3540. return &weight;
  3541. }
  3542. }
  3543. return nullptr;
  3544. }
  3545. const llama_tensor_weight * get_weight(int i) const {
  3546. return get_weight(get_tensor_name(i));
  3547. }
  3548. const llama_tensor_weight & require_weight(const char * name) const {
  3549. const llama_tensor_weight * weight = get_weight(name);
  3550. if (!weight) {
  3551. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3552. }
  3553. return *weight;
  3554. }
  3555. struct ggml_tensor * get_tensor_meta(const char * name) const {
  3556. const auto * weight = get_weight(name);
  3557. if (!weight) {
  3558. return nullptr;
  3559. }
  3560. return weight->tensor;
  3561. }
  3562. struct ggml_tensor * require_tensor_meta(const char * name) const {
  3563. struct ggml_tensor * tensor = get_tensor_meta(name);
  3564. if (!tensor) {
  3565. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3566. }
  3567. return tensor;
  3568. }
  3569. struct ggml_tensor * get_tensor_meta(int i) const {
  3570. return get_tensor_meta(get_tensor_name(i));
  3571. }
  3572. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  3573. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  3574. ggml_set_name(tensor, ggml_get_name(cur));
  3575. if (duplicated) {
  3576. size_data += ggml_nbytes(cur);
  3577. } else {
  3578. n_created++;
  3579. }
  3580. return tensor;
  3581. }
  3582. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  3583. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  3584. if (cur == NULL) {
  3585. if (!required) {
  3586. return NULL;
  3587. }
  3588. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  3589. }
  3590. {
  3591. bool is_ok = true;
  3592. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3593. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  3594. is_ok = false;
  3595. break;
  3596. }
  3597. }
  3598. if (!is_ok) {
  3599. throw std::runtime_error(
  3600. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  3601. __func__, name.c_str(),
  3602. llama_format_tensor_shape(ne).c_str(),
  3603. llama_format_tensor_shape(cur).c_str()));
  3604. }
  3605. }
  3606. return cur;
  3607. }
  3608. static const int TENSOR_NOT_REQUIRED = 1;
  3609. static const int TENSOR_DUPLICATED = 2;
  3610. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  3611. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  3612. if (cur == NULL) {
  3613. return NULL;
  3614. }
  3615. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  3616. }
  3617. struct ggml_tensor * create_tensor_as_view(struct ggml_context * ctx, struct ggml_tensor * base, const std::string & name, const std::vector<int64_t> & ne, size_t offset, bool required = true) {
  3618. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3619. if (cur == NULL) {
  3620. return NULL;
  3621. }
  3622. if (cur->type != base->type) {
  3623. 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)));
  3624. }
  3625. std::array<int64_t, GGML_MAX_DIMS> dims;
  3626. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3627. dims[i] = i < ne.size() ? ne[i] : 1;
  3628. }
  3629. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  3630. dims[0], dims[1], dims[2], dims[3],
  3631. cur->nb[1], cur->nb[2], cur->nb[3],
  3632. offset);
  3633. ggml_set_name(tensor, name.c_str());
  3634. n_created++;
  3635. return tensor;
  3636. }
  3637. void done_getting_tensors() const {
  3638. if (n_created != n_tensors) {
  3639. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  3640. }
  3641. }
  3642. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  3643. if (use_mmap) {
  3644. mappings.reserve(files.size());
  3645. mmaps_used.reserve(files.size());
  3646. for (const auto & file : files) {
  3647. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  3648. mmaps_used.emplace_back(mapping->size, 0);
  3649. if (mlock_mmaps) {
  3650. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  3651. mlock_mmap->init(mapping->addr);
  3652. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  3653. }
  3654. mappings.emplace_back(std::move(mapping));
  3655. }
  3656. }
  3657. // compute the total size of all tensors for progress reporting
  3658. for (auto & w : weights) {
  3659. size_data += ggml_nbytes(w.tensor);
  3660. }
  3661. }
  3662. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  3663. GGML_ASSERT(!mappings.empty());
  3664. const auto & mapping = mappings.at(idx);
  3665. *first = mapping->size;
  3666. *last = 0;
  3667. *addr = mapping->addr;
  3668. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3669. try {
  3670. const auto * weight = get_weight(ggml_get_name(tensor));
  3671. if (!weight) {
  3672. continue;
  3673. }
  3674. if (weight->idx != idx) {
  3675. continue;
  3676. }
  3677. *first = std::min(*first, weight->offs);
  3678. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  3679. } catch(...) {
  3680. // the tensor is not in the model
  3681. }
  3682. }
  3683. }
  3684. // for backwards compatibility, does not support ggml-backend
  3685. void load_data_for(struct ggml_tensor * cur) const {
  3686. const auto & w = require_weight(ggml_get_name(cur));
  3687. if (use_mmap) {
  3688. const auto & mapping = mappings.at(w.idx);
  3689. if (cur->data == nullptr) {
  3690. cur->data = (uint8_t *)mapping->addr + w.offs;
  3691. } else {
  3692. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  3693. }
  3694. } else {
  3695. GGML_ASSERT(cur->data != nullptr);
  3696. GGML_ASSERT(w.idx < files.size());
  3697. const auto & file = files.at(w.idx);
  3698. file->seek(w.offs, SEEK_SET);
  3699. file->read_raw(cur->data, ggml_nbytes(cur));
  3700. }
  3701. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  3702. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3703. }
  3704. }
  3705. size_t size_done = 0;
  3706. size_t size_data = 0;
  3707. std::vector<std::pair<size_t, size_t>> mmaps_used;
  3708. // Returns false if cancelled by progress_callback
  3709. bool load_all_data(
  3710. struct ggml_context * ctx,
  3711. llama_buf_map & bufs_mmap,
  3712. llama_mlocks * lmlocks,
  3713. llama_progress_callback progress_callback,
  3714. void * progress_callback_user_data) {
  3715. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  3716. std::vector<no_init<uint8_t>> read_buf;
  3717. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  3718. #if defined(GGML_USE_CUDA)
  3719. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  3720. // NVMe raid configurations might require more / larger buffers.
  3721. constexpr size_t n_buffers = 4;
  3722. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  3723. std::vector<ggml_backend_buffer_t> host_buffers;
  3724. std::vector<void*> host_ptrs;
  3725. std::vector<ggml_backend_event_t> events;
  3726. size_t buffer_idx = 0; // buffer to use for async loads
  3727. ggml_backend_t cuda_backend = nullptr;
  3728. if (!use_mmap && !check_tensors) {
  3729. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  3730. // First determine if the CUDA backend is active, and if so, determine the device ID.
  3731. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  3732. if (buf) {
  3733. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  3734. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  3735. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  3736. if (buffer_type == cuda_buffer_type) {
  3737. cuda_backend = ggml_backend_cuda_init(i);
  3738. break;
  3739. }
  3740. }
  3741. }
  3742. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  3743. if (cuda_backend) {
  3744. for (size_t idx = 0; idx < n_buffers; ++idx) {
  3745. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  3746. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  3747. events.emplace_back(ggml_backend_event_new(cuda_backend));
  3748. }
  3749. }
  3750. }
  3751. #endif
  3752. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3753. const auto * weight = get_weight(ggml_get_name(cur));
  3754. if (weight == nullptr) {
  3755. // this can happen with split experts models
  3756. continue;
  3757. }
  3758. if (progress_callback) {
  3759. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  3760. return false;
  3761. }
  3762. }
  3763. size_t n_size = ggml_nbytes(cur);
  3764. if (use_mmap) {
  3765. const auto & mapping = mappings.at(weight->idx);
  3766. ggml_backend_buffer_t buf_mmap = nullptr;
  3767. if (bufs_mmap.count(weight->idx)) {
  3768. buf_mmap = bufs_mmap.at(weight->idx);
  3769. }
  3770. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  3771. if (check_tensors) {
  3772. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  3773. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  3774. }));
  3775. }
  3776. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  3777. if (buf_mmap && cur->data == nullptr) {
  3778. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  3779. if (lmlocks) {
  3780. const auto & lmlock = lmlocks->at(weight->idx);
  3781. lmlock->grow_to(weight->offs + n_size);
  3782. }
  3783. auto & mmap_used = mmaps_used[weight->idx];
  3784. mmap_used.first = std::min(mmap_used.first, weight->offs);
  3785. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  3786. } else {
  3787. ggml_backend_tensor_set(cur, data, 0, n_size);
  3788. }
  3789. } else {
  3790. GGML_ASSERT(weight->idx < files.size());
  3791. const auto & file = files.at(weight->idx);
  3792. if (ggml_backend_buffer_is_host(cur->buffer)) {
  3793. file->seek(weight->offs, SEEK_SET);
  3794. file->read_raw(cur->data, n_size);
  3795. if (check_tensors) {
  3796. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  3797. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  3798. }));
  3799. }
  3800. } else {
  3801. #if defined(GGML_USE_CUDA)
  3802. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  3803. if (cuda_backend) {
  3804. file->seek(weight->offs, SEEK_SET);
  3805. size_t bytes_read = 0;
  3806. while (bytes_read < n_size) {
  3807. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  3808. ggml_backend_event_synchronize(events[buffer_idx]);
  3809. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  3810. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  3811. ggml_backend_event_record(events[buffer_idx]);
  3812. bytes_read += read_iteration;
  3813. ++buffer_idx;
  3814. buffer_idx %= n_buffers;
  3815. }
  3816. }
  3817. else
  3818. #endif
  3819. {
  3820. read_buf.resize(n_size);
  3821. file->seek(weight->offs, SEEK_SET);
  3822. file->read_raw(read_buf.data(), n_size);
  3823. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3824. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  3825. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3826. }
  3827. }
  3828. }
  3829. }
  3830. size_done += n_size;
  3831. }
  3832. #if defined(GGML_USE_CUDA)
  3833. // free temporary resources used for async cuda uploads
  3834. if (cuda_backend) {
  3835. for (size_t idx = 0; idx < n_buffers;++idx) {
  3836. ggml_backend_event_synchronize(events[idx]);
  3837. ggml_backend_event_free(events[idx]);
  3838. ggml_backend_buffer_free(host_buffers[idx]);
  3839. }
  3840. ggml_backend_free(cuda_backend);
  3841. }
  3842. #endif
  3843. // check validation results
  3844. bool validation_failed = false;
  3845. for (auto & future : validation_result) {
  3846. auto result = future.get();
  3847. if (!result.second) {
  3848. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  3849. validation_failed = true;
  3850. }
  3851. }
  3852. if (validation_failed) {
  3853. throw std::runtime_error("found tensors with invalid data");
  3854. }
  3855. // check if this is the last call and do final cleanup
  3856. if (size_done >= size_data) {
  3857. // unmap offloaded tensors and metadata
  3858. if (use_mmap) {
  3859. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3860. const auto & mmap_used = mmaps_used.at(idx);
  3861. auto & mapping = mappings.at(idx);
  3862. mapping->unmap_fragment(0, mmap_used.first);
  3863. if (mmap_used.second != 0) {
  3864. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3865. }
  3866. }
  3867. }
  3868. if (progress_callback) {
  3869. // Even though the model is done loading, we still honor
  3870. // cancellation since we need to free allocations.
  3871. return progress_callback(1.0f, progress_callback_user_data);
  3872. }
  3873. }
  3874. return true;
  3875. }
  3876. };
  3877. template<>
  3878. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3879. uint32_t tmp;
  3880. const bool found = get_key(kid, tmp, required);
  3881. if (found) {
  3882. result = (enum llama_pooling_type) tmp;
  3883. } else {
  3884. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3885. }
  3886. return found;
  3887. }
  3888. //
  3889. // load LLaMA models
  3890. //
  3891. static const char * llama_model_arch_name(llm_arch arch) {
  3892. auto it = LLM_ARCH_NAMES.find(arch);
  3893. if (it == LLM_ARCH_NAMES.end()) {
  3894. return "unknown";
  3895. }
  3896. return it->second;
  3897. }
  3898. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3899. if (ftype & LLAMA_FTYPE_GUESSED) {
  3900. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3901. }
  3902. switch (ftype) {
  3903. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3904. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3905. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  3906. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3907. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3908. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3909. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3910. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3911. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3912. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3913. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3914. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3915. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3916. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3917. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3918. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3919. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3920. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3921. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  3922. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3923. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3924. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3925. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3926. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  3927. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  3928. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  3929. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3930. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3931. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3932. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3933. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  3934. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  3935. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  3936. default: return "unknown, may not work";
  3937. }
  3938. }
  3939. static const char * llama_model_type_name(e_model type) {
  3940. switch (type) {
  3941. case MODEL_14M: return "14M";
  3942. case MODEL_17M: return "17M";
  3943. case MODEL_22M: return "22M";
  3944. case MODEL_33M: return "33M";
  3945. case MODEL_60M: return "60M";
  3946. case MODEL_70M: return "70M";
  3947. case MODEL_80M: return "80M";
  3948. case MODEL_109M: return "109M";
  3949. case MODEL_137M: return "137M";
  3950. case MODEL_160M: return "160M";
  3951. case MODEL_220M: return "220M";
  3952. case MODEL_250M: return "250M";
  3953. case MODEL_270M: return "270M";
  3954. case MODEL_335M: return "335M";
  3955. case MODEL_410M: return "410M";
  3956. case MODEL_450M: return "450M";
  3957. case MODEL_770M: return "770M";
  3958. case MODEL_780M: return "780M";
  3959. case MODEL_0_5B: return "0.5B";
  3960. case MODEL_1B: return "1B";
  3961. case MODEL_1_3B: return "1.3B";
  3962. case MODEL_1_4B: return "1.4B";
  3963. case MODEL_2B: return "2B";
  3964. case MODEL_2_8B: return "2.8B";
  3965. case MODEL_3B: return "3B";
  3966. case MODEL_4B: return "4B";
  3967. case MODEL_6B: return "6B";
  3968. case MODEL_6_9B: return "6.9B";
  3969. case MODEL_7B: return "7B";
  3970. case MODEL_8B: return "8B";
  3971. case MODEL_9B: return "9B";
  3972. case MODEL_11B: return "11B";
  3973. case MODEL_12B: return "12B";
  3974. case MODEL_13B: return "13B";
  3975. case MODEL_14B: return "14B";
  3976. case MODEL_15B: return "15B";
  3977. case MODEL_16B: return "16B";
  3978. case MODEL_20B: return "20B";
  3979. case MODEL_30B: return "30B";
  3980. case MODEL_34B: return "34B";
  3981. case MODEL_35B: return "35B";
  3982. case MODEL_40B: return "40B";
  3983. case MODEL_65B: return "65B";
  3984. case MODEL_70B: return "70B";
  3985. case MODEL_236B: return "236B";
  3986. case MODEL_314B: return "314B";
  3987. case MODEL_SMALL: return "0.1B";
  3988. case MODEL_MEDIUM: return "0.4B";
  3989. case MODEL_LARGE: return "0.8B";
  3990. case MODEL_XL: return "1.5B";
  3991. case MODEL_A2_7B: return "A2.7B";
  3992. case MODEL_8x7B: return "8x7B";
  3993. case MODEL_8x22B: return "8x22B";
  3994. case MODEL_16x12B: return "16x12B";
  3995. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  3996. case MODEL_57B_A14B: return "57B.A14B";
  3997. case MODEL_27B: return "27B";
  3998. default: return "?B";
  3999. }
  4000. }
  4001. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4002. switch (type) {
  4003. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4004. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4005. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4006. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4007. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4008. default: return "unknown";
  4009. }
  4010. }
  4011. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4012. model.arch = ml.get_arch();
  4013. if (model.arch == LLM_ARCH_UNKNOWN) {
  4014. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4015. }
  4016. }
  4017. static void llm_load_hparams(
  4018. llama_model_loader & ml,
  4019. llama_model & model) {
  4020. auto & hparams = model.hparams;
  4021. const gguf_context * ctx = ml.meta;
  4022. // get metadata as string
  4023. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4024. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4025. if (type == GGUF_TYPE_ARRAY) {
  4026. continue;
  4027. }
  4028. const char * name = gguf_get_key(ctx, i);
  4029. const std::string value = gguf_kv_to_str(ctx, i);
  4030. model.gguf_kv.emplace(name, value);
  4031. }
  4032. // get general kv
  4033. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4034. // get hparams kv
  4035. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4036. // everything past this point is not vocab-related
  4037. if (hparams.vocab_only) {
  4038. return;
  4039. }
  4040. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4041. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4042. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4043. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4044. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4045. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4046. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4047. if (hparams.n_expert > 0) {
  4048. GGML_ASSERT(hparams.n_expert_used > 0);
  4049. } else {
  4050. GGML_ASSERT(hparams.n_expert_used == 0);
  4051. }
  4052. // zero-out the per-layer hparams
  4053. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4054. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4055. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4056. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4057. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4058. // n_head_kv is optional, default to n_head
  4059. hparams.n_head_kv_arr = hparams.n_head_arr;
  4060. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4061. bool rope_finetuned = false;
  4062. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4063. hparams.rope_finetuned = rope_finetuned;
  4064. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4065. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4066. // rope_freq_base (optional)
  4067. hparams.rope_freq_base_train = 10000.0f;
  4068. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4069. std::string rope_scaling("linear");
  4070. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4071. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4072. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4073. // rope_freq_scale (inverse of the kv) is optional
  4074. float ropescale = 0.0f;
  4075. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4076. // try the old key name
  4077. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4078. }
  4079. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4080. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4081. // non-transformer models do not have attention heads
  4082. if (hparams.n_head() > 0) {
  4083. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4084. // gpt-j n_rot = rotary_dim
  4085. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4086. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4087. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  4088. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  4089. // sanity check for n_rot (optional)
  4090. hparams.n_rot = hparams.n_embd_head_k;
  4091. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  4092. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  4093. if (hparams.n_rot != hparams.n_embd_head_k) {
  4094. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  4095. }
  4096. }
  4097. } else {
  4098. hparams.n_rot = 0;
  4099. hparams.n_embd_head_k = 0;
  4100. hparams.n_embd_head_v = 0;
  4101. }
  4102. // arch-specific KVs
  4103. switch (model.arch) {
  4104. case LLM_ARCH_LLAMA:
  4105. {
  4106. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4107. if (hparams.n_expert == 8) {
  4108. switch (hparams.n_layer) {
  4109. case 32: model.type = e_model::MODEL_8x7B; break;
  4110. case 56: model.type = e_model::MODEL_8x22B; break;
  4111. default: model.type = e_model::MODEL_UNKNOWN;
  4112. }
  4113. } else {
  4114. switch (hparams.n_layer) {
  4115. case 22: model.type = e_model::MODEL_1B; break;
  4116. case 26: model.type = e_model::MODEL_3B; break;
  4117. // granite uses a vocab with len 49152
  4118. 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;
  4119. case 36: model.type = e_model::MODEL_8B; break; // granite
  4120. case 40: model.type = e_model::MODEL_13B; break;
  4121. case 48: model.type = e_model::MODEL_34B; break;
  4122. case 60: model.type = e_model::MODEL_30B; break;
  4123. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  4124. default: model.type = e_model::MODEL_UNKNOWN;
  4125. }
  4126. }
  4127. } break;
  4128. case LLM_ARCH_MINICPM:
  4129. {
  4130. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4131. switch (hparams.n_layer) {
  4132. case 40: model.type = e_model::MODEL_2B; break;
  4133. default: model.type = e_model::MODEL_UNKNOWN;
  4134. }
  4135. } break;
  4136. case LLM_ARCH_GROK:
  4137. {
  4138. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4139. switch (hparams.n_layer) {
  4140. case 64: model.type = e_model::MODEL_314B; break;
  4141. default: model.type = e_model::MODEL_UNKNOWN;
  4142. }
  4143. } break;
  4144. case LLM_ARCH_FALCON:
  4145. {
  4146. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4147. switch (hparams.n_layer) {
  4148. case 32: model.type = e_model::MODEL_7B; break;
  4149. case 60: model.type = e_model::MODEL_40B; break;
  4150. default: model.type = e_model::MODEL_UNKNOWN;
  4151. }
  4152. } break;
  4153. case LLM_ARCH_BAICHUAN:
  4154. {
  4155. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4156. switch (hparams.n_layer) {
  4157. case 32: model.type = e_model::MODEL_7B; break;
  4158. case 40: model.type = e_model::MODEL_13B; break;
  4159. default: model.type = e_model::MODEL_UNKNOWN;
  4160. }
  4161. if (model.type == e_model::MODEL_13B) {
  4162. // TODO: become GGUF KV parameter
  4163. hparams.f_max_alibi_bias = 8.0f;
  4164. }
  4165. } break;
  4166. case LLM_ARCH_STARCODER:
  4167. {
  4168. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4169. switch (hparams.n_layer) {
  4170. case 24: model.type = e_model::MODEL_1B; break;
  4171. case 36: model.type = e_model::MODEL_3B; break;
  4172. case 42: model.type = e_model::MODEL_7B; break;
  4173. case 40: model.type = e_model::MODEL_15B; break;
  4174. default: model.type = e_model::MODEL_UNKNOWN;
  4175. }
  4176. } break;
  4177. case LLM_ARCH_REFACT:
  4178. {
  4179. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4180. switch (hparams.n_layer) {
  4181. case 32: model.type = e_model::MODEL_1B; break;
  4182. default: model.type = e_model::MODEL_UNKNOWN;
  4183. }
  4184. // TODO: become GGUF KV parameter
  4185. hparams.f_max_alibi_bias = 8.0f;
  4186. } break;
  4187. case LLM_ARCH_BERT:
  4188. {
  4189. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4190. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4191. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4192. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4193. switch (hparams.n_layer) {
  4194. case 3:
  4195. model.type = e_model::MODEL_17M; break; // bge-micro
  4196. case 6:
  4197. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  4198. case 12:
  4199. switch (hparams.n_embd) {
  4200. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  4201. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  4202. } break;
  4203. case 24:
  4204. model.type = e_model::MODEL_335M; break; // bge-large
  4205. }
  4206. } break;
  4207. case LLM_ARCH_JINA_BERT_V2:
  4208. {
  4209. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4210. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4211. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4212. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4213. hparams.f_max_alibi_bias = 8.0f;
  4214. switch (hparams.n_layer) {
  4215. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  4216. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  4217. }
  4218. } break;
  4219. case LLM_ARCH_NOMIC_BERT:
  4220. {
  4221. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4222. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4223. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4224. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4225. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  4226. model.type = e_model::MODEL_137M;
  4227. }
  4228. } break;
  4229. case LLM_ARCH_BLOOM:
  4230. {
  4231. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4232. switch (hparams.n_layer) {
  4233. case 24: model.type = e_model::MODEL_1B; break;
  4234. case 30:
  4235. switch (hparams.n_embd) {
  4236. case 2560: model.type = e_model::MODEL_3B; break;
  4237. case 4096: model.type = e_model::MODEL_7B; break;
  4238. } break;
  4239. }
  4240. // TODO: become GGUF KV parameter
  4241. hparams.f_max_alibi_bias = 8.0f;
  4242. } break;
  4243. case LLM_ARCH_MPT:
  4244. {
  4245. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4246. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4247. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4248. switch (hparams.n_layer) {
  4249. case 32: model.type = e_model::MODEL_7B; break;
  4250. case 48: model.type = e_model::MODEL_30B; break;
  4251. default: model.type = e_model::MODEL_UNKNOWN;
  4252. }
  4253. } break;
  4254. case LLM_ARCH_STABLELM:
  4255. {
  4256. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4257. switch (hparams.n_layer) {
  4258. case 24: model.type = e_model::MODEL_1B; break;
  4259. case 32: model.type = e_model::MODEL_3B; break;
  4260. case 40: model.type = e_model::MODEL_12B; break;
  4261. default: model.type = e_model::MODEL_UNKNOWN;
  4262. }
  4263. } break;
  4264. case LLM_ARCH_QWEN:
  4265. {
  4266. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4267. switch (hparams.n_layer) {
  4268. case 32: model.type = e_model::MODEL_7B; break;
  4269. case 40: model.type = e_model::MODEL_13B; break;
  4270. default: model.type = e_model::MODEL_UNKNOWN;
  4271. }
  4272. } break;
  4273. case LLM_ARCH_QWEN2:
  4274. {
  4275. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4276. switch (hparams.n_layer) {
  4277. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  4278. case 32: model.type = e_model::MODEL_7B; break;
  4279. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  4280. case 80: model.type = e_model::MODEL_70B; break;
  4281. default: model.type = e_model::MODEL_UNKNOWN;
  4282. }
  4283. } break;
  4284. case LLM_ARCH_QWEN2MOE:
  4285. {
  4286. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  4287. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  4288. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4289. switch (hparams.n_layer) {
  4290. case 24: model.type = e_model::MODEL_A2_7B; break;
  4291. case 28: model.type = e_model::MODEL_57B_A14B; break;
  4292. default: model.type = e_model::MODEL_UNKNOWN;
  4293. }
  4294. } break;
  4295. case LLM_ARCH_PHI2:
  4296. {
  4297. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4298. switch (hparams.n_layer) {
  4299. case 24: model.type = e_model::MODEL_1B; break;
  4300. case 32: model.type = e_model::MODEL_3B; break;
  4301. default: model.type = e_model::MODEL_UNKNOWN;
  4302. }
  4303. } break;
  4304. case LLM_ARCH_PHI3:
  4305. {
  4306. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);
  4307. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4308. switch (hparams.n_layer) {
  4309. case 24: model.type = e_model::MODEL_1B; break;
  4310. case 32: model.type = e_model::MODEL_3B; break;
  4311. case 40: model.type = e_model::MODEL_14B; break;
  4312. default: model.type = e_model::MODEL_UNKNOWN;
  4313. }
  4314. } break;
  4315. case LLM_ARCH_PLAMO:
  4316. {
  4317. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4318. switch (hparams.n_layer) {
  4319. case 40: model.type = e_model::MODEL_13B; break;
  4320. default: model.type = e_model::MODEL_UNKNOWN;
  4321. }
  4322. } break;
  4323. case LLM_ARCH_GPT2:
  4324. {
  4325. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4326. switch (hparams.n_layer) {
  4327. case 12: model.type = e_model::MODEL_SMALL; break;
  4328. case 24: model.type = e_model::MODEL_MEDIUM; break;
  4329. case 36: model.type = e_model::MODEL_LARGE; break;
  4330. case 48: model.type = e_model::MODEL_XL; break;
  4331. default: model.type = e_model::MODEL_UNKNOWN;
  4332. }
  4333. } break;
  4334. case LLM_ARCH_CODESHELL:
  4335. {
  4336. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4337. switch (hparams.n_layer) {
  4338. case 42: model.type = e_model::MODEL_7B; break;
  4339. default: model.type = e_model::MODEL_UNKNOWN;
  4340. }
  4341. } break;
  4342. case LLM_ARCH_ORION:
  4343. {
  4344. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4345. switch (hparams.n_layer) {
  4346. case 40: model.type = e_model::MODEL_14B; break;
  4347. default: model.type = e_model::MODEL_UNKNOWN;
  4348. }
  4349. } break;
  4350. case LLM_ARCH_INTERNLM2:
  4351. {
  4352. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4353. switch (hparams.n_layer) {
  4354. case 32: model.type = e_model::MODEL_7B; break;
  4355. case 48: model.type = e_model::MODEL_20B; break;
  4356. default: model.type = e_model::MODEL_UNKNOWN;
  4357. }
  4358. } break;
  4359. case LLM_ARCH_GEMMA:
  4360. {
  4361. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4362. switch (hparams.n_layer) {
  4363. case 18: model.type = e_model::MODEL_2B; break;
  4364. case 28: model.type = e_model::MODEL_7B; break;
  4365. default: model.type = e_model::MODEL_UNKNOWN;
  4366. }
  4367. } break;
  4368. case LLM_ARCH_GEMMA2:
  4369. {
  4370. hparams.n_swa = 4096; // default value of gemma 2
  4371. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  4372. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4373. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  4374. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  4375. hparams.attn_soft_cap = true;
  4376. switch (hparams.n_layer) {
  4377. case 26: model.type = e_model::MODEL_2B; break;
  4378. case 42: model.type = e_model::MODEL_9B; break;
  4379. case 46: model.type = e_model::MODEL_27B; break;
  4380. default: model.type = e_model::MODEL_UNKNOWN;
  4381. }
  4382. } break;
  4383. case LLM_ARCH_STARCODER2:
  4384. {
  4385. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4386. switch (hparams.n_layer) {
  4387. case 30: model.type = e_model::MODEL_3B; break;
  4388. case 32: model.type = e_model::MODEL_7B; break;
  4389. case 40: model.type = e_model::MODEL_15B; break;
  4390. case 52: model.type = e_model::MODEL_20B; break; // granite
  4391. case 88: model.type = e_model::MODEL_34B; break; // granite
  4392. default: model.type = e_model::MODEL_UNKNOWN;
  4393. }
  4394. } break;
  4395. case LLM_ARCH_MAMBA:
  4396. {
  4397. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  4398. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  4399. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  4400. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  4401. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4402. switch (hparams.n_layer) {
  4403. case 24:
  4404. switch (hparams.n_embd) {
  4405. case 768: model.type = e_model::MODEL_SMALL; break;
  4406. default: model.type = e_model::MODEL_UNKNOWN;
  4407. } break;
  4408. case 48:
  4409. switch (hparams.n_embd) {
  4410. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  4411. case 1536: model.type = e_model::MODEL_LARGE; break;
  4412. case 2048: model.type = e_model::MODEL_XL; break;
  4413. default: model.type = e_model::MODEL_UNKNOWN;
  4414. } break;
  4415. case 64:
  4416. switch (hparams.n_embd) {
  4417. case 2560: model.type = e_model::MODEL_3B; break;
  4418. default: model.type = e_model::MODEL_UNKNOWN;
  4419. } break;
  4420. default: model.type = e_model::MODEL_UNKNOWN;
  4421. }
  4422. } break;
  4423. case LLM_ARCH_XVERSE:
  4424. {
  4425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4426. switch (hparams.n_layer) {
  4427. case 32: model.type = e_model::MODEL_7B; break;
  4428. case 40: model.type = e_model::MODEL_13B; break;
  4429. case 80: model.type = e_model::MODEL_65B; break;
  4430. default: model.type = e_model::MODEL_UNKNOWN;
  4431. }
  4432. } break;
  4433. case LLM_ARCH_COMMAND_R:
  4434. {
  4435. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  4436. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4437. switch (hparams.n_layer) {
  4438. case 40: model.type = e_model::MODEL_35B; break;
  4439. default: model.type = e_model::MODEL_UNKNOWN;
  4440. }
  4441. } break;
  4442. case LLM_ARCH_DBRX:
  4443. {
  4444. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4445. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  4446. switch (hparams.n_layer) {
  4447. case 40: model.type = e_model::MODEL_16x12B; break;
  4448. default: model.type = e_model::MODEL_UNKNOWN;
  4449. }
  4450. } break;
  4451. case LLM_ARCH_OLMO:
  4452. {
  4453. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4454. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4455. switch (hparams.n_layer) {
  4456. case 22: model.type = e_model::MODEL_1B; break;
  4457. case 32: model.type = e_model::MODEL_7B; break;
  4458. case 80: model.type = e_model::MODEL_70B; break;
  4459. default: model.type = e_model::MODEL_UNKNOWN;
  4460. }
  4461. } break;
  4462. case LLM_ARCH_OPENELM:
  4463. {
  4464. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4465. switch (hparams.n_layer) {
  4466. case 16: model.type = e_model::MODEL_270M; break;
  4467. case 20: model.type = e_model::MODEL_450M; break;
  4468. case 28: model.type = e_model::MODEL_1B; break;
  4469. case 36: model.type = e_model::MODEL_3B; break;
  4470. default: model.type = e_model::MODEL_UNKNOWN;
  4471. }
  4472. } break;
  4473. case LLM_ARCH_GPTNEOX:
  4474. {
  4475. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4476. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  4477. switch (hparams.n_layer) {
  4478. case 6:
  4479. switch (hparams.n_ff()) {
  4480. case 512: model.type = e_model::MODEL_14M; break;
  4481. case 2048: model.type = e_model::MODEL_70M; break;
  4482. default: model.type = e_model::MODEL_UNKNOWN;
  4483. } break;
  4484. case 12:
  4485. switch (hparams.n_ff()) {
  4486. case 3072: model.type = e_model::MODEL_160M; break;
  4487. default: model.type = e_model::MODEL_UNKNOWN;
  4488. } break;
  4489. case 16:
  4490. switch (hparams.n_ff()) {
  4491. case 8192: model.type = e_model::MODEL_1B; break;
  4492. default: model.type = e_model::MODEL_UNKNOWN;
  4493. } break;
  4494. case 24:
  4495. switch (hparams.n_ff()) {
  4496. case 4096: model.type = e_model::MODEL_410M; break;
  4497. case 8192: model.type = e_model::MODEL_1_4B; break;
  4498. default: model.type = e_model::MODEL_UNKNOWN;
  4499. } break;
  4500. case 32:
  4501. switch (hparams.n_ff()) {
  4502. case 10240: model.type = e_model::MODEL_2_8B; break;
  4503. case 16384: model.type = e_model::MODEL_6_9B; break;
  4504. default: model.type = e_model::MODEL_UNKNOWN;
  4505. } break;
  4506. case 36:
  4507. switch (hparams.n_ff()) {
  4508. case 20480: model.type = e_model::MODEL_12B; break;
  4509. default: model.type = e_model::MODEL_UNKNOWN;
  4510. } break;
  4511. case 44:
  4512. switch (hparams.n_ff()) {
  4513. case 24576: model.type = e_model::MODEL_20B; break;
  4514. default: model.type = e_model::MODEL_UNKNOWN;
  4515. } break;
  4516. default: model.type = e_model::MODEL_UNKNOWN;
  4517. }
  4518. } break;
  4519. case LLM_ARCH_ARCTIC:
  4520. {
  4521. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4522. if (hparams.n_expert == 128) {
  4523. switch (hparams.n_layer) {
  4524. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  4525. default: model.type = e_model::MODEL_UNKNOWN;
  4526. }
  4527. } else {
  4528. model.type = e_model::MODEL_UNKNOWN;
  4529. }
  4530. } break;
  4531. case LLM_ARCH_DEEPSEEK2:
  4532. {
  4533. bool is_lite = (hparams.n_layer == 27);
  4534. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4535. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  4536. if (!is_lite) {
  4537. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  4538. }
  4539. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  4540. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  4541. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  4542. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  4543. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  4544. switch (hparams.n_layer) {
  4545. case 27: model.type = e_model::MODEL_16B; break;
  4546. case 60: model.type = e_model::MODEL_236B; break;
  4547. default: model.type = e_model::MODEL_UNKNOWN;
  4548. }
  4549. } break;
  4550. case LLM_ARCH_CHATGLM:
  4551. {
  4552. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4553. switch (hparams.n_layer) {
  4554. case 28: model.type = e_model::MODEL_6B; break;
  4555. case 40: model.type = e_model::MODEL_9B; break;
  4556. default: model.type = e_model::MODEL_UNKNOWN;
  4557. }
  4558. } break;
  4559. case LLM_ARCH_BITNET:
  4560. {
  4561. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4562. switch (hparams.n_layer) {
  4563. case 26: model.type = e_model::MODEL_3B; break;
  4564. default: model.type = e_model::MODEL_UNKNOWN;
  4565. }
  4566. } break;
  4567. case LLM_ARCH_T5:
  4568. {
  4569. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4570. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  4571. uint32_t dec_start_token_id;
  4572. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  4573. hparams.dec_start_token_id = dec_start_token_id;
  4574. }
  4575. switch (hparams.n_layer) {
  4576. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  4577. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  4578. case 12:
  4579. switch (hparams.n_ff()) {
  4580. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  4581. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  4582. default: model.type = e_model::MODEL_UNKNOWN;
  4583. } break;
  4584. case 24:
  4585. switch (hparams.n_ff()) {
  4586. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  4587. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  4588. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  4589. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  4590. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  4591. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  4592. default: model.type = e_model::MODEL_UNKNOWN;
  4593. } break;
  4594. default: model.type = e_model::MODEL_UNKNOWN;
  4595. }
  4596. } break;
  4597. case LLM_ARCH_JAIS:
  4598. {
  4599. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4600. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4601. switch (hparams.n_layer) {
  4602. case 24: model.type = e_model::MODEL_1_3B; break;
  4603. case 40: model.type = e_model::MODEL_13B; break;
  4604. /* TODO: add variants */
  4605. default: model.type = e_model::MODEL_UNKNOWN;
  4606. }
  4607. } break;
  4608. default: (void)0;
  4609. }
  4610. model.ftype = ml.ftype;
  4611. if (hparams.f_max_alibi_bias > 0.0f) {
  4612. hparams.use_alibi = true;
  4613. }
  4614. hparams.rope_type = llama_rope_type(&model);
  4615. }
  4616. static void llm_load_vocab(
  4617. llama_model_loader & ml,
  4618. llama_model & model) {
  4619. auto & vocab = model.vocab;
  4620. struct gguf_context * ctx = ml.meta;
  4621. const auto kv = LLM_KV(model.arch);
  4622. // determine vocab type
  4623. {
  4624. std::string tokenizer_model;
  4625. std::string tokenizer_pre;
  4626. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  4627. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  4628. if (tokenizer_model == "no_vocab") {
  4629. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  4630. // default special tokens
  4631. vocab.special_bos_id = -1;
  4632. vocab.special_eos_id = -1;
  4633. vocab.special_unk_id = -1;
  4634. vocab.special_sep_id = -1;
  4635. vocab.special_pad_id = -1;
  4636. vocab.special_cls_id = -1;
  4637. vocab.special_mask_id = -1;
  4638. vocab.linefeed_id = -1;
  4639. return;
  4640. } else if (tokenizer_model == "llama") {
  4641. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  4642. // default special tokens
  4643. vocab.special_bos_id = 1;
  4644. vocab.special_eos_id = 2;
  4645. vocab.special_unk_id = 0;
  4646. vocab.special_sep_id = -1;
  4647. vocab.special_pad_id = -1;
  4648. vocab.special_cls_id = -1;
  4649. vocab.special_mask_id = -1;
  4650. } else if (tokenizer_model == "bert") {
  4651. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  4652. // default special tokens
  4653. vocab.special_bos_id = -1;
  4654. vocab.special_eos_id = -1;
  4655. vocab.special_unk_id = 100;
  4656. vocab.special_sep_id = 102;
  4657. vocab.special_pad_id = 0;
  4658. vocab.special_cls_id = 101;
  4659. vocab.special_mask_id = 103;
  4660. } else if (tokenizer_model == "gpt2") {
  4661. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  4662. // read bpe merges and populate bpe ranks
  4663. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  4664. if (merges_keyidx == -1) {
  4665. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  4666. }
  4667. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  4668. for (int i = 0; i < n_merges; i++) {
  4669. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  4670. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4671. std::string first;
  4672. std::string second;
  4673. const size_t pos = word.find(' ', 1);
  4674. if (pos != std::string::npos) {
  4675. first = word.substr(0, pos);
  4676. second = word.substr(pos + 1);
  4677. }
  4678. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  4679. }
  4680. // default special tokens
  4681. vocab.special_bos_id = 11;
  4682. vocab.special_eos_id = 11;
  4683. vocab.special_unk_id = -1;
  4684. vocab.special_sep_id = -1;
  4685. vocab.special_pad_id = -1;
  4686. vocab.special_cls_id = -1;
  4687. vocab.special_mask_id = -1;
  4688. } else if (tokenizer_model == "t5") {
  4689. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  4690. // default special tokens
  4691. vocab.special_bos_id = -1;
  4692. vocab.special_eos_id = 1;
  4693. vocab.special_unk_id = 2;
  4694. vocab.special_sep_id = -1;
  4695. vocab.special_pad_id = 0;
  4696. vocab.special_cls_id = -1;
  4697. vocab.special_mask_id = -1;
  4698. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  4699. if (precompiled_charsmap_keyidx != -1) {
  4700. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  4701. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  4702. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  4703. #ifdef IS_BIG_ENDIAN
  4704. // correct endiannes of data in precompiled_charsmap binary blob
  4705. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  4706. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  4707. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  4708. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  4709. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  4710. for (size_t i = 0; i < xcda_array_size; ++i) {
  4711. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  4712. }
  4713. #endif
  4714. }
  4715. } else {
  4716. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  4717. }
  4718. // for now, only BPE models have pre-tokenizers
  4719. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  4720. vocab.tokenizer_add_space_prefix = false;
  4721. vocab.tokenizer_clean_spaces = true;
  4722. if (tokenizer_pre.empty()) {
  4723. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  4724. LLAMA_LOG_WARN("%s: \n", __func__);
  4725. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  4726. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  4727. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  4728. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  4729. LLAMA_LOG_WARN("%s: \n", __func__);
  4730. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4731. } else if (tokenizer_pre == "default") {
  4732. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4733. } else if (
  4734. tokenizer_pre == "llama3" ||
  4735. tokenizer_pre == "llama-v3" ||
  4736. tokenizer_pre == "llama-bpe") {
  4737. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  4738. vocab.tokenizer_ignore_merges = true;
  4739. vocab.tokenizer_add_bos = true;
  4740. } else if (
  4741. tokenizer_pre == "deepseek-llm") {
  4742. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  4743. vocab.tokenizer_clean_spaces = false;
  4744. } else if (
  4745. tokenizer_pre == "deepseek-coder") {
  4746. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  4747. vocab.tokenizer_clean_spaces = false;
  4748. } else if (
  4749. tokenizer_pre == "falcon") {
  4750. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  4751. } else if (
  4752. tokenizer_pre == "mpt") {
  4753. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  4754. } else if (
  4755. tokenizer_pre == "starcoder") {
  4756. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  4757. } else if (
  4758. tokenizer_pre == "gpt-2" ||
  4759. tokenizer_pre == "phi-2" ||
  4760. tokenizer_pre == "jina-es" ||
  4761. tokenizer_pre == "jina-de" ||
  4762. tokenizer_pre == "jina-v2-es" ||
  4763. tokenizer_pre == "jina-v2-de" ||
  4764. tokenizer_pre == "jina-v2-code") {
  4765. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  4766. } else if (
  4767. tokenizer_pre == "refact") {
  4768. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  4769. } else if (
  4770. tokenizer_pre == "command-r") {
  4771. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  4772. vocab.tokenizer_clean_spaces = false;
  4773. } else if (
  4774. tokenizer_pre == "qwen2") {
  4775. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  4776. vocab.tokenizer_clean_spaces = false;
  4777. } else if (
  4778. tokenizer_pre == "stablelm2") {
  4779. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  4780. } else if (
  4781. tokenizer_pre == "olmo") {
  4782. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  4783. } else if (
  4784. tokenizer_pre == "dbrx") {
  4785. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  4786. } else if (
  4787. tokenizer_pre == "smaug-bpe") {
  4788. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  4789. } else if (
  4790. tokenizer_pre == "poro-chat") {
  4791. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  4792. vocab.tokenizer_clean_spaces = false;
  4793. } else if (
  4794. tokenizer_pre == "chatglm-bpe") {
  4795. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  4796. vocab.special_bos_id = -1;
  4797. } else if (
  4798. tokenizer_pre == "viking") {
  4799. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  4800. vocab.tokenizer_clean_spaces = false;
  4801. } else if (
  4802. tokenizer_pre == "jais") {
  4803. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  4804. } else if (
  4805. tokenizer_pre == "tekken") {
  4806. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  4807. vocab.tokenizer_clean_spaces = false;
  4808. vocab.tokenizer_ignore_merges = true;
  4809. vocab.tokenizer_add_bos = true;
  4810. } else if (
  4811. tokenizer_pre == "smollm") {
  4812. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  4813. vocab.tokenizer_clean_spaces = false;
  4814. } else if (
  4815. tokenizer_pre == "codeshell") {
  4816. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  4817. } else {
  4818. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  4819. }
  4820. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4821. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4822. vocab.tokenizer_add_space_prefix = true;
  4823. vocab.tokenizer_clean_spaces = false;
  4824. vocab.tokenizer_add_bos = true;
  4825. vocab.tokenizer_add_eos = false;
  4826. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4827. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4828. vocab.tokenizer_add_space_prefix = false;
  4829. vocab.tokenizer_clean_spaces = true;
  4830. vocab.tokenizer_add_bos = true;
  4831. vocab.tokenizer_add_eos = false;
  4832. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  4833. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4834. vocab.tokenizer_add_bos = false;
  4835. vocab.tokenizer_add_eos = true;
  4836. } else {
  4837. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4838. }
  4839. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  4840. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  4841. }
  4842. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  4843. if (token_idx == -1) {
  4844. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  4845. }
  4846. const float * scores = nullptr;
  4847. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  4848. if (score_idx != -1) {
  4849. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  4850. }
  4851. const int * toktypes = nullptr;
  4852. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  4853. if (toktype_idx != -1) {
  4854. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  4855. }
  4856. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  4857. vocab.id_to_token.resize(n_vocab);
  4858. for (uint32_t i = 0; i < n_vocab; i++) {
  4859. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  4860. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4861. vocab.token_to_id[word] = i;
  4862. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  4863. auto & token_data = vocab.id_to_token[i];
  4864. token_data.text = std::move(word);
  4865. token_data.score = scores ? scores[i] : 0.0f;
  4866. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  4867. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  4868. switch(toktypes[i]) {
  4869. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  4870. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  4871. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  4872. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  4873. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  4874. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  4875. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4876. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4877. }
  4878. }
  4879. }
  4880. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  4881. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  4882. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4883. // For Fill-In-the-Middle (FIM)/infill models which where converted
  4884. // prior to support of FIM special tokens in GGUF, the following
  4885. // will allow those models to continue to work. The general names
  4886. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  4887. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  4888. // new versions of these models have been published.
  4889. std::string gen_name;
  4890. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  4891. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  4892. [](unsigned char c){ return std::tolower(c); });
  4893. if (gen_name.find("code") != std::string::npos) {
  4894. if (model.arch == LLM_ARCH_LLAMA
  4895. && 32010 < vocab.id_to_token.size()
  4896. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  4897. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  4898. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  4899. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  4900. vocab.special_prefix_id = 32007;
  4901. vocab.special_suffix_id = 32008;
  4902. vocab.special_middle_id = 32009;
  4903. vocab.special_eot_id = 32010;
  4904. } else if (model.arch == LLM_ARCH_GEMMA
  4905. && 107 < vocab.id_to_token.size()
  4906. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  4907. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  4908. && vocab.id_to_token[68].text == "<|fim_middle|>"
  4909. && vocab.id_to_token[107].text == "<end_of_turn>") {
  4910. vocab.special_prefix_id = 67;
  4911. vocab.special_suffix_id = 69;
  4912. vocab.special_middle_id = 68;
  4913. // TODO: this is not EOT, it is "file separator" token, needs fix
  4914. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  4915. //vocab.special_eot_id = 70;
  4916. vocab.special_eot_id = 107;
  4917. }
  4918. }
  4919. try {
  4920. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  4921. } catch (const std::exception & e) {
  4922. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  4923. vocab.linefeed_id = vocab.special_pad_id;
  4924. }
  4925. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4926. vocab.linefeed_id = vocab.special_pad_id;
  4927. } else {
  4928. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  4929. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  4930. vocab.linefeed_id = ids[0];
  4931. }
  4932. // special tokens
  4933. {
  4934. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  4935. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  4936. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  4937. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  4938. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  4939. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  4940. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  4941. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  4942. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  4943. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  4944. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  4945. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  4946. };
  4947. for (const auto & it : special_token_types) {
  4948. const std::string & key = kv(std::get<0>(it));
  4949. int32_t & id = std::get<1>(it);
  4950. uint32_t new_id;
  4951. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  4952. continue;
  4953. }
  4954. if (new_id >= vocab.id_to_token.size()) {
  4955. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  4956. __func__, key.c_str(), new_id, id);
  4957. } else {
  4958. id = new_id;
  4959. }
  4960. }
  4961. // Handle add_bos_token and add_eos_token
  4962. {
  4963. bool temp = true;
  4964. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  4965. vocab.tokenizer_add_bos = temp;
  4966. }
  4967. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  4968. vocab.tokenizer_add_eos = temp;
  4969. }
  4970. }
  4971. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  4972. //
  4973. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  4974. // for now, we apply this workaround to find the EOT token based on its text
  4975. if (vocab.special_eot_id == -1) {
  4976. for (const auto & t : vocab.token_to_id) {
  4977. if (
  4978. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  4979. // need to fix convert script
  4980. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  4981. (t.first == "<|eot_id|>" ||
  4982. t.first == "<|im_end|>" ||
  4983. t.first == "<|end|>" ||
  4984. t.first == "<end_of_turn>" ||
  4985. t.first == "<|endoftext|>"
  4986. )
  4987. ) {
  4988. vocab.special_eot_id = t.second;
  4989. break;
  4990. }
  4991. }
  4992. }
  4993. }
  4994. // build special tokens cache
  4995. {
  4996. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  4997. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  4998. vocab.cache_special_tokens.push_back(id);
  4999. }
  5000. }
  5001. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  5002. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  5003. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  5004. }
  5005. );
  5006. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  5007. }
  5008. // build token to piece cache
  5009. {
  5010. size_t size_cache = 0;
  5011. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  5012. for (uint32_t id = 0; id < n_vocab; ++id) {
  5013. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  5014. size_cache += cache_token_to_piece[id].size();
  5015. }
  5016. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  5017. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  5018. }
  5019. // Handle per token attributes
  5020. //NOTE: Each model customizes per token attributes.
  5021. //NOTE: Per token attributes are missing from the GGUF file.
  5022. //TODO: Extract attributes from GGUF file.
  5023. {
  5024. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  5025. for (auto substr : substrs) {
  5026. if (str.find(substr) < std::string::npos) {
  5027. return true;
  5028. }
  5029. }
  5030. return false;
  5031. };
  5032. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  5033. uint32_t current = vocab.id_to_token.at(id).attr;
  5034. current = value ? (current | attr) : (current & ~attr);
  5035. vocab.id_to_token[id].attr = (llama_token_attr) current;
  5036. };
  5037. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  5038. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  5039. };
  5040. std::string model_name;
  5041. std::string tokenizer_pre;
  5042. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  5043. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5044. // model name to lowercase
  5045. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  5046. [] (const std::string::value_type x) {
  5047. return std::tolower(x);
  5048. }
  5049. );
  5050. // set attributes by model/tokenizer name
  5051. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  5052. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  5053. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  5054. for (auto id : vocab.cache_special_tokens) {
  5055. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5056. }
  5057. for (auto token : {"</s>"}) {
  5058. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5059. }
  5060. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  5061. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  5062. }
  5063. }
  5064. }
  5065. }
  5066. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  5067. const auto & hparams = model.hparams;
  5068. const auto & vocab = model.vocab;
  5069. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  5070. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  5071. bool is_var = false;
  5072. std::vector<uint32_t> v;
  5073. for (uint32_t i = 0; i < n; ++i) {
  5074. v.push_back(f(i));
  5075. if (v[i] != v[0]) {
  5076. is_var = true;
  5077. }
  5078. }
  5079. std::stringstream ss;
  5080. if (is_var) {
  5081. ss << "[";
  5082. for (uint32_t i = 0; i < n; ++i) {
  5083. ss << v[i];
  5084. if (i < n - 1) {
  5085. ss << ", ";
  5086. }
  5087. }
  5088. ss << "]";
  5089. } else {
  5090. ss << v[0];
  5091. }
  5092. return ss.str();
  5093. };
  5094. // hparams
  5095. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  5096. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  5097. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  5098. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  5099. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  5100. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  5101. if (!hparams.vocab_only) {
  5102. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  5103. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  5104. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  5105. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  5106. 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());
  5107. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  5108. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  5109. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  5110. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  5111. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  5112. 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());
  5113. 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());
  5114. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  5115. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  5116. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  5117. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  5118. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  5119. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  5120. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  5121. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  5122. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  5123. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  5124. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  5125. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  5126. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  5127. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  5128. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  5129. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  5130. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  5131. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  5132. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  5133. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  5134. }
  5135. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  5136. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  5137. if (ml.n_elements >= 1e12) {
  5138. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  5139. } else if (ml.n_elements >= 1e9) {
  5140. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  5141. } else if (ml.n_elements >= 1e6) {
  5142. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  5143. } else {
  5144. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  5145. }
  5146. if (ml.n_bytes < GiB) {
  5147. 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);
  5148. } else {
  5149. 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);
  5150. }
  5151. // general kv
  5152. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  5153. // special tokens
  5154. 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() ); }
  5155. 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() ); }
  5156. 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() ); }
  5157. 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() ); }
  5158. 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() ); }
  5159. 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() ); }
  5160. 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() ); }
  5161. 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() ); }
  5162. if (vocab.special_prefix_id != -1) { LLAMA_LOG_INFO( "%s: PRE token = %d '%s'\n", __func__, vocab.special_prefix_id, vocab.id_to_token[vocab.special_prefix_id].text.c_str() ); }
  5163. if (vocab.special_suffix_id != -1) { LLAMA_LOG_INFO( "%s: SUF token = %d '%s'\n", __func__, vocab.special_suffix_id, vocab.id_to_token[vocab.special_suffix_id].text.c_str() ); }
  5164. if (vocab.special_middle_id != -1) { LLAMA_LOG_INFO( "%s: MID token = %d '%s'\n", __func__, vocab.special_middle_id, vocab.id_to_token[vocab.special_middle_id].text.c_str() ); }
  5165. 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() ); }
  5166. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  5167. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  5168. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  5169. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  5170. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  5171. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5172. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  5173. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  5174. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  5175. }
  5176. if (model.arch == LLM_ARCH_QWEN2MOE) {
  5177. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5178. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  5179. }
  5180. }
  5181. // Returns false if cancelled by progress_callback
  5182. static bool llm_load_tensors(
  5183. llama_model_loader & ml,
  5184. llama_model & model,
  5185. int n_gpu_layers,
  5186. enum llama_split_mode split_mode,
  5187. int main_gpu,
  5188. const float * tensor_split,
  5189. bool use_mlock,
  5190. llama_progress_callback progress_callback,
  5191. void * progress_callback_user_data) {
  5192. model.t_start_us = ggml_time_us();
  5193. auto & hparams = model.hparams;
  5194. model.split_mode = split_mode;
  5195. model.main_gpu = main_gpu;
  5196. model.n_gpu_layers = n_gpu_layers;
  5197. const int n_layer = hparams.n_layer;
  5198. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  5199. bool use_mmap_buffer = true;
  5200. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  5201. model.buft_input = llama_default_buffer_type_cpu(true);
  5202. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  5203. model.buft_layer.resize(n_layer);
  5204. // assign cpu layers
  5205. for (int i = 0; i < i_gpu_start; ++i) {
  5206. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  5207. }
  5208. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  5209. // calculate the split points
  5210. int device_count = llama_get_device_count(model);
  5211. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  5212. std::vector<float> splits(device_count);
  5213. if (all_zero) {
  5214. // default split, by free memory
  5215. for (int i = 0; i < device_count; ++i) {
  5216. splits[i] = llama_get_device_memory(model, i);
  5217. }
  5218. } else {
  5219. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  5220. }
  5221. // sum and normalize the splits to get the split points
  5222. float split_sum = 0.0f;
  5223. for (int i = 0; i < device_count; ++i) {
  5224. split_sum += splits[i];
  5225. splits[i] = split_sum;
  5226. }
  5227. for (int i = 0; i < device_count; ++i) {
  5228. splits[i] /= split_sum;
  5229. }
  5230. // assign the repeating layers to the devices according to the splits
  5231. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  5232. for (int i = i_gpu_start; i < n_layer; ++i) {
  5233. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  5234. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  5235. }
  5236. // assign the output layer
  5237. if (n_gpu_layers > n_layer) {
  5238. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  5239. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  5240. } else {
  5241. model.buft_output = llama_default_buffer_type_cpu(true);
  5242. }
  5243. } else {
  5244. ggml_backend_buffer_type_t split_buft;
  5245. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  5246. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  5247. } else {
  5248. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  5249. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  5250. }
  5251. // assign the repeating layers
  5252. for (int i = i_gpu_start; i < n_layer; ++i) {
  5253. model.buft_layer[i] = {
  5254. split_buft,
  5255. llama_default_buffer_type_offload(model, main_gpu)
  5256. };
  5257. }
  5258. // assign the output layer
  5259. if (n_gpu_layers > n_layer) {
  5260. model.buft_output = {
  5261. split_buft,
  5262. llama_default_buffer_type_offload(model, main_gpu)
  5263. };
  5264. } else {
  5265. model.buft_output = llama_default_buffer_type_cpu(true);
  5266. }
  5267. }
  5268. // count used buffer types
  5269. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  5270. buft_layer_count[model.buft_input.buft]++;
  5271. buft_layer_count[model.buft_input.buft_matrix]++;
  5272. buft_layer_count[model.buft_output.buft]++;
  5273. buft_layer_count[model.buft_output.buft_matrix]++;
  5274. for (int i = 0; i < n_layer; ++i) {
  5275. buft_layer_count[model.buft_layer[i].buft]++;
  5276. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  5277. }
  5278. // create one context per buffer type
  5279. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  5280. // for moe merged tensors
  5281. ctx_size += ggml_tensor_overhead()*n_layer*3;
  5282. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  5283. for (auto & it : buft_layer_count) {
  5284. struct ggml_init_params params = {
  5285. /*.mem_size =*/ ctx_size,
  5286. /*.mem_buffer =*/ NULL,
  5287. /*.no_alloc =*/ true,
  5288. };
  5289. ggml_context * ctx = ggml_init(params);
  5290. if (!ctx) {
  5291. throw std::runtime_error(format("failed to create context"));
  5292. }
  5293. ctx_map[it.first] = ctx;
  5294. model.ctxs.push_back(ctx);
  5295. }
  5296. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  5297. // create tensors for the weights
  5298. {
  5299. // note: cast to int64_t since we will use these for the tensor dimensions
  5300. const int64_t n_head = hparams.n_head();
  5301. const int64_t n_head_kv = hparams.n_head_kv();
  5302. const int64_t n_embd = hparams.n_embd;
  5303. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5304. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5305. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5306. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5307. const int64_t n_ff = hparams.n_ff();
  5308. const int64_t n_embd_gqa = n_embd_v_gqa;
  5309. const int64_t n_vocab = hparams.n_vocab;
  5310. const int64_t n_vocab_type = hparams.n_vocab_type;
  5311. const int64_t n_expert = hparams.n_expert;
  5312. const int64_t n_expert_used = hparams.n_expert_used;
  5313. const int64_t n_ctx_train = hparams.n_ctx_train;
  5314. if (n_expert > 0 && hparams.n_expert_used == 0) {
  5315. throw std::runtime_error("model has expert layers but no expert layers are used");
  5316. }
  5317. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  5318. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  5319. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  5320. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  5321. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  5322. model.layers.resize(n_layer);
  5323. const auto tn = LLM_TN(model.arch);
  5324. switch (model.arch) {
  5325. case LLM_ARCH_LLAMA:
  5326. case LLM_ARCH_REFACT:
  5327. case LLM_ARCH_MINICPM:
  5328. {
  5329. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5330. // output
  5331. {
  5332. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5333. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5334. // if output is NULL, init from the input tok embed
  5335. if (model.output == NULL) {
  5336. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5337. }
  5338. }
  5339. for (int i = 0; i < n_layer; ++i) {
  5340. ggml_context * ctx_layer = ctx_for_layer(i);
  5341. ggml_context * ctx_split = ctx_for_layer_split(i);
  5342. auto & layer = model.layers[i];
  5343. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5344. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  5345. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5346. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5347. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  5348. // optional bias tensors
  5349. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5350. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5351. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5352. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5353. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5354. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_embd/n_head/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  5355. if (n_expert == 0) {
  5356. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5357. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5358. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5359. // optional MLP bias
  5360. layer.ffn_gate_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5361. layer.ffn_down_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5362. layer.ffn_up_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5363. } else {
  5364. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5365. 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);
  5366. if (layer.ffn_gate_exps) {
  5367. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5368. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5369. } else {
  5370. // merge split expert into a single tensor for compatibility with older models
  5371. // requires disabling mmap
  5372. use_mmap_buffer = false;
  5373. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5374. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5375. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5376. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5377. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5378. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5379. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5380. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5381. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5382. for (uint32_t x = 0; x < n_expert; ++x) {
  5383. // the individual experts are loaded into a view of the merged tensor
  5384. 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);
  5385. 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);
  5386. 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);
  5387. }
  5388. }
  5389. }
  5390. }
  5391. } break;
  5392. case LLM_ARCH_GROK:
  5393. {
  5394. if (n_expert == 0) {
  5395. throw std::runtime_error("Grok model cannot have zero experts");
  5396. }
  5397. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5398. // output
  5399. {
  5400. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5401. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5402. // if output is NULL, init from the input tok embed
  5403. if (model.output == NULL) {
  5404. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5405. }
  5406. }
  5407. for (int i = 0; i < n_layer; ++i) {
  5408. ggml_context * ctx_layer = ctx_for_layer(i);
  5409. ggml_context * ctx_split = ctx_for_layer_split(i);
  5410. auto & layer = model.layers[i];
  5411. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5412. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5413. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5414. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5415. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5416. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5417. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5418. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5419. 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);
  5420. if (layer.ffn_gate_exps) {
  5421. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5422. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5423. } else {
  5424. // merge split expert into a single tensor for compatibility with older models
  5425. // requires disabling mmap
  5426. use_mmap_buffer = false;
  5427. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5428. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5429. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5430. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5431. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5432. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5433. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5434. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5435. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5436. for (uint32_t x = 0; x < n_expert; ++x) {
  5437. // the individual experts are loaded into a view of the merged tensor
  5438. 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);
  5439. 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);
  5440. 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);
  5441. }
  5442. }
  5443. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5444. }
  5445. } break;
  5446. case LLM_ARCH_DBRX:
  5447. {
  5448. if (n_expert == 0) {
  5449. throw std::runtime_error("DBRX model cannot have zero experts");
  5450. }
  5451. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5452. // output
  5453. {
  5454. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5455. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5456. }
  5457. for (int i = 0; i < n_layer; ++i) {
  5458. ggml_context * ctx_layer = ctx_for_layer(i);
  5459. ggml_context * ctx_split = ctx_for_layer_split(i);
  5460. auto & layer = model.layers[i];
  5461. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5462. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5463. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5464. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5465. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5466. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5467. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  5468. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5469. }
  5470. } break;
  5471. case LLM_ARCH_BAICHUAN:
  5472. {
  5473. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5474. {
  5475. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5476. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5477. }
  5478. for (int i = 0; i < n_layer; ++i) {
  5479. ggml_context * ctx_layer = ctx_for_layer(i);
  5480. ggml_context * ctx_split = ctx_for_layer_split(i);
  5481. auto & layer = model.layers[i];
  5482. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5483. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5484. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5485. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5486. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5487. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5488. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5489. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5490. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5491. }
  5492. } break;
  5493. case LLM_ARCH_FALCON:
  5494. {
  5495. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5496. // output
  5497. {
  5498. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5499. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5500. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5501. if (!model.output) {
  5502. 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
  5503. }
  5504. }
  5505. for (int i = 0; i < n_layer; ++i) {
  5506. ggml_context * ctx_layer = ctx_for_layer(i);
  5507. ggml_context * ctx_split = ctx_for_layer_split(i);
  5508. auto & layer = model.layers[i];
  5509. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5510. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5511. 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);
  5512. 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);
  5513. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5514. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5515. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5516. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5517. }
  5518. } break;
  5519. case LLM_ARCH_STARCODER:
  5520. {
  5521. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5522. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5523. // output
  5524. {
  5525. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5526. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5527. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5528. if (!model.output) {
  5529. // needs to be on GPU
  5530. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5531. }
  5532. }
  5533. for (int i = 0; i < n_layer; ++i) {
  5534. ggml_context * ctx_layer = ctx_for_layer(i);
  5535. ggml_context * ctx_split = ctx_for_layer_split(i);
  5536. auto & layer = model.layers[i];
  5537. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5538. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5539. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5540. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5541. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5542. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5543. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5544. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5545. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5546. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5547. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5548. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5549. }
  5550. } break;
  5551. case LLM_ARCH_BERT:
  5552. case LLM_ARCH_NOMIC_BERT:
  5553. {
  5554. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5555. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  5556. if (model.arch == LLM_ARCH_BERT) {
  5557. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5558. }
  5559. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5560. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5561. for (int i = 0; i < n_layer; ++i) {
  5562. ggml_context * ctx_layer = ctx_for_layer(i);
  5563. ggml_context * ctx_split = ctx_for_layer_split(i);
  5564. auto & layer = model.layers[i];
  5565. if (model.arch == LLM_ARCH_BERT) {
  5566. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5567. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5568. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5569. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5570. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5571. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5572. } else {
  5573. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5574. }
  5575. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5576. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5577. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5578. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5579. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5580. if (model.arch == LLM_ARCH_BERT) {
  5581. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5582. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5583. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5584. } else {
  5585. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5586. }
  5587. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5588. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5589. }
  5590. } break;
  5591. case LLM_ARCH_JINA_BERT_V2:
  5592. {
  5593. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  5594. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  5595. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  5596. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  5597. for (int i = 0; i < n_layer; ++i) {
  5598. ggml_context * ctx_layer = ctx_for_layer(i);
  5599. ggml_context * ctx_split = ctx_for_layer_split(i);
  5600. auto & layer = model.layers[i]; // JinaBertLayer
  5601. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5602. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5603. 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);
  5604. 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);
  5605. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5606. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5607. 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);
  5608. 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);
  5609. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5610. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5611. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  5612. layer.bo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  5613. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  5614. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5615. 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);
  5616. 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);
  5617. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5618. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5619. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5620. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5621. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5622. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5623. }
  5624. } break;
  5625. case LLM_ARCH_BLOOM:
  5626. {
  5627. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5628. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5629. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5630. // output
  5631. {
  5632. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5633. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5634. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5635. }
  5636. for (int i = 0; i < n_layer; ++i) {
  5637. ggml_context * ctx_layer = ctx_for_layer(i);
  5638. ggml_context * ctx_split = ctx_for_layer_split(i);
  5639. auto & layer = model.layers[i];
  5640. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5641. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5642. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5643. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5644. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5645. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5646. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5647. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5648. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5649. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5650. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5651. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5652. }
  5653. } break;
  5654. case LLM_ARCH_MPT:
  5655. {
  5656. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5657. 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);
  5658. // output
  5659. {
  5660. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5661. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5662. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5663. if (!model.output) {
  5664. 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
  5665. }
  5666. }
  5667. for (int i = 0; i < n_layer; ++i) {
  5668. ggml_context * ctx_layer = ctx_for_layer(i);
  5669. ggml_context * ctx_split = ctx_for_layer_split(i);
  5670. auto & layer = model.layers[i];
  5671. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5672. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5673. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5674. 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);
  5675. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5676. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5677. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5678. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5679. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5680. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5681. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5682. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5683. 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);
  5684. 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);
  5685. 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);
  5686. 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);
  5687. // AWQ ScaleActivation layer
  5688. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5689. }
  5690. } break;
  5691. case LLM_ARCH_STABLELM:
  5692. {
  5693. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5694. // output
  5695. {
  5696. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5697. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5698. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5699. }
  5700. for (int i = 0; i < n_layer; ++i) {
  5701. ggml_context * ctx_layer = ctx_for_layer(i);
  5702. ggml_context * ctx_split = ctx_for_layer_split(i);
  5703. auto & layer = model.layers[i];
  5704. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5705. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5706. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5707. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5708. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5709. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5710. // optional bias tensors, present in Stable LM 2 1.6B
  5711. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5712. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5713. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5714. // optional q and k layernorms, present in StableLM 2 12B
  5715. 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);
  5716. 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);
  5717. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  5718. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5719. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5720. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5721. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5722. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5723. }
  5724. } break;
  5725. case LLM_ARCH_QWEN:
  5726. {
  5727. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5728. // output
  5729. {
  5730. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5731. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5732. }
  5733. for (int i = 0; i < n_layer; ++i) {
  5734. ggml_context * ctx_layer = ctx_for_layer(i);
  5735. ggml_context * ctx_split = ctx_for_layer_split(i);
  5736. auto & layer = model.layers[i];
  5737. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5738. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  5739. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  5740. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5741. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5742. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  5743. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  5744. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  5745. }
  5746. } break;
  5747. case LLM_ARCH_QWEN2:
  5748. {
  5749. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5750. // output
  5751. {
  5752. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5753. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5754. // if output is NULL, init from the input tok embed
  5755. if (model.output == NULL) {
  5756. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5757. }
  5758. }
  5759. for (int i = 0; i < n_layer; ++i) {
  5760. ggml_context * ctx_layer = ctx_for_layer(i);
  5761. ggml_context * ctx_split = ctx_for_layer_split(i);
  5762. auto & layer = model.layers[i];
  5763. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5764. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5765. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5766. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5767. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5768. // optional bias tensors
  5769. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5770. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5771. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5772. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5773. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5774. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5775. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5776. }
  5777. } break;
  5778. case LLM_ARCH_QWEN2MOE:
  5779. {
  5780. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5781. // output
  5782. {
  5783. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5784. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5785. }
  5786. for (int i = 0; i < n_layer; ++i) {
  5787. ggml_context * ctx_layer = ctx_for_layer(i);
  5788. ggml_context * ctx_split = ctx_for_layer_split(i);
  5789. auto & layer = model.layers[i];
  5790. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5791. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5792. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5793. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5794. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5795. // optional bias tensors
  5796. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5797. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5798. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5799. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5800. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5801. GGML_ASSERT(n_expert > 0);
  5802. GGML_ASSERT(n_expert_used > 0);
  5803. // MoE branch
  5804. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  5805. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5806. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  5807. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5808. // Shared expert branch
  5809. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  5810. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  5811. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5812. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  5813. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5814. }
  5815. } break;
  5816. case LLM_ARCH_PHI2:
  5817. {
  5818. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5819. // output
  5820. {
  5821. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5822. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5823. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5824. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  5825. }
  5826. for (int i = 0; i < n_layer; ++i) {
  5827. ggml_context * ctx_layer = ctx_for_layer(i);
  5828. ggml_context * ctx_split = ctx_for_layer_split(i);
  5829. auto & layer = model.layers[i];
  5830. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5831. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5832. 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);
  5833. 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);
  5834. if (layer.wqkv == nullptr) {
  5835. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5836. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5837. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5838. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5839. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5840. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5841. }
  5842. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5843. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5844. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5845. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5846. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5847. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5848. }
  5849. } break;
  5850. case LLM_ARCH_PHI3:
  5851. {
  5852. const int64_t n_embd_head = n_embd / n_head;
  5853. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  5854. // output
  5855. {
  5856. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  5857. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  5858. }
  5859. for (int i = 0; i < n_layer; ++i) {
  5860. ggml_context * ctx_layer = ctx_for_layer(i);
  5861. ggml_context * ctx_split = ctx_for_layer_split(i);
  5862. auto & layer = model.layers[i];
  5863. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  5864. 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);
  5865. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  5866. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  5867. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  5868. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  5869. 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));
  5870. 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));
  5871. }
  5872. } break;
  5873. case LLM_ARCH_PLAMO:
  5874. {
  5875. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5876. // output
  5877. {
  5878. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5879. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5880. }
  5881. for (int i = 0; i < n_layer; ++i) {
  5882. ggml_context * ctx_layer = ctx_for_layer(i);
  5883. ggml_context * ctx_split = ctx_for_layer_split(i);
  5884. auto & layer = model.layers[i];
  5885. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5886. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5887. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5888. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5889. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5890. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5891. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5892. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5893. }
  5894. } break;
  5895. case LLM_ARCH_GPT2:
  5896. {
  5897. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5898. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5899. // output
  5900. {
  5901. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5902. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5903. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5904. }
  5905. for (int i = 0; i < n_layer; ++i) {
  5906. ggml_context * ctx_layer = ctx_for_layer(i);
  5907. ggml_context * ctx_split = ctx_for_layer_split(i);
  5908. auto & layer = model.layers[i];
  5909. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5910. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5911. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5912. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5913. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5914. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5915. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5916. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5917. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5918. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5919. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5920. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5921. }
  5922. } break;
  5923. case LLM_ARCH_CODESHELL:
  5924. {
  5925. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5926. // output
  5927. {
  5928. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5929. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5930. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5931. }
  5932. for (int i = 0; i < n_layer; ++i) {
  5933. ggml_context * ctx_layer = ctx_for_layer(i);
  5934. ggml_context * ctx_split = ctx_for_layer_split(i);
  5935. auto & layer = model.layers[i];
  5936. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5937. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5938. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5939. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5940. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5941. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5942. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5943. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5944. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5945. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5946. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5947. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5948. }
  5949. } break;
  5950. case LLM_ARCH_ORION:
  5951. {
  5952. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5953. {
  5954. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5955. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5956. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5957. }
  5958. for (int i = 0; i < n_layer; ++i) {
  5959. ggml_context * ctx_layer = ctx_for_layer(i);
  5960. ggml_context * ctx_split = ctx_for_layer_split(i);
  5961. auto & layer = model.layers[i];
  5962. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5963. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5964. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5965. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5966. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5967. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5968. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5969. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5970. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5971. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5972. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5973. }
  5974. } break;
  5975. case LLM_ARCH_INTERNLM2:
  5976. {
  5977. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5978. // output
  5979. {
  5980. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5981. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5982. }
  5983. for (int i = 0; i < n_layer; ++i) {
  5984. ggml_context * ctx_layer = ctx_for_layer(i);
  5985. ggml_context * ctx_split = ctx_for_layer_split(i);
  5986. auto & layer = model.layers[i];
  5987. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5988. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5989. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5990. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5991. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5992. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5993. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5994. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5995. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5996. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5997. }
  5998. } break;
  5999. case LLM_ARCH_GEMMA:
  6000. {
  6001. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6002. // output
  6003. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6004. 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
  6005. for (int i = 0; i < n_layer; ++i) {
  6006. ggml_context * ctx_layer = ctx_for_layer(i);
  6007. ggml_context * ctx_split = ctx_for_layer_split(i);
  6008. auto & layer = model.layers[i];
  6009. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6010. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6011. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6012. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6013. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6014. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6015. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6016. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6017. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6018. }
  6019. } break;
  6020. case LLM_ARCH_GEMMA2:
  6021. {
  6022. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6023. // output
  6024. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6025. 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
  6026. for (int i = 0; i < n_layer; ++i) {
  6027. ggml_context * ctx_layer = ctx_for_layer(i);
  6028. ggml_context * ctx_split = ctx_for_layer_split(i);
  6029. auto & layer = model.layers[i];
  6030. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6031. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6032. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6033. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6034. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6035. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  6036. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6037. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6038. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6039. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6040. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  6041. }
  6042. } break;
  6043. case LLM_ARCH_STARCODER2:
  6044. {
  6045. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6046. // output
  6047. {
  6048. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6049. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6050. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6051. // if output is NULL, init from the input tok embed
  6052. if (model.output == NULL) {
  6053. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6054. }
  6055. }
  6056. for (int i = 0; i < n_layer; ++i) {
  6057. ggml_context * ctx_layer = ctx_for_layer(i);
  6058. ggml_context * ctx_split = ctx_for_layer_split(i);
  6059. auto & layer = model.layers[i];
  6060. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6061. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6062. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6063. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6064. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6065. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6066. // optional bias tensors
  6067. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6068. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6069. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6070. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6071. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6072. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6073. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6074. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6075. // optional bias tensors
  6076. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6077. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  6078. }
  6079. } break;
  6080. case LLM_ARCH_MAMBA:
  6081. {
  6082. const int64_t d_conv = hparams.ssm_d_conv;
  6083. const int64_t d_inner = hparams.ssm_d_inner;
  6084. const int64_t d_state = hparams.ssm_d_state;
  6085. const int64_t dt_rank = hparams.ssm_dt_rank;
  6086. // only an expansion factor of 2 is supported for now
  6087. GGML_ASSERT(2 * n_embd == d_inner);
  6088. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6089. // output
  6090. {
  6091. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6092. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6093. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  6094. if (model.output == NULL) {
  6095. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6096. }
  6097. }
  6098. for (int i = 0; i < n_layer; ++i) {
  6099. ggml_context * ctx_layer = ctx_for_layer(i);
  6100. ggml_context * ctx_split = ctx_for_layer_split(i);
  6101. auto & layer = model.layers[i];
  6102. // norm
  6103. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6104. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  6105. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  6106. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  6107. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  6108. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  6109. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  6110. // no "weight" suffix for these
  6111. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  6112. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  6113. // out_proj
  6114. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  6115. }
  6116. } break;
  6117. case LLM_ARCH_XVERSE:
  6118. {
  6119. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6120. {
  6121. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6122. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6123. }
  6124. for (int i = 0; i < n_layer; ++i) {
  6125. ggml_context * ctx_layer = ctx_for_layer(i);
  6126. ggml_context * ctx_split = ctx_for_layer_split(i);
  6127. auto & layer = model.layers[i];
  6128. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6129. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6130. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6131. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6132. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6133. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6134. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6135. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6136. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6137. }
  6138. } break;
  6139. case LLM_ARCH_COMMAND_R:
  6140. {
  6141. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6142. // output
  6143. {
  6144. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6145. // init output from the input tok embed
  6146. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6147. }
  6148. for (int i = 0; i < n_layer; ++i) {
  6149. ggml_context * ctx_layer = ctx_for_layer(i);
  6150. ggml_context * ctx_split = ctx_for_layer_split(i);
  6151. auto & layer = model.layers[i];
  6152. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6153. if (n_layer >= 64){
  6154. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  6155. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  6156. }
  6157. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6158. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6159. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6160. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6161. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6162. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6163. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6164. }
  6165. } break;
  6166. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  6167. {
  6168. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6169. // output
  6170. {
  6171. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6172. // if output is NULL, init from the input tok embed
  6173. if (model.output == NULL) {
  6174. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6175. }
  6176. }
  6177. for (int i = 0; i < n_layer; ++i) {
  6178. ggml_context * ctx_split = ctx_for_layer_split(i);
  6179. auto & layer = model.layers[i];
  6180. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6181. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6182. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6183. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6184. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6185. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6186. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6187. }
  6188. } break;
  6189. case LLM_ARCH_OPENELM:
  6190. {
  6191. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6192. // output
  6193. {
  6194. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6195. // init output from the input tok embed
  6196. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6197. }
  6198. for (int i = 0; i < n_layer; ++i) {
  6199. const int64_t n_head = hparams.n_head(i);
  6200. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  6201. const int64_t n_ff = hparams.n_ff(i);
  6202. ggml_context * ctx_layer = ctx_for_layer(i);
  6203. ggml_context * ctx_split = ctx_for_layer_split(i);
  6204. auto & layer = model.layers[i];
  6205. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6206. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  6207. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  6208. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  6209. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  6210. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6211. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6212. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6213. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6214. }
  6215. } break;
  6216. case LLM_ARCH_GPTNEOX:
  6217. {
  6218. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6219. // output
  6220. {
  6221. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6222. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6223. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6224. }
  6225. for (int i = 0; i < n_layer; ++i) {
  6226. ggml_context * ctx_layer = ctx_for_layer(i);
  6227. ggml_context * ctx_split = ctx_for_layer_split(i);
  6228. auto & layer = model.layers[i];
  6229. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6230. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6231. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6232. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6233. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6234. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6235. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6236. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6237. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6238. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6239. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6240. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6241. }
  6242. } break;
  6243. case LLM_ARCH_ARCTIC:
  6244. {
  6245. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6246. // output
  6247. {
  6248. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6249. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6250. // if output is NULL, init from the input tok embed
  6251. if (model.output == NULL) {
  6252. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6253. }
  6254. }
  6255. for (int i = 0; i < n_layer; ++i) {
  6256. ggml_context * ctx_layer = ctx_for_layer(i);
  6257. ggml_context * ctx_split = ctx_for_layer_split(i);
  6258. auto & layer = model.layers[i];
  6259. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6260. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6261. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6262. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6263. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6264. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6265. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  6266. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  6267. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  6268. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6269. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  6270. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  6271. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6272. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6273. }
  6274. } break;
  6275. case LLM_ARCH_DEEPSEEK2:
  6276. {
  6277. const bool is_lite = (hparams.n_layer == 27);
  6278. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6279. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6280. const int64_t q_lora_rank = hparams.n_lora_q;
  6281. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6282. const int64_t n_ff_exp = hparams.n_ff_exp;
  6283. const int64_t n_expert_shared = hparams.n_expert_shared;
  6284. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6285. // output
  6286. {
  6287. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6288. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6289. }
  6290. for (int i = 0; i < n_layer; ++i) {
  6291. ggml_context * ctx_layer = ctx_for_layer(i);
  6292. ggml_context * ctx_split = ctx_for_layer_split(i);
  6293. auto & layer = model.layers[i];
  6294. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6295. if (!is_lite) {
  6296. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6297. }
  6298. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6299. if (!is_lite) {
  6300. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6301. 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});
  6302. } else {
  6303. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6304. }
  6305. 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)});
  6306. 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)});
  6307. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6308. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6309. if (i < (int) hparams.n_layer_dense_lead) {
  6310. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6311. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6312. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6313. } else {
  6314. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6315. GGML_ASSERT(n_expert > 0);
  6316. GGML_ASSERT(n_expert_used > 0);
  6317. // MoE branch
  6318. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6319. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6320. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6321. // Shared expert branch
  6322. 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});
  6323. 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});
  6324. 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});
  6325. }
  6326. }
  6327. } break;
  6328. case LLM_ARCH_BITNET:
  6329. {
  6330. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6331. // output
  6332. {
  6333. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6334. }
  6335. for (int i = 0; i < n_layer; ++i) {
  6336. ggml_context * ctx_layer = ctx_for_layer(i);
  6337. ggml_context * ctx_split = ctx_for_layer_split(i);
  6338. auto & layer = model.layers[i];
  6339. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6340. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  6341. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6342. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1});
  6343. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6344. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1});
  6345. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6346. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1});
  6347. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6348. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1});
  6349. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6350. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  6351. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6352. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1});
  6353. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6354. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1});
  6355. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6356. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1});
  6357. }
  6358. } break;
  6359. case LLM_ARCH_T5:
  6360. {
  6361. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  6362. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6363. // output
  6364. {
  6365. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  6366. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  6367. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6368. // if output is NULL, init from the input tok embed
  6369. if (model.output == NULL) {
  6370. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6371. }
  6372. }
  6373. for (int i = 0; i < n_layer; ++i) {
  6374. ggml_context * ctx_layer = ctx_for_layer(i);
  6375. ggml_context * ctx_split = ctx_for_layer_split(i);
  6376. auto & layer = model.layers[i];
  6377. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  6378. 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);
  6379. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6380. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6381. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6382. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6383. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  6384. 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);
  6385. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6386. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  6387. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  6388. 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);
  6389. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6390. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6391. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6392. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6393. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  6394. // this tensor seems to be unused in HF transformers implementation
  6395. 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);
  6396. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6397. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6398. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6399. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6400. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  6401. 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);
  6402. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6403. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  6404. }
  6405. } break;
  6406. case LLM_ARCH_JAIS:
  6407. {
  6408. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6409. // Output
  6410. {
  6411. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6412. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6413. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6414. }
  6415. for (int i = 0; i < n_layer; ++i) {
  6416. ggml_context * ctx_layer = ctx_for_layer(i);
  6417. ggml_context * ctx_split = ctx_for_layer_split(i);
  6418. auto & layer = model.layers[i];
  6419. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6420. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6421. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6422. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6423. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6424. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6425. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6426. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6427. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6428. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6429. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6430. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  6431. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6432. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6433. }
  6434. } break;
  6435. case LLM_ARCH_CHATGLM:
  6436. {
  6437. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6438. // output
  6439. {
  6440. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6441. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6442. }
  6443. for (int i = 0; i < n_layer; ++i) {
  6444. ggml_context * ctx_layer = ctx_for_layer(i);
  6445. ggml_context * ctx_split = ctx_for_layer_split(i);
  6446. auto & layer = model.layers[i];
  6447. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6448. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + (hparams.n_embd_head_k << 2)});
  6449. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + (hparams.n_embd_head_k << 2)});
  6450. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6451. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6452. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  6453. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6454. }
  6455. } break;
  6456. default:
  6457. throw std::runtime_error("unknown architecture");
  6458. }
  6459. }
  6460. ml.done_getting_tensors();
  6461. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  6462. model.mappings.reserve(ml.mappings.size());
  6463. // create the backend buffers
  6464. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  6465. ctx_bufs.reserve(ctx_map.size());
  6466. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  6467. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  6468. model.bufs.reserve(n_max_backend_buffer);
  6469. for (auto & it : ctx_map) {
  6470. ggml_backend_buffer_type_t buft = it.first;
  6471. ggml_context * ctx = it.second;
  6472. llama_buf_map bufs;
  6473. bufs.reserve(n_max_backend_buffer);
  6474. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  6475. // 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
  6476. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  6477. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  6478. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6479. void * addr = nullptr;
  6480. size_t first, last;
  6481. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6482. if (first >= last) {
  6483. continue;
  6484. }
  6485. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  6486. if (buf == nullptr) {
  6487. throw std::runtime_error("unable to allocate backend CPU buffer");
  6488. }
  6489. model.bufs.push_back(buf);
  6490. bufs.emplace(idx, buf);
  6491. #ifdef GGML_USE_CUDA
  6492. if (n_layer >= n_gpu_layers) {
  6493. ggml_backend_cuda_register_host_buffer(
  6494. ggml_backend_buffer_get_base(buf),
  6495. ggml_backend_buffer_get_size(buf));
  6496. }
  6497. #endif
  6498. }
  6499. }
  6500. #ifdef GGML_USE_METAL
  6501. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  6502. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6503. const size_t max_size = ggml_get_max_tensor_size(ctx);
  6504. void * addr = nullptr;
  6505. size_t first, last;
  6506. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6507. if (first >= last) {
  6508. continue;
  6509. }
  6510. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  6511. if (buf == nullptr) {
  6512. throw std::runtime_error("unable to allocate backend metal buffer");
  6513. }
  6514. model.bufs.push_back(buf);
  6515. bufs.emplace(idx, buf);
  6516. }
  6517. }
  6518. #endif
  6519. else {
  6520. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  6521. if (buf == nullptr) {
  6522. throw std::runtime_error("unable to allocate backend buffer");
  6523. }
  6524. model.bufs.push_back(buf);
  6525. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  6526. model.mlock_bufs.emplace_back(new llama_mlock);
  6527. auto & mlock_buf = model.mlock_bufs.back();
  6528. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  6529. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  6530. }
  6531. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6532. bufs.emplace(idx, buf);
  6533. }
  6534. }
  6535. if (bufs.empty()) {
  6536. throw std::runtime_error("failed to allocate buffer");
  6537. }
  6538. for (auto & buf : bufs) {
  6539. // indicate that this buffer contains weights
  6540. // 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
  6541. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  6542. }
  6543. ctx_bufs.emplace_back(ctx, bufs);
  6544. }
  6545. if (llama_supports_gpu_offload()) {
  6546. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  6547. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  6548. if (n_gpu_layers > (int) hparams.n_layer) {
  6549. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  6550. }
  6551. const int max_backend_supported_layers = hparams.n_layer + 1;
  6552. const int max_offloadable_layers = hparams.n_layer + 1;
  6553. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  6554. }
  6555. // print memory requirements
  6556. for (ggml_backend_buffer_t buf : model.bufs) {
  6557. 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);
  6558. }
  6559. // populate tensors_by_name
  6560. for (ggml_context * ctx : model.ctxs) {
  6561. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  6562. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  6563. }
  6564. }
  6565. // load tensor data
  6566. for (auto & it : ctx_bufs) {
  6567. ggml_context * ctx = it.first;
  6568. auto & bufs = it.second;
  6569. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  6570. return false;
  6571. }
  6572. }
  6573. if (use_mmap_buffer) {
  6574. for (auto & mapping : ml.mappings) {
  6575. model.mappings.emplace_back(std::move(mapping));
  6576. }
  6577. }
  6578. // loading time will be recalculate after the first eval, so
  6579. // we take page faults deferred by mmap() into consideration
  6580. model.t_load_us = ggml_time_us() - model.t_start_us;
  6581. return true;
  6582. }
  6583. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  6584. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  6585. try {
  6586. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  6587. model.hparams.vocab_only = params.vocab_only;
  6588. try {
  6589. llm_load_arch(ml, model);
  6590. } catch(const std::exception & e) {
  6591. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  6592. }
  6593. try {
  6594. llm_load_hparams(ml, model);
  6595. } catch(const std::exception & e) {
  6596. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  6597. }
  6598. try {
  6599. llm_load_vocab(ml, model);
  6600. } catch(const std::exception & e) {
  6601. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  6602. }
  6603. llm_load_print_meta(ml, model);
  6604. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  6605. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  6606. throw std::runtime_error("vocab size mismatch");
  6607. }
  6608. if (params.vocab_only) {
  6609. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  6610. return 0;
  6611. }
  6612. #ifdef GGML_USE_KOMPUTE
  6613. if (params.n_gpu_layers > 0 && (
  6614. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  6615. || !(
  6616. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  6617. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  6618. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  6619. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  6620. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  6621. )
  6622. )) {
  6623. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  6624. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  6625. params.n_gpu_layers = 0;
  6626. }
  6627. #endif
  6628. if (!llm_load_tensors(
  6629. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  6630. params.progress_callback, params.progress_callback_user_data
  6631. )) {
  6632. return -2;
  6633. }
  6634. } catch (const std::exception & err) {
  6635. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  6636. return -1;
  6637. }
  6638. return 0;
  6639. }
  6640. //
  6641. // llm_build
  6642. //
  6643. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  6644. enum llm_ffn_op_type {
  6645. LLM_FFN_SILU,
  6646. LLM_FFN_GELU,
  6647. LLM_FFN_RELU,
  6648. LLM_FFN_RELU_SQR,
  6649. LLM_FFN_SWIGLU,
  6650. };
  6651. enum llm_ffn_gate_type {
  6652. LLM_FFN_SEQ,
  6653. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  6654. };
  6655. enum llm_norm_type {
  6656. LLM_NORM,
  6657. LLM_NORM_RMS,
  6658. };
  6659. static struct ggml_tensor * llm_build_inp_embd(
  6660. struct ggml_context * ctx,
  6661. struct llama_context & lctx,
  6662. const llama_hparams & hparams,
  6663. const llama_batch & batch,
  6664. struct ggml_tensor * tok_embd,
  6665. const llm_build_cb & cb) {
  6666. const int64_t n_embd = hparams.n_embd;
  6667. struct ggml_tensor * inpL;
  6668. if (batch.token) {
  6669. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  6670. cb(lctx.inp_tokens, "inp_tokens", -1);
  6671. ggml_set_input(lctx.inp_tokens);
  6672. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  6673. } else {
  6674. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  6675. inpL = lctx.inp_embd;
  6676. ggml_set_input(lctx.inp_embd);
  6677. }
  6678. cb(inpL, "inp_embd", -1);
  6679. return inpL;
  6680. }
  6681. static void llm_build_kv_store(
  6682. struct ggml_context * ctx,
  6683. const llama_hparams & hparams,
  6684. const llama_cparams & cparams,
  6685. const llama_kv_cache & kv,
  6686. struct ggml_cgraph * graph,
  6687. struct ggml_tensor * k_cur,
  6688. struct ggml_tensor * v_cur,
  6689. int32_t n_tokens,
  6690. int32_t kv_head,
  6691. const llm_build_cb & cb,
  6692. int64_t il) {
  6693. const int64_t n_ctx = cparams.n_ctx;
  6694. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  6695. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  6696. GGML_ASSERT(kv.size == n_ctx);
  6697. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  6698. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  6699. cb(k_cache_view, "k_cache_view", il);
  6700. // note: storing RoPE-ed version of K in the KV cache
  6701. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  6702. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  6703. struct ggml_tensor * v_cache_view = nullptr;
  6704. if (cparams.flash_attn) {
  6705. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  6706. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  6707. } else {
  6708. // note: the V cache is transposed when not using flash attention
  6709. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  6710. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  6711. (kv_head)*ggml_element_size(kv.v_l[il]));
  6712. v_cur = ggml_transpose(ctx, v_cur);
  6713. }
  6714. cb(v_cache_view, "v_cache_view", il);
  6715. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  6716. }
  6717. // do mat_mul, while optionally apply lora
  6718. static struct ggml_tensor * llm_build_lora_mm(
  6719. struct llama_context & lctx,
  6720. struct ggml_context * ctx0,
  6721. struct ggml_tensor * w,
  6722. struct ggml_tensor * cur) {
  6723. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  6724. for (auto & it : lctx.lora_adapters) {
  6725. struct llama_lora_weight * lora = it.first->get_weight(w);
  6726. if (lora == nullptr) {
  6727. continue;
  6728. }
  6729. const float alpha = it.first->alpha;
  6730. const float rank = (float) lora->b->ne[0];
  6731. const float scale = alpha ? it.second * alpha / rank : it.second;
  6732. struct ggml_tensor * ab_cur = ggml_mul_mat(
  6733. ctx0, lora->b,
  6734. ggml_mul_mat(ctx0, lora->a, cur)
  6735. );
  6736. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6737. res = ggml_add(ctx0, res, ab_cur);
  6738. }
  6739. return res;
  6740. }
  6741. // do mat_mul_id, while optionally apply lora
  6742. static struct ggml_tensor * llm_build_lora_mm_id(
  6743. struct llama_context & lctx,
  6744. struct ggml_context * ctx0,
  6745. struct ggml_tensor * w, // struct ggml_tensor * as
  6746. struct ggml_tensor * cur, // struct ggml_tensor * b
  6747. struct ggml_tensor * ids) {
  6748. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  6749. for (auto & it : lctx.lora_adapters) {
  6750. struct llama_lora_weight * lora = it.first->get_weight(w);
  6751. if (lora == nullptr) {
  6752. continue;
  6753. }
  6754. const float alpha = it.first->alpha;
  6755. const float rank = (float) lora->b->ne[0];
  6756. const float scale = alpha ? it.second * alpha / rank : it.second;
  6757. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  6758. ctx0, lora->b,
  6759. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  6760. ids
  6761. );
  6762. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6763. res = ggml_add(ctx0, res, ab_cur);
  6764. }
  6765. return res;
  6766. }
  6767. static struct ggml_tensor * llm_build_norm(
  6768. struct ggml_context * ctx,
  6769. struct ggml_tensor * cur,
  6770. const llama_hparams & hparams,
  6771. struct ggml_tensor * mw,
  6772. struct ggml_tensor * mb,
  6773. llm_norm_type type,
  6774. const llm_build_cb & cb,
  6775. int il) {
  6776. switch (type) {
  6777. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  6778. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  6779. }
  6780. if (mw || mb) {
  6781. cb(cur, "norm", il);
  6782. }
  6783. if (mw) {
  6784. cur = ggml_mul(ctx, cur, mw);
  6785. if (mb) {
  6786. cb(cur, "norm_w", il);
  6787. }
  6788. }
  6789. if (mb) {
  6790. cur = ggml_add(ctx, cur, mb);
  6791. }
  6792. return cur;
  6793. }
  6794. static struct ggml_tensor * llm_build_ffn(
  6795. struct ggml_context * ctx,
  6796. struct llama_context & lctx,
  6797. struct ggml_tensor * cur,
  6798. struct ggml_tensor * up,
  6799. struct ggml_tensor * up_b,
  6800. struct ggml_tensor * up_s,
  6801. struct ggml_tensor * gate,
  6802. struct ggml_tensor * gate_b,
  6803. struct ggml_tensor * gate_s,
  6804. struct ggml_tensor * down,
  6805. struct ggml_tensor * down_b,
  6806. struct ggml_tensor * down_s,
  6807. struct ggml_tensor * act_scales,
  6808. llm_ffn_op_type type_op,
  6809. llm_ffn_gate_type type_gate,
  6810. const llm_build_cb & cb,
  6811. int il) {
  6812. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  6813. cb(tmp, "ffn_up", il);
  6814. if (up_b) {
  6815. tmp = ggml_add(ctx, tmp, up_b);
  6816. cb(tmp, "ffn_up_b", il);
  6817. }
  6818. if (up_s) {
  6819. tmp = ggml_mul(ctx, tmp, up_s);
  6820. cb(tmp, "ffn_up_s", il);
  6821. }
  6822. if (gate) {
  6823. switch (type_gate) {
  6824. case LLM_FFN_SEQ:
  6825. {
  6826. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  6827. cb(cur, "ffn_gate", il);
  6828. } break;
  6829. case LLM_FFN_PAR:
  6830. {
  6831. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  6832. cb(cur, "ffn_gate", il);
  6833. } break;
  6834. }
  6835. if (gate_b) {
  6836. cur = ggml_add(ctx, cur, gate_b);
  6837. cb(cur, "ffn_gate_b", il);
  6838. }
  6839. if (gate_s) {
  6840. cur = ggml_mul(ctx, cur, gate_s);
  6841. cb(cur, "ffn_gate_s", il);
  6842. }
  6843. } else {
  6844. cur = tmp;
  6845. }
  6846. switch (type_op) {
  6847. case LLM_FFN_SILU:
  6848. {
  6849. cur = ggml_silu(ctx, cur);
  6850. cb(cur, "ffn_silu", il);
  6851. } break;
  6852. case LLM_FFN_GELU:
  6853. {
  6854. cur = ggml_gelu(ctx, cur);
  6855. cb(cur, "ffn_gelu", il);
  6856. if (act_scales != NULL) {
  6857. cur = ggml_div(ctx, cur, act_scales);
  6858. cb(cur, "ffn_act", il);
  6859. }
  6860. } break;
  6861. case LLM_FFN_RELU:
  6862. {
  6863. cur = ggml_relu(ctx, cur);
  6864. cb(cur, "ffn_relu", il);
  6865. } break;
  6866. case LLM_FFN_RELU_SQR:
  6867. {
  6868. cur = ggml_relu(ctx, cur);
  6869. cb(cur, "ffn_relu", il);
  6870. cur = ggml_sqr(ctx, cur);
  6871. cb(cur, "ffn_sqr(relu)", il);
  6872. } break;
  6873. case LLM_FFN_SWIGLU:
  6874. {
  6875. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  6876. int64_t split_point = cur->ne[0] / 2;
  6877. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  6878. 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)));
  6879. x0 = ggml_silu(ctx, x0);
  6880. cb(cur, "ffn_silu", il);
  6881. cur = ggml_mul(ctx, x0, x1);
  6882. cb(cur, "ffn_mul", il);
  6883. } break;
  6884. }
  6885. if (type_gate == LLM_FFN_PAR) {
  6886. cur = ggml_mul(ctx, cur, tmp);
  6887. cb(cur, "ffn_gate_par", il);
  6888. }
  6889. if (down) {
  6890. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  6891. }
  6892. if (down_b) {
  6893. cb(cur, "ffn_down", il);
  6894. }
  6895. if (down_b) {
  6896. cur = ggml_add(ctx, cur, down_b);
  6897. }
  6898. if (down_s) {
  6899. cur = ggml_mul(ctx, cur, down_s);
  6900. cb(cur, "ffn_down_s", il);
  6901. }
  6902. return cur;
  6903. }
  6904. static struct ggml_tensor * llm_build_moe_ffn(
  6905. struct ggml_context * ctx,
  6906. struct llama_context & lctx,
  6907. struct ggml_tensor * cur,
  6908. struct ggml_tensor * gate_inp,
  6909. struct ggml_tensor * up_exps,
  6910. struct ggml_tensor * gate_exps,
  6911. struct ggml_tensor * down_exps,
  6912. int64_t n_expert,
  6913. int64_t n_expert_used,
  6914. llm_ffn_op_type type_op,
  6915. bool norm_w,
  6916. bool scale_w,
  6917. float w_scale,
  6918. const llm_build_cb & cb,
  6919. int il) {
  6920. int64_t n_embd = cur->ne[0];
  6921. int64_t n_tokens = cur->ne[1];
  6922. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  6923. cb(logits, "ffn_moe_logits", il);
  6924. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  6925. cb(probs, "ffn_moe_probs", il);
  6926. // select experts
  6927. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  6928. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  6929. cb(selected_experts, "ffn_moe_topk", il);
  6930. ggml_tensor * weights = ggml_get_rows(ctx,
  6931. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  6932. cb(weights, "ffn_moe_weights", il);
  6933. if (norm_w) {
  6934. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  6935. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  6936. cb(weights_sum, "ffn_moe_weights_sum", il);
  6937. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  6938. cb(weights, "ffn_moe_weights_norm", il);
  6939. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  6940. }
  6941. if (scale_w) {
  6942. weights = ggml_scale(ctx, weights, w_scale);
  6943. cb(weights, "ffn_moe_weights_scaled", il);
  6944. }
  6945. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  6946. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6947. cb(up, "ffn_moe_up", il);
  6948. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6949. cb(gate, "ffn_moe_gate", il);
  6950. switch (type_op) {
  6951. case LLM_FFN_SILU:
  6952. {
  6953. gate = ggml_silu(ctx, gate);
  6954. cb(gate, "ffn_moe_silu", il);
  6955. } break;
  6956. case LLM_FFN_GELU:
  6957. {
  6958. gate = ggml_gelu(ctx, gate);
  6959. cb(gate, "ffn_moe_gelu", il);
  6960. } break;
  6961. default:
  6962. GGML_ABORT("fatal error");
  6963. }
  6964. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  6965. cb(par, "ffn_moe_gate_par", il);
  6966. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  6967. cb(experts, "ffn_moe_down", il);
  6968. experts = ggml_mul(ctx, experts, weights);
  6969. // aggregate experts
  6970. ggml_tensor * moe_out = nullptr;
  6971. for (int i = 0; i < n_expert_used; ++i) {
  6972. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  6973. experts->nb[2], i*experts->nb[1]);
  6974. if (i == 0) {
  6975. moe_out = cur_expert;
  6976. } else {
  6977. moe_out = ggml_add(ctx, moe_out, cur_expert);
  6978. }
  6979. }
  6980. if (n_expert_used == 1) {
  6981. // avoid returning a non-contiguous tensor
  6982. moe_out = ggml_cont(ctx, moe_out);
  6983. }
  6984. return moe_out;
  6985. }
  6986. static struct ggml_tensor * llm_build_kqv(
  6987. struct ggml_context * ctx,
  6988. struct llama_context & lctx,
  6989. const llama_kv_cache & kv,
  6990. struct ggml_cgraph * graph,
  6991. struct ggml_tensor * wo,
  6992. struct ggml_tensor * wo_b,
  6993. struct ggml_tensor * q_cur,
  6994. struct ggml_tensor * kq_mask,
  6995. int32_t n_tokens,
  6996. int32_t n_kv,
  6997. float kq_scale,
  6998. const llm_build_cb & cb,
  6999. int il) {
  7000. const llama_model & model = lctx.model;
  7001. const llama_hparams & hparams = lctx.model.hparams;
  7002. const llama_cparams & cparams = lctx.cparams;
  7003. const int64_t n_ctx = cparams.n_ctx;
  7004. const int64_t n_head = hparams.n_head(il);
  7005. const int64_t n_head_kv = hparams.n_head_kv(il);
  7006. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7007. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7008. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  7009. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7010. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  7011. cb(q, "q", il);
  7012. struct ggml_tensor * k =
  7013. ggml_view_3d(ctx, kv.k_l[il],
  7014. n_embd_head_k, n_kv, n_head_kv,
  7015. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  7016. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  7017. 0);
  7018. cb(k, "k", il);
  7019. struct ggml_tensor * cur;
  7020. if (cparams.flash_attn) {
  7021. GGML_UNUSED(model);
  7022. GGML_UNUSED(n_ctx);
  7023. // split cached v into n_head heads (not transposed)
  7024. struct ggml_tensor * v =
  7025. ggml_view_3d(ctx, kv.v_l[il],
  7026. n_embd_head_v, n_kv, n_head_kv,
  7027. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  7028. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  7029. 0);
  7030. cb(v, "v", il);
  7031. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7032. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX) {
  7033. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  7034. }
  7035. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  7036. } else {
  7037. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  7038. cb(kq, "kq", il);
  7039. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_QWEN2) {
  7040. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  7041. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  7042. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7043. }
  7044. if (model.arch == LLM_ARCH_GROK) {
  7045. // need to do the following:
  7046. // multiply by attn_output_multiplyer of 0.08838834764831845
  7047. // and then :
  7048. // kq = 30 * tanh(kq / 30)
  7049. // before the softmax below
  7050. //try from phi2
  7051. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7052. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  7053. kq = ggml_scale(ctx, kq, 30);
  7054. }
  7055. if (hparams.attn_soft_cap) {
  7056. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  7057. kq = ggml_tanh(ctx, kq);
  7058. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  7059. }
  7060. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7061. cb(kq, "kq_soft_max_ext", il);
  7062. GGML_ASSERT(kv.size == n_ctx);
  7063. // split cached v into n_head heads
  7064. struct ggml_tensor * v =
  7065. ggml_view_3d(ctx, kv.v_l[il],
  7066. n_kv, n_embd_head_v, n_head_kv,
  7067. ggml_element_size(kv.v_l[il])*n_ctx,
  7068. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  7069. 0);
  7070. cb(v, "v", il);
  7071. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  7072. cb(kqv, "kqv", il);
  7073. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  7074. cb(kqv_merged, "kqv_merged", il);
  7075. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  7076. cb(cur, "kqv_merged_cont", il);
  7077. }
  7078. ggml_build_forward_expand(graph, cur);
  7079. if (wo) {
  7080. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  7081. }
  7082. if (wo_b) {
  7083. cb(cur, "kqv_wo", il);
  7084. }
  7085. if (wo_b) {
  7086. cur = ggml_add(ctx, cur, wo_b);
  7087. }
  7088. return cur;
  7089. }
  7090. static struct ggml_tensor * llm_build_kv(
  7091. struct ggml_context * ctx,
  7092. struct llama_context & lctx,
  7093. const llama_kv_cache & kv,
  7094. struct ggml_cgraph * graph,
  7095. struct ggml_tensor * wo,
  7096. struct ggml_tensor * wo_b,
  7097. struct ggml_tensor * k_cur,
  7098. struct ggml_tensor * v_cur,
  7099. struct ggml_tensor * q_cur,
  7100. struct ggml_tensor * kq_mask,
  7101. int32_t n_tokens,
  7102. int32_t kv_head,
  7103. int32_t n_kv,
  7104. float kq_scale,
  7105. const llm_build_cb & cb,
  7106. int il) {
  7107. const llama_hparams & hparams = lctx.model.hparams;
  7108. const llama_cparams & cparams = lctx.cparams;
  7109. // these nodes are added to the graph together so that they are not reordered
  7110. // by doing so, the number of splits in the graph is reduced
  7111. ggml_build_forward_expand(graph, q_cur);
  7112. ggml_build_forward_expand(graph, k_cur);
  7113. ggml_build_forward_expand(graph, v_cur);
  7114. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  7115. struct ggml_tensor * cur;
  7116. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b,
  7117. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  7118. cb(cur, "kqv_out", il);
  7119. return cur;
  7120. }
  7121. struct llm_build_context {
  7122. const llama_model & model;
  7123. llama_context & lctx;
  7124. const llama_hparams & hparams;
  7125. const llama_cparams & cparams;
  7126. const llama_batch & batch;
  7127. const llama_kv_cache & kv_self;
  7128. const int64_t n_embd;
  7129. const int64_t n_layer;
  7130. const int64_t n_rot;
  7131. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  7132. const int64_t n_head;
  7133. const int64_t n_head_kv;
  7134. const int64_t n_embd_head_k;
  7135. const int64_t n_embd_k_gqa;
  7136. const int64_t n_embd_head_v;
  7137. const int64_t n_embd_v_gqa;
  7138. const int64_t n_expert;
  7139. const int64_t n_expert_used;
  7140. const float freq_base;
  7141. const float freq_scale;
  7142. const float ext_factor;
  7143. const float attn_factor;
  7144. const float beta_fast;
  7145. const float beta_slow;
  7146. const float norm_eps;
  7147. const float norm_rms_eps;
  7148. const int32_t n_tokens;
  7149. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  7150. const int32_t n_outputs;
  7151. const int32_t n_outputs_enc;
  7152. const int32_t kv_head; // index of where we store new KV data in the cache
  7153. const int32_t n_ctx_orig;
  7154. const bool flash_attn;
  7155. const enum llama_pooling_type pooling_type;
  7156. const enum llama_rope_type rope_type;
  7157. const llm_build_cb & cb;
  7158. std::vector<uint8_t> & buf_compute_meta;
  7159. struct ggml_context * ctx0 = nullptr;
  7160. // TODO: consider making the entire interface noexcept
  7161. llm_build_context(
  7162. llama_context & lctx,
  7163. const llama_batch & batch,
  7164. const llm_build_cb & cb,
  7165. bool worst_case) :
  7166. model (lctx.model),
  7167. lctx (lctx),
  7168. hparams (model.hparams),
  7169. cparams (lctx.cparams),
  7170. batch (batch),
  7171. kv_self (lctx.kv_self),
  7172. n_embd (hparams.n_embd),
  7173. n_layer (hparams.n_layer),
  7174. n_rot (hparams.n_rot),
  7175. n_ctx (cparams.n_ctx),
  7176. n_head (hparams.n_head()),
  7177. n_head_kv (hparams.n_head_kv()),
  7178. n_embd_head_k (hparams.n_embd_head_k),
  7179. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  7180. n_embd_head_v (hparams.n_embd_head_v),
  7181. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  7182. n_expert (hparams.n_expert),
  7183. n_expert_used (hparams.n_expert_used),
  7184. freq_base (cparams.rope_freq_base),
  7185. freq_scale (cparams.rope_freq_scale),
  7186. ext_factor (cparams.yarn_ext_factor),
  7187. attn_factor (cparams.yarn_attn_factor),
  7188. beta_fast (cparams.yarn_beta_fast),
  7189. beta_slow (cparams.yarn_beta_slow),
  7190. norm_eps (hparams.f_norm_eps),
  7191. norm_rms_eps (hparams.f_norm_rms_eps),
  7192. n_tokens (batch.n_tokens),
  7193. n_kv (worst_case ? kv_self.size : kv_self.n),
  7194. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  7195. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  7196. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  7197. n_ctx_orig (cparams.n_ctx_orig_yarn),
  7198. flash_attn (cparams.flash_attn),
  7199. pooling_type (cparams.pooling_type),
  7200. rope_type (hparams.rope_type),
  7201. cb (cb),
  7202. buf_compute_meta (lctx.buf_compute_meta) {
  7203. // all initializations should be done in init()
  7204. }
  7205. void init() {
  7206. struct ggml_init_params params = {
  7207. /*.mem_size =*/ buf_compute_meta.size(),
  7208. /*.mem_buffer =*/ buf_compute_meta.data(),
  7209. /*.no_alloc =*/ true,
  7210. };
  7211. ctx0 = ggml_init(params);
  7212. lctx.inp_tokens = nullptr;
  7213. lctx.inp_embd = nullptr;
  7214. lctx.inp_pos = nullptr;
  7215. lctx.inp_out_ids = nullptr;
  7216. lctx.inp_KQ_mask = nullptr;
  7217. lctx.inp_KQ_mask_swa = nullptr;
  7218. lctx.inp_K_shift = nullptr;
  7219. lctx.inp_mean = nullptr;
  7220. lctx.inp_cls = nullptr;
  7221. lctx.inp_s_copy = nullptr;
  7222. lctx.inp_s_mask = nullptr;
  7223. lctx.inp_s_seq = nullptr;
  7224. lctx.inp_pos_bucket = nullptr;
  7225. lctx.inp_embd_enc = nullptr;
  7226. lctx.inp_KQ_mask_cross = nullptr;
  7227. }
  7228. void free() {
  7229. if (ctx0) {
  7230. ggml_free(ctx0);
  7231. ctx0 = nullptr;
  7232. }
  7233. }
  7234. struct ggml_cgraph * build_k_shift() {
  7235. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7236. GGML_ASSERT(kv_self.size == n_ctx);
  7237. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  7238. cb(lctx.inp_K_shift, "K_shift", -1);
  7239. ggml_set_input(lctx.inp_K_shift);
  7240. for (int il = 0; il < n_layer; ++il) {
  7241. const int64_t n_head_kv = hparams.n_head_kv(il);
  7242. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7243. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7244. struct ggml_tensor * tmp =
  7245. // we rotate only the first n_rot dimensions
  7246. ggml_rope_ext_inplace(ctx0,
  7247. ggml_view_3d(ctx0, kv_self.k_l[il],
  7248. n_embd_head_k, n_head_kv, n_ctx,
  7249. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  7250. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7251. 0),
  7252. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7253. ext_factor, attn_factor, beta_fast, beta_slow);
  7254. cb(tmp, "K_shifted", il);
  7255. ggml_build_forward_expand(gf, tmp);
  7256. }
  7257. return gf;
  7258. }
  7259. struct ggml_cgraph * build_s_copy() {
  7260. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7261. GGML_ASSERT(kv_self.recurrent);
  7262. struct ggml_tensor * state_copy = build_inp_s_copy();
  7263. for (int il = 0; il < n_layer; ++il) {
  7264. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7265. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7266. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  7267. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  7268. // TODO: name the intermediate tensors with cb()
  7269. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  7270. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  7271. }
  7272. return gf;
  7273. }
  7274. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  7275. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7276. for (uint32_t i = 0; i < ids.size(); ++i) {
  7277. const uint32_t id = ids[i];
  7278. if (i == id || id == ids.size()) {
  7279. continue;
  7280. }
  7281. uint32_t nm = 1;
  7282. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  7283. nm++;
  7284. }
  7285. for (int il = 0; il < n_layer; ++il) {
  7286. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7287. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7288. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  7289. n_embd_k_gqa, nm,
  7290. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7291. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  7292. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  7293. n_embd_k_gqa, nm,
  7294. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7295. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  7296. ggml_tensor * view_v_src;
  7297. ggml_tensor * view_v_dst;
  7298. if (flash_attn) {
  7299. // NOTE: the V cache is not transposed when using flash attention
  7300. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7301. n_embd_v_gqa, nm,
  7302. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7303. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  7304. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7305. n_embd_v_gqa, nm,
  7306. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7307. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  7308. } else {
  7309. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7310. nm, n_embd_v_gqa,
  7311. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7312. ggml_row_size(kv_self.v_l[il]->type, i));
  7313. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7314. nm, n_embd_v_gqa,
  7315. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7316. ggml_row_size(kv_self.v_l[il]->type, id));
  7317. }
  7318. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  7319. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  7320. }
  7321. i += nm - 1;
  7322. }
  7323. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  7324. return gf;
  7325. }
  7326. struct ggml_tensor * build_inp_pos() {
  7327. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7328. cb(lctx.inp_pos, "inp_pos", -1);
  7329. ggml_set_input(lctx.inp_pos);
  7330. return lctx.inp_pos;
  7331. }
  7332. struct ggml_tensor * build_rope_factors(int il) {
  7333. // choose long/short freq factors based on the context size
  7334. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  7335. if (model.layers[il].rope_freqs != nullptr) {
  7336. return model.layers[il].rope_freqs;
  7337. }
  7338. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  7339. return model.layers[il].rope_long;
  7340. }
  7341. return model.layers[il].rope_short;
  7342. }
  7343. struct ggml_tensor * build_inp_out_ids() {
  7344. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  7345. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  7346. ggml_set_input(lctx.inp_out_ids);
  7347. return lctx.inp_out_ids;
  7348. }
  7349. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  7350. lctx.inp_KQ_mask = causal
  7351. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7352. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7353. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  7354. ggml_set_input(lctx.inp_KQ_mask);
  7355. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  7356. }
  7357. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  7358. GGML_ASSERT(hparams.n_swa > 0);
  7359. lctx.inp_KQ_mask_swa = causal
  7360. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7361. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7362. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  7363. ggml_set_input(lctx.inp_KQ_mask_swa);
  7364. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  7365. }
  7366. struct ggml_tensor * build_inp_mean() {
  7367. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  7368. cb(lctx.inp_mean, "inp_mean", -1);
  7369. ggml_set_input(lctx.inp_mean);
  7370. return lctx.inp_mean;
  7371. }
  7372. struct ggml_tensor * build_inp_cls() {
  7373. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7374. cb(lctx.inp_cls, "inp_cls", -1);
  7375. ggml_set_input(lctx.inp_cls);
  7376. return lctx.inp_cls;
  7377. }
  7378. struct ggml_tensor * build_inp_s_copy() {
  7379. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  7380. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  7381. ggml_set_input(lctx.inp_s_copy);
  7382. return lctx.inp_s_copy;
  7383. }
  7384. struct ggml_tensor * build_inp_s_mask() {
  7385. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  7386. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  7387. ggml_set_input(lctx.inp_s_mask);
  7388. return lctx.inp_s_mask;
  7389. }
  7390. struct ggml_tensor * build_inp_s_seq() {
  7391. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7392. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  7393. ggml_set_input(lctx.inp_s_seq);
  7394. return lctx.inp_s_seq;
  7395. }
  7396. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  7397. // find result_norm tensor for input
  7398. struct ggml_tensor * inp = nullptr;
  7399. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  7400. inp = gf->nodes[i];
  7401. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  7402. break;
  7403. } else {
  7404. inp = nullptr;
  7405. }
  7406. }
  7407. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  7408. struct ggml_tensor * cur;
  7409. switch (pooling_type) {
  7410. case LLAMA_POOLING_TYPE_MEAN:
  7411. {
  7412. struct ggml_tensor * inp_mean = build_inp_mean();
  7413. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  7414. } break;
  7415. case LLAMA_POOLING_TYPE_CLS:
  7416. case LLAMA_POOLING_TYPE_LAST:
  7417. {
  7418. struct ggml_tensor * inp_cls = build_inp_cls();
  7419. cur = ggml_get_rows(ctx0, inp, inp_cls);
  7420. } break;
  7421. case LLAMA_POOLING_TYPE_NONE:
  7422. {
  7423. cur = inp;
  7424. } break;
  7425. default:
  7426. {
  7427. GGML_ABORT("unknown pooling type");
  7428. }
  7429. }
  7430. cb(cur, "result_embd_pooled", -1);
  7431. ggml_build_forward_expand(gf, cur);
  7432. return gf;
  7433. }
  7434. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  7435. if (causal) {
  7436. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7437. } else {
  7438. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  7439. }
  7440. ggml_set_input(lctx.inp_pos_bucket);
  7441. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  7442. return lctx.inp_pos_bucket;
  7443. }
  7444. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  7445. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  7446. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  7447. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  7448. cb(pos_bias, "pos_bias", -1);
  7449. 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);
  7450. cb(pos_bias, "pos_bias", -1);
  7451. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  7452. cb(pos_bias, "pos_bias", -1);
  7453. pos_bias = ggml_cont(ctx0, pos_bias);
  7454. cb(pos_bias, "pos_bias", -1);
  7455. return pos_bias;
  7456. }
  7457. struct ggml_tensor * llm_build_inp_embd_enc() {
  7458. const int64_t n_embd = hparams.n_embd;
  7459. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  7460. ggml_set_input(lctx.inp_embd_enc);
  7461. cb(lctx.inp_embd_enc, "embd_enc", -1);
  7462. return lctx.inp_embd_enc;
  7463. }
  7464. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  7465. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7466. ggml_set_input(lctx.inp_KQ_mask_cross);
  7467. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  7468. return lctx.inp_KQ_mask_cross;
  7469. }
  7470. struct ggml_cgraph * build_llama() {
  7471. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7472. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7473. int32_t n_tokens = this->n_tokens;
  7474. const int64_t n_embd_head = hparams.n_embd_head_v;
  7475. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7476. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7477. struct ggml_tensor * cur;
  7478. struct ggml_tensor * inpL;
  7479. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7480. // inp_pos - contains the positions
  7481. struct ggml_tensor * inp_pos = build_inp_pos();
  7482. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7483. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7484. for (int il = 0; il < n_layer; ++il) {
  7485. struct ggml_tensor * inpSA = inpL;
  7486. // norm
  7487. cur = llm_build_norm(ctx0, inpL, hparams,
  7488. model.layers[il].attn_norm, NULL,
  7489. LLM_NORM_RMS, cb, il);
  7490. cb(cur, "attn_norm", il);
  7491. // self-attention
  7492. {
  7493. // rope freq factors for llama3; may return nullptr for llama2 and other models
  7494. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7495. // compute Q and K and RoPE them
  7496. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7497. cb(Qcur, "Qcur", il);
  7498. if (model.layers[il].bq) {
  7499. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7500. cb(Qcur, "Qcur", il);
  7501. }
  7502. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7503. cb(Kcur, "Kcur", il);
  7504. if (model.layers[il].bk) {
  7505. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7506. cb(Kcur, "Kcur", il);
  7507. }
  7508. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7509. cb(Vcur, "Vcur", il);
  7510. if (model.layers[il].bv) {
  7511. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7512. cb(Vcur, "Vcur", il);
  7513. }
  7514. Qcur = ggml_rope_ext(
  7515. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  7516. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7517. ext_factor, attn_factor, beta_fast, beta_slow
  7518. );
  7519. cb(Qcur, "Qcur", il);
  7520. Kcur = ggml_rope_ext(
  7521. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  7522. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7523. ext_factor, attn_factor, beta_fast, beta_slow
  7524. );
  7525. cb(Kcur, "Kcur", il);
  7526. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7527. model.layers[il].wo, model.layers[il].bo,
  7528. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7529. }
  7530. if (il == n_layer - 1) {
  7531. // skip computing output for unused tokens
  7532. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7533. n_tokens = n_outputs;
  7534. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7535. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7536. }
  7537. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7538. cb(ffn_inp, "ffn_inp", il);
  7539. // feed-forward network
  7540. if (model.layers[il].ffn_gate_inp == nullptr) {
  7541. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7542. model.layers[il].ffn_norm, NULL,
  7543. LLM_NORM_RMS, cb, il);
  7544. cb(cur, "ffn_norm", il);
  7545. cur = llm_build_ffn(ctx0, lctx, cur,
  7546. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  7547. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  7548. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  7549. NULL,
  7550. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7551. cb(cur, "ffn_out", il);
  7552. } else {
  7553. // MoE branch
  7554. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7555. model.layers[il].ffn_norm, NULL,
  7556. LLM_NORM_RMS, cb, il);
  7557. cb(cur, "ffn_norm", il);
  7558. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7559. model.layers[il].ffn_gate_inp,
  7560. model.layers[il].ffn_up_exps,
  7561. model.layers[il].ffn_gate_exps,
  7562. model.layers[il].ffn_down_exps,
  7563. n_expert, n_expert_used,
  7564. LLM_FFN_SILU, true,
  7565. false, 0.0,
  7566. cb, il);
  7567. cb(cur, "ffn_moe_out", il);
  7568. }
  7569. cur = ggml_add(ctx0, cur, ffn_inp);
  7570. cb(cur, "ffn_out", il);
  7571. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7572. cb(cur, "l_out", il);
  7573. // input for next layer
  7574. inpL = cur;
  7575. }
  7576. cur = inpL;
  7577. cur = llm_build_norm(ctx0, cur, hparams,
  7578. model.output_norm, NULL,
  7579. LLM_NORM_RMS, cb, -1);
  7580. cb(cur, "result_norm", -1);
  7581. // lm_head
  7582. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7583. cb(cur, "result_output", -1);
  7584. ggml_build_forward_expand(gf, cur);
  7585. return gf;
  7586. }
  7587. struct ggml_cgraph * build_baichuan() {
  7588. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7589. const int64_t n_embd_head = hparams.n_embd_head_v;
  7590. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7591. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7592. struct ggml_tensor * cur;
  7593. struct ggml_tensor * inpL;
  7594. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7595. // inp_pos - contains the positions
  7596. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  7597. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7598. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7599. for (int il = 0; il < n_layer; ++il) {
  7600. struct ggml_tensor * inpSA = inpL;
  7601. cur = llm_build_norm(ctx0, inpL, hparams,
  7602. model.layers[il].attn_norm, NULL,
  7603. LLM_NORM_RMS, cb, il);
  7604. cb(cur, "attn_norm", il);
  7605. // self-attention
  7606. {
  7607. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7608. cb(Qcur, "Qcur", il);
  7609. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7610. cb(Kcur, "Kcur", il);
  7611. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7612. cb(Vcur, "Vcur", il);
  7613. switch (model.type) {
  7614. case MODEL_7B:
  7615. Qcur = ggml_rope_ext(
  7616. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7617. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7618. ext_factor, attn_factor, beta_fast, beta_slow
  7619. );
  7620. Kcur = ggml_rope_ext(
  7621. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7622. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7623. ext_factor, attn_factor, beta_fast, beta_slow
  7624. );
  7625. break;
  7626. case MODEL_13B:
  7627. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  7628. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  7629. break;
  7630. default:
  7631. GGML_ABORT("fatal error");
  7632. }
  7633. cb(Qcur, "Qcur", il);
  7634. cb(Kcur, "Kcur", il);
  7635. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7636. model.layers[il].wo, NULL,
  7637. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7638. }
  7639. if (il == n_layer - 1) {
  7640. // skip computing output for unused tokens
  7641. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7642. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7643. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7644. }
  7645. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7646. cb(ffn_inp, "ffn_inp", il);
  7647. // feed-forward network
  7648. {
  7649. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7650. model.layers[il].ffn_norm, NULL,
  7651. LLM_NORM_RMS, cb, il);
  7652. cb(cur, "ffn_norm", il);
  7653. cur = llm_build_ffn(ctx0, lctx, cur,
  7654. model.layers[il].ffn_up, NULL, NULL,
  7655. model.layers[il].ffn_gate, NULL, NULL,
  7656. model.layers[il].ffn_down, NULL, NULL,
  7657. NULL,
  7658. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7659. cb(cur, "ffn_out", il);
  7660. }
  7661. cur = ggml_add(ctx0, cur, ffn_inp);
  7662. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7663. cb(cur, "l_out", il);
  7664. // input for next layer
  7665. inpL = cur;
  7666. }
  7667. cur = inpL;
  7668. cur = llm_build_norm(ctx0, cur, hparams,
  7669. model.output_norm, NULL,
  7670. LLM_NORM_RMS, cb, -1);
  7671. cb(cur, "result_norm", -1);
  7672. // lm_head
  7673. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7674. cb(cur, "result_output", -1);
  7675. ggml_build_forward_expand(gf, cur);
  7676. return gf;
  7677. }
  7678. struct ggml_cgraph * build_xverse() {
  7679. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7680. const int64_t n_embd_head = hparams.n_embd_head_v;
  7681. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7682. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7683. struct ggml_tensor * cur;
  7684. struct ggml_tensor * inpL;
  7685. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7686. // inp_pos - contains the positions
  7687. struct ggml_tensor * inp_pos = build_inp_pos();
  7688. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7689. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7690. for (int il = 0; il < n_layer; ++il) {
  7691. struct ggml_tensor * inpSA = inpL;
  7692. cur = llm_build_norm(ctx0, inpL, hparams,
  7693. model.layers[il].attn_norm, NULL,
  7694. LLM_NORM_RMS, cb, il);
  7695. cb(cur, "attn_norm", il);
  7696. // self-attention
  7697. {
  7698. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7699. cb(Qcur, "Qcur", il);
  7700. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7701. cb(Kcur, "Kcur", il);
  7702. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7703. cb(Vcur, "Vcur", il);
  7704. Qcur = ggml_rope_ext(
  7705. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7706. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7707. ext_factor, attn_factor, beta_fast, beta_slow
  7708. );
  7709. cb(Qcur, "Qcur", il);
  7710. Kcur = ggml_rope_ext(
  7711. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7712. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7713. ext_factor, attn_factor, beta_fast, beta_slow
  7714. );
  7715. cb(Kcur, "Kcur", il);
  7716. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7717. model.layers[il].wo, NULL,
  7718. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7719. }
  7720. if (il == n_layer - 1) {
  7721. // skip computing output for unused tokens
  7722. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7723. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7724. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7725. }
  7726. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7727. cb(ffn_inp, "ffn_inp", il);
  7728. // feed-forward network
  7729. {
  7730. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7731. model.layers[il].ffn_norm, NULL,
  7732. LLM_NORM_RMS, cb, il);
  7733. cb(cur, "ffn_norm", il);
  7734. cur = llm_build_ffn(ctx0, lctx, cur,
  7735. model.layers[il].ffn_up, NULL, NULL,
  7736. model.layers[il].ffn_gate, NULL, NULL,
  7737. model.layers[il].ffn_down, NULL, NULL,
  7738. NULL,
  7739. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7740. cb(cur, "ffn_out", il);
  7741. }
  7742. cur = ggml_add(ctx0, cur, ffn_inp);
  7743. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7744. cb(cur, "l_out", il);
  7745. // input for next layer
  7746. inpL = cur;
  7747. }
  7748. cur = inpL;
  7749. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  7750. cb(cur, "result_norm", -1);
  7751. // lm_head
  7752. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7753. cb(cur, "result_output", -1);
  7754. ggml_build_forward_expand(gf, cur);
  7755. return gf;
  7756. }
  7757. struct ggml_cgraph * build_falcon() {
  7758. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7759. const int64_t n_embd_head = hparams.n_embd_head_v;
  7760. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7761. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7762. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7763. struct ggml_tensor * cur;
  7764. struct ggml_tensor * inpL;
  7765. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7766. // inp_pos - contains the positions
  7767. struct ggml_tensor * inp_pos = build_inp_pos();
  7768. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7769. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7770. for (int il = 0; il < n_layer; ++il) {
  7771. struct ggml_tensor * attn_norm;
  7772. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  7773. model.layers[il].attn_norm,
  7774. model.layers[il].attn_norm_b,
  7775. LLM_NORM, cb, il);
  7776. cb(attn_norm, "attn_norm", il);
  7777. // self-attention
  7778. {
  7779. if (model.layers[il].attn_norm_2) {
  7780. // Falcon-40B
  7781. cur = llm_build_norm(ctx0, inpL, hparams,
  7782. model.layers[il].attn_norm_2,
  7783. model.layers[il].attn_norm_2_b,
  7784. LLM_NORM, cb, il);
  7785. cb(cur, "attn_norm_2", il);
  7786. } else {
  7787. cur = attn_norm;
  7788. }
  7789. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  7790. cb(cur, "wqkv", il);
  7791. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7792. 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)));
  7793. 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)));
  7794. cb(Qcur, "Qcur", il);
  7795. cb(Kcur, "Kcur", il);
  7796. cb(Vcur, "Vcur", il);
  7797. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7798. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7799. // using mode = 2 for neox mode
  7800. Qcur = ggml_rope_ext(
  7801. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7802. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7803. );
  7804. cb(Qcur, "Qcur", il);
  7805. Kcur = ggml_rope_ext(
  7806. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7807. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7808. );
  7809. cb(Kcur, "Kcur", il);
  7810. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7811. model.layers[il].wo, NULL,
  7812. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7813. }
  7814. if (il == n_layer - 1) {
  7815. // skip computing output for unused tokens
  7816. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7817. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7818. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7819. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  7820. }
  7821. struct ggml_tensor * ffn_inp = cur;
  7822. // feed forward
  7823. {
  7824. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  7825. model.layers[il].ffn_up, NULL, NULL,
  7826. NULL, NULL, NULL,
  7827. model.layers[il].ffn_down, NULL, NULL,
  7828. NULL,
  7829. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7830. cb(cur, "ffn_out", il);
  7831. }
  7832. cur = ggml_add(ctx0, cur, ffn_inp);
  7833. cur = ggml_add(ctx0, cur, inpL);
  7834. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7835. cb(cur, "l_out", il);
  7836. // input for next layer
  7837. inpL = cur;
  7838. }
  7839. cur = inpL;
  7840. // norm
  7841. cur = llm_build_norm(ctx0, cur, hparams,
  7842. model.output_norm,
  7843. model.output_norm_b,
  7844. LLM_NORM, cb, -1);
  7845. cb(cur, "result_norm", -1);
  7846. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7847. cb(cur, "result_output", -1);
  7848. ggml_build_forward_expand(gf, cur);
  7849. return gf;
  7850. }
  7851. struct ggml_cgraph * build_grok() {
  7852. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7853. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7854. int32_t n_tokens = this->n_tokens;
  7855. const int64_t n_embd_head = hparams.n_embd_head_v;
  7856. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7857. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7858. struct ggml_tensor * cur;
  7859. struct ggml_tensor * inpL;
  7860. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7861. // multiply by embedding_multiplier_scale of 78.38367176906169
  7862. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  7863. // inp_pos - contains the positions
  7864. struct ggml_tensor * inp_pos = build_inp_pos();
  7865. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7866. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7867. for (int il = 0; il < n_layer; ++il) {
  7868. struct ggml_tensor * inpSA = inpL;
  7869. // norm
  7870. cur = llm_build_norm(ctx0, inpL, hparams,
  7871. model.layers[il].attn_norm, NULL,
  7872. LLM_NORM_RMS, cb, il);
  7873. cb(cur, "attn_norm", il);
  7874. // self-attention
  7875. {
  7876. // compute Q and K and RoPE them
  7877. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7878. cb(Qcur, "Qcur", il);
  7879. if (model.layers[il].bq) {
  7880. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7881. cb(Qcur, "Qcur", il);
  7882. }
  7883. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7884. cb(Kcur, "Kcur", il);
  7885. if (model.layers[il].bk) {
  7886. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7887. cb(Kcur, "Kcur", il);
  7888. }
  7889. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7890. cb(Vcur, "Vcur", il);
  7891. if (model.layers[il].bv) {
  7892. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7893. cb(Vcur, "Vcur", il);
  7894. }
  7895. Qcur = ggml_rope_ext(
  7896. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7897. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7898. ext_factor, attn_factor, beta_fast, beta_slow
  7899. );
  7900. cb(Qcur, "Qcur", il);
  7901. Kcur = ggml_rope_ext(
  7902. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7903. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7904. ext_factor, attn_factor, beta_fast, beta_slow
  7905. );
  7906. cb(Kcur, "Kcur", il);
  7907. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7908. model.layers[il].wo, model.layers[il].bo,
  7909. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7910. }
  7911. if (il == n_layer - 1) {
  7912. // skip computing output for unused tokens
  7913. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7914. n_tokens = n_outputs;
  7915. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7916. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7917. }
  7918. // Grok
  7919. // if attn_out_norm is present then apply it before adding the input
  7920. if (model.layers[il].attn_out_norm) {
  7921. cur = llm_build_norm(ctx0, cur, hparams,
  7922. model.layers[il].attn_out_norm, NULL,
  7923. LLM_NORM_RMS, cb, il);
  7924. cb(cur, "attn_out_norm", il);
  7925. }
  7926. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7927. cb(ffn_inp, "ffn_inp", il);
  7928. // feed-forward network
  7929. // MoE branch
  7930. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7931. model.layers[il].ffn_norm, NULL,
  7932. LLM_NORM_RMS, cb, il);
  7933. cb(cur, "ffn_norm", il);
  7934. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7935. model.layers[il].ffn_gate_inp,
  7936. model.layers[il].ffn_up_exps,
  7937. model.layers[il].ffn_gate_exps,
  7938. model.layers[il].ffn_down_exps,
  7939. n_expert, n_expert_used,
  7940. LLM_FFN_GELU, true,
  7941. false, 0.0,
  7942. cb, il);
  7943. cb(cur, "ffn_moe_out", il);
  7944. // Grok
  7945. // if layer_out_norm is present then apply it before adding the input
  7946. // Idea: maybe ffn_out_norm is a better name
  7947. if (model.layers[il].layer_out_norm) {
  7948. cur = llm_build_norm(ctx0, cur, hparams,
  7949. model.layers[il].layer_out_norm, NULL,
  7950. LLM_NORM_RMS, cb, il);
  7951. cb(cur, "layer_out_norm", il);
  7952. }
  7953. cur = ggml_add(ctx0, cur, ffn_inp);
  7954. cb(cur, "ffn_out", il);
  7955. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7956. cb(cur, "l_out", il);
  7957. // input for next layer
  7958. inpL = cur;
  7959. }
  7960. cur = inpL;
  7961. cur = llm_build_norm(ctx0, cur, hparams,
  7962. model.output_norm, NULL,
  7963. LLM_NORM_RMS, cb, -1);
  7964. cb(cur, "result_norm", -1);
  7965. // lm_head
  7966. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7967. // Grok
  7968. // multiply logits by output_multiplier_scale of 0.5773502691896257
  7969. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  7970. cb(cur, "result_output", -1);
  7971. ggml_build_forward_expand(gf, cur);
  7972. return gf;
  7973. }
  7974. struct ggml_cgraph * build_dbrx() {
  7975. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7976. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7977. int32_t n_tokens = this->n_tokens;
  7978. const int64_t n_embd_head = hparams.n_embd_head_v;
  7979. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7980. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7981. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7982. struct ggml_tensor * cur;
  7983. struct ggml_tensor * inpL;
  7984. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7985. // inp_pos - contains the positions
  7986. struct ggml_tensor * inp_pos = build_inp_pos();
  7987. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7988. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7989. for (int il = 0; il < n_layer; ++il) {
  7990. struct ggml_tensor * inpSA = inpL;
  7991. // norm
  7992. cur = llm_build_norm(ctx0, inpL, hparams,
  7993. model.layers[il].attn_norm, NULL,
  7994. LLM_NORM, cb, il);
  7995. cb(cur, "attn_norm", il);
  7996. // self-attention
  7997. {
  7998. struct ggml_tensor * Qcur = nullptr;
  7999. struct ggml_tensor * Kcur = nullptr;
  8000. struct ggml_tensor * Vcur = nullptr;
  8001. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8002. cb(cur, "wqkv", il);
  8003. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8004. cb(cur, "wqkv_clamped", il);
  8005. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8006. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8007. 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)));
  8008. cb(Qcur, "Qcur", il);
  8009. cb(Kcur, "Kcur", il);
  8010. cb(Vcur, "Vcur", il);
  8011. Qcur = ggml_rope_ext(
  8012. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8013. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8014. ext_factor, attn_factor, beta_fast, beta_slow
  8015. );
  8016. cb(Qcur, "Qcur", il);
  8017. Kcur = ggml_rope_ext(
  8018. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8019. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8020. ext_factor, attn_factor, beta_fast, beta_slow
  8021. );
  8022. cb(Kcur, "Kcur", il);
  8023. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8024. model.layers[il].wo, NULL,
  8025. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8026. }
  8027. if (il == n_layer - 1) {
  8028. // skip computing output for unused tokens
  8029. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8030. n_tokens = n_outputs;
  8031. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8032. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8033. }
  8034. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8035. cb(ffn_inp, "ffn_inp", il);
  8036. // feed-forward network
  8037. // MoE branch
  8038. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8039. model.layers[il].attn_out_norm, NULL,
  8040. LLM_NORM, cb, il);
  8041. cb(cur, "attn_out_norm", il);
  8042. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8043. model.layers[il].ffn_gate_inp,
  8044. model.layers[il].ffn_up_exps,
  8045. model.layers[il].ffn_gate_exps,
  8046. model.layers[il].ffn_down_exps,
  8047. n_expert, n_expert_used,
  8048. LLM_FFN_SILU, true,
  8049. false, 0.0,
  8050. cb, il);
  8051. cb(cur, "ffn_moe_out", il);
  8052. cur = ggml_add(ctx0, cur, ffn_inp);
  8053. cb(cur, "ffn_out", il);
  8054. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8055. cb(cur, "l_out", il);
  8056. // input for next layer
  8057. inpL = cur;
  8058. }
  8059. cur = inpL;
  8060. cur = llm_build_norm(ctx0, cur, hparams,
  8061. model.output_norm, NULL,
  8062. LLM_NORM, cb, -1);
  8063. cb(cur, "result_norm", -1);
  8064. // lm_head
  8065. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8066. cb(cur, "result_output", -1);
  8067. ggml_build_forward_expand(gf, cur);
  8068. return gf;
  8069. }
  8070. struct ggml_cgraph * build_starcoder() {
  8071. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8072. const int64_t n_embd_head = hparams.n_embd_head_v;
  8073. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8074. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8075. struct ggml_tensor * cur;
  8076. struct ggml_tensor * inpL;
  8077. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8078. // inp_pos - contains the positions
  8079. struct ggml_tensor * inp_pos = build_inp_pos();
  8080. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8081. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8082. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8083. cb(pos, "pos_embd", -1);
  8084. inpL = ggml_add(ctx0, inpL, pos);
  8085. cb(inpL, "inpL", -1);
  8086. for (int il = 0; il < n_layer; ++il) {
  8087. cur = llm_build_norm(ctx0, inpL, hparams,
  8088. model.layers[il].attn_norm,
  8089. model.layers[il].attn_norm_b,
  8090. LLM_NORM, cb, il);
  8091. cb(cur, "attn_norm", il);
  8092. // self-attention
  8093. {
  8094. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8095. cb(cur, "wqkv", il);
  8096. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8097. cb(cur, "bqkv", il);
  8098. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8099. 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)));
  8100. 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)));
  8101. cb(Qcur, "Qcur", il);
  8102. cb(Kcur, "Kcur", il);
  8103. cb(Vcur, "Vcur", il);
  8104. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8105. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8106. model.layers[il].wo, model.layers[il].bo,
  8107. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8108. }
  8109. if (il == n_layer - 1) {
  8110. // skip computing output for unused tokens
  8111. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8112. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8113. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8114. }
  8115. // add the input
  8116. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8117. cb(ffn_inp, "ffn_inp", il);
  8118. // FF
  8119. {
  8120. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8121. model.layers[il].ffn_norm,
  8122. model.layers[il].ffn_norm_b,
  8123. LLM_NORM, cb, il);
  8124. cb(cur, "ffn_norm", il);
  8125. cur = llm_build_ffn(ctx0, lctx, cur,
  8126. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8127. NULL, NULL, NULL,
  8128. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8129. NULL,
  8130. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8131. cb(cur, "ffn_out", il);
  8132. }
  8133. cur = ggml_add(ctx0, cur, ffn_inp);
  8134. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8135. cb(cur, "l_out", il);
  8136. // input for next layer
  8137. inpL = cur;
  8138. }
  8139. cur = llm_build_norm(ctx0, inpL, hparams,
  8140. model.output_norm,
  8141. model.output_norm_b,
  8142. LLM_NORM, cb, -1);
  8143. cb(cur, "result_norm", -1);
  8144. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8145. cb(cur, "result_output", -1);
  8146. ggml_build_forward_expand(gf, cur);
  8147. return gf;
  8148. }
  8149. struct ggml_cgraph * build_refact() {
  8150. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8151. const int64_t n_embd_head = hparams.n_embd_head_v;
  8152. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8153. struct ggml_tensor * cur;
  8154. struct ggml_tensor * inpL;
  8155. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8156. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8157. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8158. for (int il = 0; il < n_layer; ++il) {
  8159. struct ggml_tensor * inpSA = inpL;
  8160. cur = llm_build_norm(ctx0, inpL, hparams,
  8161. model.layers[il].attn_norm, NULL,
  8162. LLM_NORM_RMS, cb, il);
  8163. cb(cur, "attn_norm", il);
  8164. // self-attention
  8165. {
  8166. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8167. cb(Qcur, "Qcur", il);
  8168. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8169. cb(Kcur, "Kcur", il);
  8170. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8171. cb(Vcur, "Vcur", il);
  8172. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8173. cb(Kcur, "Kcur", il);
  8174. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8175. cb(Qcur, "Qcur", il);
  8176. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8177. model.layers[il].wo, NULL,
  8178. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8179. }
  8180. if (il == n_layer - 1) {
  8181. // skip computing output for unused tokens
  8182. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8183. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8184. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8185. }
  8186. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8187. cb(ffn_inp, "ffn_inp", il);
  8188. // feed-forward network
  8189. {
  8190. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8191. model.layers[il].ffn_norm, NULL,
  8192. LLM_NORM_RMS, cb, il);
  8193. cb(cur, "ffn_norm", il);
  8194. cur = llm_build_ffn(ctx0, lctx, cur,
  8195. model.layers[il].ffn_up, NULL, NULL,
  8196. model.layers[il].ffn_gate, NULL, NULL,
  8197. model.layers[il].ffn_down, NULL, NULL,
  8198. NULL,
  8199. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8200. cb(cur, "ffn_out", il);
  8201. }
  8202. cur = ggml_add(ctx0, cur, ffn_inp);
  8203. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8204. cb(cur, "l_out", il);
  8205. // input for next layer
  8206. inpL = cur;
  8207. }
  8208. cur = inpL;
  8209. cur = llm_build_norm(ctx0, cur, hparams,
  8210. model.output_norm, NULL,
  8211. LLM_NORM_RMS, cb, -1);
  8212. cb(cur, "result_norm", -1);
  8213. // lm_head
  8214. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8215. cb(cur, "result_output", -1);
  8216. ggml_build_forward_expand(gf, cur);
  8217. return gf;
  8218. }
  8219. struct ggml_cgraph * build_bert() {
  8220. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8221. const int64_t n_embd_head = hparams.n_embd_head_v;
  8222. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8223. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8224. struct ggml_tensor * cur;
  8225. struct ggml_tensor * inpL;
  8226. struct ggml_tensor * inp_pos = nullptr;
  8227. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  8228. inp_pos = build_inp_pos();
  8229. }
  8230. // construct input embeddings (token, type, position)
  8231. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8232. // token types are hardcoded to zero ("Sentence A")
  8233. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  8234. inpL = ggml_add(ctx0, inpL, type_row0);
  8235. if (model.arch == LLM_ARCH_BERT) {
  8236. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  8237. }
  8238. cb(inpL, "inp_embd", -1);
  8239. // embed layer norm
  8240. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  8241. cb(inpL, "inp_norm", -1);
  8242. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8243. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  8244. // iterate layers
  8245. for (int il = 0; il < n_layer; ++il) {
  8246. struct ggml_tensor * cur = inpL;
  8247. struct ggml_tensor * Qcur;
  8248. struct ggml_tensor * Kcur;
  8249. struct ggml_tensor * Vcur;
  8250. // self-attention
  8251. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  8252. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  8253. cb(Qcur, "Qcur", il);
  8254. if (model.layers[il].attn_q_norm) {
  8255. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8256. model.layers[il].attn_q_norm,
  8257. model.layers[il].attn_q_norm_b,
  8258. LLM_NORM, cb, il);
  8259. }
  8260. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  8261. cb(Kcur, "Kcur", il);
  8262. if (model.layers[il].attn_k_norm) {
  8263. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8264. model.layers[il].attn_k_norm,
  8265. model.layers[il].attn_k_norm_b,
  8266. LLM_NORM, cb, il);
  8267. }
  8268. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  8269. cb(Vcur, "Vcur", il);
  8270. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8271. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8272. } else {
  8273. // compute Q and K and RoPE them
  8274. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8275. cb(cur, "wqkv", il);
  8276. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8277. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8278. 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)));
  8279. cb(Qcur, "Qcur", il);
  8280. cb(Kcur, "Kcur", il);
  8281. cb(Vcur, "Vcur", il);
  8282. Qcur = ggml_rope_ext(
  8283. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8284. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8285. ext_factor, attn_factor, beta_fast, beta_slow
  8286. );
  8287. cb(Qcur, "Qcur", il);
  8288. Kcur = ggml_rope_ext(
  8289. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8290. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8291. ext_factor, attn_factor, beta_fast, beta_slow
  8292. );
  8293. cb(Kcur, "Kcur", il);
  8294. }
  8295. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  8296. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  8297. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  8298. cb(kq, "kq", il);
  8299. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  8300. cb(kq, "kq_soft_max_ext", il);
  8301. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  8302. cb(v, "v", il);
  8303. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  8304. cb(kqv, "kqv", il);
  8305. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  8306. cb(kqv_merged, "kqv_merged", il);
  8307. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  8308. cb(cur, "kqv_merged_cont", il);
  8309. ggml_build_forward_expand(gf, cur);
  8310. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  8311. if (model.layers[il].bo) {
  8312. cb(cur, "kqv_wo", il);
  8313. }
  8314. if (model.layers[il].bo) {
  8315. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  8316. }
  8317. cb(cur, "kqv_out", il);
  8318. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8319. // skip computing output for unused tokens
  8320. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8321. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8322. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8323. }
  8324. // re-add the layer input
  8325. cur = ggml_add(ctx0, cur, inpL);
  8326. // attention layer norm
  8327. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  8328. if (model.layers[il].attn_norm_2 != nullptr) {
  8329. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  8330. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  8331. }
  8332. struct ggml_tensor * ffn_inp = cur;
  8333. cb(ffn_inp, "ffn_inp", il);
  8334. // feed-forward network
  8335. if (model.arch == LLM_ARCH_BERT) {
  8336. cur = llm_build_ffn(ctx0, lctx, cur,
  8337. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8338. NULL, NULL, NULL,
  8339. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8340. NULL,
  8341. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8342. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  8343. cur = llm_build_ffn(ctx0, lctx, cur,
  8344. model.layers[il].ffn_up, NULL, NULL,
  8345. model.layers[il].ffn_gate, NULL, NULL,
  8346. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8347. NULL,
  8348. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  8349. } else {
  8350. cur = llm_build_ffn(ctx0, lctx, cur,
  8351. model.layers[il].ffn_up, NULL, NULL,
  8352. model.layers[il].ffn_gate, NULL, NULL,
  8353. model.layers[il].ffn_down, NULL, NULL,
  8354. NULL,
  8355. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8356. }
  8357. cb(cur, "ffn_out", il);
  8358. // attentions bypass the intermediate layer
  8359. cur = ggml_add(ctx0, cur, ffn_inp);
  8360. // output layer norm
  8361. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  8362. // input for next layer
  8363. inpL = cur;
  8364. }
  8365. // final output
  8366. cur = inpL;
  8367. cb(cur, "result_embd", -1);
  8368. ggml_build_forward_expand(gf, cur);
  8369. return gf;
  8370. }
  8371. struct ggml_cgraph * build_bloom() {
  8372. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8373. const int64_t n_embd_head = hparams.n_embd_head_v;
  8374. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8375. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8376. struct ggml_tensor * cur;
  8377. struct ggml_tensor * inpL;
  8378. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8379. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8380. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8381. inpL = llm_build_norm(ctx0, inpL, hparams,
  8382. model.tok_norm,
  8383. model.tok_norm_b,
  8384. LLM_NORM, cb, -1);
  8385. cb(inpL, "inp_norm", -1);
  8386. for (int il = 0; il < n_layer; ++il) {
  8387. cur = llm_build_norm(ctx0, inpL, hparams,
  8388. model.layers[il].attn_norm,
  8389. model.layers[il].attn_norm_b,
  8390. LLM_NORM, cb, il);
  8391. cb(cur, "attn_norm", il);
  8392. // self-attention
  8393. {
  8394. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8395. cb(cur, "wqkv", il);
  8396. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8397. cb(cur, "bqkv", il);
  8398. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8399. 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)));
  8400. 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)));
  8401. cb(Qcur, "Qcur", il);
  8402. cb(Kcur, "Kcur", il);
  8403. cb(Vcur, "Vcur", il);
  8404. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8405. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8406. model.layers[il].wo, model.layers[il].bo,
  8407. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8408. }
  8409. if (il == n_layer - 1) {
  8410. // skip computing output for unused tokens
  8411. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8412. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8413. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8414. }
  8415. // Add the input
  8416. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8417. cb(ffn_inp, "ffn_inp", il);
  8418. // FF
  8419. {
  8420. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8421. model.layers[il].ffn_norm,
  8422. model.layers[il].ffn_norm_b,
  8423. LLM_NORM, cb, il);
  8424. cb(cur, "ffn_norm", il);
  8425. cur = llm_build_ffn(ctx0, lctx, cur,
  8426. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8427. NULL, NULL, NULL,
  8428. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8429. NULL,
  8430. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8431. cb(cur, "ffn_out", il);
  8432. }
  8433. cur = ggml_add(ctx0, cur, ffn_inp);
  8434. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8435. cb(cur, "l_out", il);
  8436. // input for next layer
  8437. inpL = cur;
  8438. }
  8439. cur = llm_build_norm(ctx0, inpL, hparams,
  8440. model.output_norm,
  8441. model.output_norm_b,
  8442. LLM_NORM, cb, -1);
  8443. cb(cur, "result_norm", -1);
  8444. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8445. cb(cur, "result_output", -1);
  8446. ggml_build_forward_expand(gf, cur);
  8447. return gf;
  8448. }
  8449. struct ggml_cgraph * build_mpt() {
  8450. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8451. const int64_t n_embd_head = hparams.n_embd_head_v;
  8452. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8453. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8454. struct ggml_tensor * cur;
  8455. struct ggml_tensor * pos;
  8456. struct ggml_tensor * inpL;
  8457. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8458. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8459. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8460. if (model.pos_embd) {
  8461. // inp_pos - contains the positions
  8462. struct ggml_tensor * inp_pos = build_inp_pos();
  8463. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8464. cb(pos, "pos_embd", -1);
  8465. inpL = ggml_add(ctx0, inpL, pos);
  8466. cb(inpL, "inpL", -1);
  8467. }
  8468. for (int il = 0; il < n_layer; ++il) {
  8469. struct ggml_tensor * attn_norm;
  8470. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  8471. model.layers[il].attn_norm,
  8472. model.layers[il].attn_norm_b,
  8473. LLM_NORM, cb, il);
  8474. cb(attn_norm, "attn_norm", il);
  8475. // self-attention
  8476. {
  8477. cur = attn_norm;
  8478. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8479. cb(cur, "wqkv", il);
  8480. if (model.layers[il].bqkv){
  8481. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8482. cb(cur, "bqkv", il);
  8483. }
  8484. if (hparams.f_clamp_kqv > 0.0f) {
  8485. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8486. cb(cur, "wqkv_clamped", il);
  8487. }
  8488. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8489. 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)));
  8490. 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)));
  8491. cb(Qcur, "Qcur", il);
  8492. cb(Kcur, "Kcur", il);
  8493. cb(Vcur, "Vcur", il);
  8494. // Q/K Layernorm
  8495. if (model.layers[il].attn_q_norm) {
  8496. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8497. model.layers[il].attn_q_norm,
  8498. model.layers[il].attn_q_norm_b,
  8499. LLM_NORM, cb, il);
  8500. cb(Qcur, "Qcur", il);
  8501. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8502. model.layers[il].attn_k_norm,
  8503. model.layers[il].attn_k_norm_b,
  8504. LLM_NORM, cb, il);
  8505. cb(Kcur, "Kcur", il);
  8506. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8507. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8508. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8509. model.layers[il].wo, model.layers[il].bo,
  8510. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8511. } else {
  8512. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8513. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8514. model.layers[il].wo, model.layers[il].bo,
  8515. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8516. }
  8517. }
  8518. if (il == n_layer - 1) {
  8519. // skip computing output for unused tokens
  8520. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8521. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8522. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8523. }
  8524. // Add the input
  8525. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8526. cb(ffn_inp, "ffn_inp", il);
  8527. // feed forward
  8528. {
  8529. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8530. model.layers[il].ffn_norm,
  8531. model.layers[il].ffn_norm_b,
  8532. LLM_NORM, cb, il);
  8533. cb(cur, "ffn_norm", il);
  8534. cur = llm_build_ffn(ctx0, lctx, cur,
  8535. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8536. NULL, NULL, NULL,
  8537. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8538. model.layers[il].ffn_act,
  8539. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8540. cb(cur, "ffn_out", il);
  8541. }
  8542. cur = ggml_add(ctx0, cur, ffn_inp);
  8543. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8544. cb(cur, "l_out", il);
  8545. // input for next layer
  8546. inpL = cur;
  8547. }
  8548. cur = inpL;
  8549. cur = llm_build_norm(ctx0, cur, hparams,
  8550. model.output_norm,
  8551. model.output_norm_b,
  8552. LLM_NORM, cb, -1);
  8553. cb(cur, "result_norm", -1);
  8554. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8555. cb(cur, "result_output", -1);
  8556. ggml_build_forward_expand(gf, cur);
  8557. return gf;
  8558. }
  8559. struct ggml_cgraph * build_stablelm() {
  8560. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  8561. const int64_t n_embd_head = hparams.n_embd_head_v;
  8562. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8563. struct ggml_tensor * cur;
  8564. struct ggml_tensor * inpL;
  8565. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8566. // inp_pos - contains the positions
  8567. struct ggml_tensor * inp_pos = build_inp_pos();
  8568. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8569. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8570. for (int il = 0; il < n_layer; ++il) {
  8571. // norm
  8572. cur = llm_build_norm(ctx0, inpL, hparams,
  8573. model.layers[il].attn_norm,
  8574. model.layers[il].attn_norm_b,
  8575. LLM_NORM, cb, il);
  8576. cb(cur, "attn_norm", il);
  8577. struct ggml_tensor * inpSA = cur;
  8578. // self-attention
  8579. {
  8580. // compute Q and K and RoPE them
  8581. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8582. cb(Qcur, "Qcur", il);
  8583. if (model.layers[il].bq) {
  8584. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8585. cb(Qcur, "Qcur", il);
  8586. }
  8587. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8588. cb(Kcur, "Kcur", il);
  8589. if (model.layers[il].bk) {
  8590. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8591. cb(Kcur, "Kcur", il);
  8592. }
  8593. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8594. cb(Vcur, "Vcur", il);
  8595. if (model.layers[il].bv) {
  8596. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8597. cb(Vcur, "Vcur", il);
  8598. }
  8599. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8600. cb(Qcur, "Qcur", il);
  8601. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8602. cb(Kcur, "Kcur", il);
  8603. if (model.layers[il].attn_q_norm) {
  8604. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8605. model.layers[il].attn_q_norm,
  8606. NULL,
  8607. LLM_NORM, cb, il);
  8608. cb(Qcur, "Qcur", il);
  8609. }
  8610. if (model.layers[il].attn_k_norm) {
  8611. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8612. model.layers[il].attn_k_norm,
  8613. NULL,
  8614. LLM_NORM, cb, il);
  8615. cb(Kcur, "Kcur", il);
  8616. }
  8617. Qcur = ggml_rope_ext(
  8618. ctx0, Qcur, inp_pos, nullptr,
  8619. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8620. ext_factor, attn_factor, beta_fast, beta_slow
  8621. );
  8622. cb(Qcur, "Qcur", il);
  8623. Kcur = ggml_rope_ext(
  8624. ctx0, Kcur, inp_pos, nullptr,
  8625. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8626. ext_factor, attn_factor, beta_fast, beta_slow
  8627. );
  8628. cb(Kcur, "Kcur", il);
  8629. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8630. model.layers[il].wo, NULL,
  8631. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8632. }
  8633. if (il == n_layer - 1) {
  8634. // skip computing output for unused tokens
  8635. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8636. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8637. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8638. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8639. }
  8640. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8641. cb(ffn_inp, "ffn_inp", il);
  8642. // feed-forward network
  8643. {
  8644. if (model.layers[il].ffn_norm) {
  8645. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8646. model.layers[il].ffn_norm,
  8647. model.layers[il].ffn_norm_b,
  8648. LLM_NORM, cb, il);
  8649. cb(cur, "ffn_norm", il);
  8650. } else {
  8651. // parallel residual
  8652. cur = inpSA;
  8653. }
  8654. cur = llm_build_ffn(ctx0, lctx, cur,
  8655. model.layers[il].ffn_up, NULL, NULL,
  8656. model.layers[il].ffn_gate, NULL, NULL,
  8657. model.layers[il].ffn_down, NULL, NULL,
  8658. NULL,
  8659. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8660. cb(cur, "ffn_out", il);
  8661. }
  8662. cur = ggml_add(ctx0, cur, ffn_inp);
  8663. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8664. cb(cur, "l_out", il);
  8665. // input for next layer
  8666. inpL = cur;
  8667. }
  8668. cur = inpL;
  8669. cur = llm_build_norm(ctx0, cur, hparams,
  8670. model.output_norm,
  8671. model.output_norm_b,
  8672. LLM_NORM, cb, -1);
  8673. cb(cur, "result_norm", -1);
  8674. // lm_head
  8675. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8676. cb(cur, "result_output", -1);
  8677. ggml_build_forward_expand(gf, cur);
  8678. return gf;
  8679. }
  8680. struct ggml_cgraph * build_qwen() {
  8681. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8682. const int64_t n_embd_head = hparams.n_embd_head_v;
  8683. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8684. struct ggml_tensor * cur;
  8685. struct ggml_tensor * inpL;
  8686. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8687. // inp_pos - contains the positions
  8688. struct ggml_tensor * inp_pos = build_inp_pos();
  8689. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8690. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8691. for (int il = 0; il < n_layer; ++il) {
  8692. struct ggml_tensor * inpSA = inpL;
  8693. cur = llm_build_norm(ctx0, inpL, hparams,
  8694. model.layers[il].attn_norm, NULL,
  8695. LLM_NORM_RMS, cb, il);
  8696. cb(cur, "attn_norm", il);
  8697. // self-attention
  8698. {
  8699. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8700. cb(cur, "wqkv", il);
  8701. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8702. cb(cur, "bqkv", il);
  8703. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8704. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8705. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  8706. cb(Qcur, "Qcur", il);
  8707. cb(Kcur, "Kcur", il);
  8708. cb(Vcur, "Vcur", il);
  8709. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8710. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8711. // using mode = 2 for neox mode
  8712. Qcur = ggml_rope_ext(
  8713. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8714. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8715. );
  8716. cb(Qcur, "Qcur", il);
  8717. Kcur = ggml_rope_ext(
  8718. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8719. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8720. );
  8721. cb(Kcur, "Kcur", il);
  8722. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8723. model.layers[il].wo, NULL,
  8724. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8725. }
  8726. if (il == n_layer - 1) {
  8727. // skip computing output for unused tokens
  8728. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8729. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8730. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8731. }
  8732. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8733. cb(ffn_inp, "ffn_inp", il);
  8734. // feed-forward forward
  8735. {
  8736. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8737. model.layers[il].ffn_norm, NULL,
  8738. LLM_NORM_RMS, cb, il);
  8739. cb(cur, "ffn_norm", il);
  8740. cur = llm_build_ffn(ctx0, lctx, cur,
  8741. model.layers[il].ffn_up, NULL, NULL,
  8742. model.layers[il].ffn_gate, NULL, NULL,
  8743. model.layers[il].ffn_down, NULL, NULL,
  8744. NULL,
  8745. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8746. cb(cur, "ffn_out", il);
  8747. }
  8748. cur = ggml_add(ctx0, cur, ffn_inp);
  8749. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8750. cb(cur, "l_out", il);
  8751. // input for next layer
  8752. inpL = cur;
  8753. }
  8754. cur = inpL;
  8755. cur = llm_build_norm(ctx0, cur, hparams,
  8756. model.output_norm, NULL,
  8757. LLM_NORM_RMS, cb, -1);
  8758. cb(cur, "result_norm", -1);
  8759. // lm_head
  8760. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8761. cb(cur, "result_output", -1);
  8762. ggml_build_forward_expand(gf, cur);
  8763. return gf;
  8764. }
  8765. struct ggml_cgraph * build_qwen2() {
  8766. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8767. const int64_t n_embd_head = hparams.n_embd_head_v;
  8768. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8769. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8770. struct ggml_tensor * cur;
  8771. struct ggml_tensor * inpL;
  8772. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8773. // inp_pos - contains the positions
  8774. struct ggml_tensor * inp_pos = build_inp_pos();
  8775. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8776. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8777. for (int il = 0; il < n_layer; ++il) {
  8778. struct ggml_tensor * inpSA = inpL;
  8779. // norm
  8780. cur = llm_build_norm(ctx0, inpL, hparams,
  8781. model.layers[il].attn_norm, NULL,
  8782. LLM_NORM_RMS, cb, il);
  8783. cb(cur, "attn_norm", il);
  8784. // self-attention
  8785. {
  8786. // compute Q and K and RoPE them
  8787. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8788. cb(Qcur, "Qcur", il);
  8789. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8790. cb(Qcur, "Qcur", il);
  8791. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8792. cb(Kcur, "Kcur", il);
  8793. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8794. cb(Kcur, "Kcur", il);
  8795. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8796. cb(Vcur, "Vcur", il);
  8797. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8798. cb(Vcur, "Vcur", il);
  8799. Qcur = ggml_rope_ext(
  8800. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8801. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8802. ext_factor, attn_factor, beta_fast, beta_slow
  8803. );
  8804. cb(Qcur, "Qcur", il);
  8805. Kcur = ggml_rope_ext(
  8806. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8807. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8808. ext_factor, attn_factor, beta_fast, beta_slow
  8809. );
  8810. cb(Kcur, "Kcur", il);
  8811. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8812. model.layers[il].wo, model.layers[il].bo,
  8813. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8814. }
  8815. if (il == n_layer - 1) {
  8816. // skip computing output for unused tokens
  8817. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8818. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8819. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8820. }
  8821. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8822. cb(ffn_inp, "ffn_inp", il);
  8823. // feed-forward network
  8824. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8825. model.layers[il].ffn_norm, NULL,
  8826. LLM_NORM_RMS, cb, il);
  8827. cb(cur, "ffn_norm", il);
  8828. cur = llm_build_ffn(ctx0, lctx, cur,
  8829. model.layers[il].ffn_up, NULL, NULL,
  8830. model.layers[il].ffn_gate, NULL, NULL,
  8831. model.layers[il].ffn_down, NULL, NULL,
  8832. NULL,
  8833. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8834. cb(cur, "ffn_out", il);
  8835. cur = ggml_add(ctx0, cur, ffn_inp);
  8836. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8837. cb(cur, "l_out", il);
  8838. // input for next layer
  8839. inpL = cur;
  8840. }
  8841. cur = inpL;
  8842. cur = llm_build_norm(ctx0, cur, hparams,
  8843. model.output_norm, NULL,
  8844. LLM_NORM_RMS, cb, -1);
  8845. cb(cur, "result_norm", -1);
  8846. // lm_head
  8847. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8848. cb(cur, "result_output", -1);
  8849. ggml_build_forward_expand(gf, cur);
  8850. return gf;
  8851. }
  8852. struct ggml_cgraph * build_qwen2moe() {
  8853. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8854. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8855. int32_t n_tokens = this->n_tokens;
  8856. const int64_t n_embd_head = hparams.n_embd_head_v;
  8857. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8858. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8859. struct ggml_tensor * cur;
  8860. struct ggml_tensor * inpL;
  8861. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8862. // inp_pos - contains the positions
  8863. struct ggml_tensor * inp_pos = build_inp_pos();
  8864. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8865. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8866. for (int il = 0; il < n_layer; ++il) {
  8867. struct ggml_tensor * inpSA = inpL;
  8868. // norm
  8869. cur = llm_build_norm(ctx0, inpL, hparams,
  8870. model.layers[il].attn_norm, NULL,
  8871. LLM_NORM_RMS, cb, il);
  8872. cb(cur, "attn_norm", il);
  8873. // self_attention
  8874. {
  8875. // compute Q and K and RoPE them
  8876. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8877. cb(Qcur, "Qcur", il);
  8878. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8879. cb(Qcur, "Qcur", il);
  8880. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8881. cb(Kcur, "Kcur", il);
  8882. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8883. cb(Kcur, "Kcur", il);
  8884. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8885. cb(Vcur, "Vcur", il);
  8886. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8887. cb(Vcur, "Vcur", il);
  8888. Qcur = ggml_rope_ext(
  8889. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8890. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8891. ext_factor, attn_factor, beta_fast, beta_slow
  8892. );
  8893. cb(Qcur, "Qcur", il);
  8894. Kcur = ggml_rope_ext(
  8895. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8896. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8897. ext_factor, attn_factor, beta_fast, beta_slow
  8898. );
  8899. cb(Kcur, "Kcur", il);
  8900. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8901. model.layers[il].wo, model.layers[il].bo,
  8902. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8903. }
  8904. if (il == n_layer - 1) {
  8905. // skip computing output for unused tokens
  8906. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8907. n_tokens = n_outputs;
  8908. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8909. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8910. }
  8911. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8912. cb(ffn_inp, "ffn_inp", il);
  8913. // MoE branch
  8914. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8915. model.layers[il].ffn_norm, NULL,
  8916. LLM_NORM_RMS, cb, il);
  8917. cb(cur, "ffn_norm", il);
  8918. ggml_tensor * moe_out =
  8919. llm_build_moe_ffn(ctx0, lctx, cur,
  8920. model.layers[il].ffn_gate_inp,
  8921. model.layers[il].ffn_up_exps,
  8922. model.layers[il].ffn_gate_exps,
  8923. model.layers[il].ffn_down_exps,
  8924. n_expert, n_expert_used,
  8925. LLM_FFN_SILU, false,
  8926. false, 0.0,
  8927. cb, il);
  8928. cb(cur, "ffn_moe_out", il);
  8929. // FFN shared expert
  8930. {
  8931. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  8932. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  8933. // sigmoid
  8934. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  8935. cb(cur_gate, "ffn_shexp_gate", il);
  8936. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  8937. model.layers[il].ffn_up_shexp, NULL, NULL,
  8938. model.layers[il].ffn_gate_shexp, NULL, NULL,
  8939. model.layers[il].ffn_down_shexp, NULL, NULL,
  8940. NULL,
  8941. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8942. cb(cur_ffn, "ffn_shexp", il);
  8943. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  8944. cb(ffn_shexp_out, "ffn_shexp_out", il);
  8945. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  8946. cb(moe_out, "ffn_out", il);
  8947. cur = moe_out;
  8948. }
  8949. cur = ggml_add(ctx0, cur, ffn_inp);
  8950. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8951. cb(cur, "l_out", il);
  8952. // input for next layer
  8953. inpL = cur;
  8954. }
  8955. cur = inpL;
  8956. cur = llm_build_norm(ctx0, cur, hparams,
  8957. model.output_norm, NULL,
  8958. LLM_NORM_RMS, cb, -1);
  8959. cb(cur, "result_norm", -1);
  8960. // lm_head
  8961. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8962. cb(cur, "result_output", -1);
  8963. ggml_build_forward_expand(gf, cur);
  8964. return gf;
  8965. }
  8966. struct ggml_cgraph * build_phi2() {
  8967. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8968. const int64_t n_embd_head = hparams.n_embd_head_v;
  8969. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8970. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8971. struct ggml_tensor * cur;
  8972. struct ggml_tensor * attn_norm_output;
  8973. struct ggml_tensor * ffn_output;
  8974. struct ggml_tensor * inpL;
  8975. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8976. // inp_pos - contains the positions
  8977. struct ggml_tensor * inp_pos = build_inp_pos();
  8978. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8979. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8980. for (int il = 0; il < n_layer; ++il) {
  8981. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  8982. model.layers[il].attn_norm,
  8983. model.layers[il].attn_norm_b,
  8984. LLM_NORM, cb, il);
  8985. cb(attn_norm_output, "attn_norm", il);
  8986. // self-attention
  8987. {
  8988. struct ggml_tensor * Qcur = nullptr;
  8989. struct ggml_tensor * Kcur = nullptr;
  8990. struct ggml_tensor * Vcur = nullptr;
  8991. if (model.layers[il].wqkv) {
  8992. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  8993. cb(cur, "wqkv", il);
  8994. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8995. cb(cur, "bqkv", il);
  8996. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8997. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8998. 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)));
  8999. } else {
  9000. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9001. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9002. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9003. }
  9004. cb(Qcur, "Qcur", il);
  9005. cb(Kcur, "Kcur", il);
  9006. cb(Vcur, "Vcur", il);
  9007. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9008. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9009. Qcur = ggml_rope_ext(
  9010. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9011. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9012. );
  9013. cb(Qcur, "Qcur", il);
  9014. // with phi2, we scale the Q to avoid precision issues
  9015. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  9016. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  9017. cb(Qcur, "Qcur", il);
  9018. Kcur = ggml_rope_ext(
  9019. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9020. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9021. );
  9022. cb(Kcur, "Kcur", il);
  9023. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9024. model.layers[il].wo, model.layers[il].bo,
  9025. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9026. }
  9027. if (il == n_layer - 1) {
  9028. // skip computing output for unused tokens
  9029. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9030. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9031. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9032. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  9033. }
  9034. // FF
  9035. {
  9036. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  9037. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9038. NULL, NULL, NULL,
  9039. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9040. NULL,
  9041. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9042. cb(ffn_output, "ffn_out", il);
  9043. }
  9044. cur = ggml_add(ctx0, cur, ffn_output);
  9045. cur = ggml_add(ctx0, cur, inpL);
  9046. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9047. cb(cur, "l_out", il);
  9048. // input for next layer
  9049. inpL = cur;
  9050. }
  9051. cur = llm_build_norm(ctx0, inpL, hparams,
  9052. model.output_norm,
  9053. model.output_norm_b,
  9054. LLM_NORM, cb, -1);
  9055. cb(cur, "result_norm", -1);
  9056. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9057. cb(cur, "result_output_no_bias", -1);
  9058. cur = ggml_add(ctx0, cur, model.output_b);
  9059. cb(cur, "result_output", -1);
  9060. ggml_build_forward_expand(gf, cur);
  9061. return gf;
  9062. }
  9063. struct ggml_cgraph * build_phi3() {
  9064. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9065. const int64_t n_embd_head = hparams.n_embd_head_v;
  9066. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9067. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9068. struct ggml_tensor * cur;
  9069. struct ggml_tensor * inpL;
  9070. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9071. // inp_pos - contains the positions
  9072. struct ggml_tensor * inp_pos = build_inp_pos();
  9073. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9074. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  9075. for (int il = 0; il < n_layer; ++il) {
  9076. auto residual = inpL;
  9077. // self-attention
  9078. {
  9079. // rope freq factors for 128k context
  9080. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9081. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9082. model.layers[il].attn_norm,
  9083. NULL,
  9084. LLM_NORM_RMS, cb, il);
  9085. cb(attn_norm_output, "attn_norm", il);
  9086. struct ggml_tensor * Qcur = nullptr;
  9087. struct ggml_tensor * Kcur = nullptr;
  9088. struct ggml_tensor * Vcur = nullptr;
  9089. if (model.layers[il].wqkv) {
  9090. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9091. cb(cur, "wqkv", il);
  9092. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  9093. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  9094. 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)));
  9095. }
  9096. else {
  9097. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9098. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9099. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9100. }
  9101. cb(Qcur, "Qcur", il);
  9102. cb(Kcur, "Kcur", il);
  9103. cb(Vcur, "Vcur", il);
  9104. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9105. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9106. Qcur = ggml_rope_ext(
  9107. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9108. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9109. );
  9110. cb(Qcur, "Qcur", il);
  9111. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  9112. cb(Qcur, "Qcur", il);
  9113. Kcur = ggml_rope_ext(
  9114. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9115. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9116. );
  9117. cb(Kcur, "Kcur", il);
  9118. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9119. model.layers[il].wo, model.layers[il].bo,
  9120. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9121. }
  9122. if (il == n_layer - 1) {
  9123. // skip computing output for unused tokens
  9124. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  9125. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9126. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  9127. }
  9128. cur = ggml_add(ctx0, cur, residual);
  9129. residual = cur;
  9130. cur = llm_build_norm(ctx0, cur, hparams,
  9131. model.layers[il].ffn_norm, NULL,
  9132. LLM_NORM_RMS, cb, il);
  9133. cb(cur, "ffn_norm", il);
  9134. // FF
  9135. // special-case: the up and gate tensors are merged into a single tensor
  9136. // TOOD: support into llm_build_ffn
  9137. {
  9138. cur = llm_build_ffn(ctx0, lctx, cur,
  9139. model.layers[il].ffn_up, NULL, NULL,
  9140. NULL, NULL, NULL,
  9141. model.layers[il].ffn_down, NULL, NULL,
  9142. NULL,
  9143. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  9144. cb(cur, "ffn_out", il);
  9145. }
  9146. cur = ggml_add(ctx0, residual, cur);
  9147. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9148. cb(cur, "l_out", il);
  9149. // input for next layer
  9150. inpL = cur;
  9151. }
  9152. cur = llm_build_norm(ctx0, inpL, hparams,
  9153. model.output_norm,
  9154. NULL,
  9155. LLM_NORM_RMS, cb, -1);
  9156. cb(cur, "result_norm", -1);
  9157. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9158. cb(cur, "result_output", -1);
  9159. ggml_build_forward_expand(gf, cur);
  9160. return gf;
  9161. }
  9162. struct ggml_cgraph * build_plamo() {
  9163. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  9164. const int64_t n_embd_head = hparams.n_embd_head_v;
  9165. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9166. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9167. struct ggml_tensor * cur;
  9168. struct ggml_tensor * inpL;
  9169. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9170. // inp_pos - contains the positions
  9171. struct ggml_tensor * inp_pos = build_inp_pos();
  9172. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9173. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9174. for (int il = 0; il < n_layer; ++il) {
  9175. // norm
  9176. cur = llm_build_norm(ctx0, inpL, hparams,
  9177. model.layers[il].attn_norm, NULL,
  9178. LLM_NORM_RMS, cb, il);
  9179. cb(cur, "attn_norm", il);
  9180. struct ggml_tensor * attention_norm = cur;
  9181. // self-attention
  9182. {
  9183. // compute Q and K and RoPE them
  9184. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9185. cb(Qcur, "Qcur", il);
  9186. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9187. cb(Kcur, "Kcur", il);
  9188. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9189. cb(Vcur, "Vcur", il);
  9190. Qcur = ggml_rope_ext(
  9191. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  9192. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9193. ext_factor, attn_factor, beta_fast, beta_slow);
  9194. cb(Qcur, "Qcur", il);
  9195. Kcur = ggml_rope_ext(
  9196. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  9197. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9198. ext_factor, attn_factor, beta_fast, beta_slow);
  9199. cb(Kcur, "Kcur", il);
  9200. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9201. model.layers[il].wo, NULL,
  9202. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9203. }
  9204. struct ggml_tensor * sa_out = cur;
  9205. cur = attention_norm;
  9206. if (il == n_layer - 1) {
  9207. // skip computing output for unused tokens
  9208. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9209. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9210. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  9211. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9212. }
  9213. // feed-forward network
  9214. {
  9215. cur = llm_build_ffn(ctx0, lctx, cur,
  9216. model.layers[il].ffn_up, NULL, NULL,
  9217. model.layers[il].ffn_gate, NULL, NULL,
  9218. model.layers[il].ffn_down, NULL, NULL,
  9219. NULL,
  9220. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9221. cb(cur, "ffn_out", il);
  9222. }
  9223. cur = ggml_add(ctx0, cur, sa_out);
  9224. cur = ggml_add(ctx0, cur, inpL);
  9225. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9226. cb(cur, "l_out", il);
  9227. // input for next layer
  9228. inpL = cur;
  9229. }
  9230. cur = inpL;
  9231. cur = llm_build_norm(ctx0, cur, hparams,
  9232. model.output_norm, NULL,
  9233. LLM_NORM_RMS, cb, -1);
  9234. cb(cur, "result_norm", -1);
  9235. // lm_head
  9236. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9237. cb(cur, "result_output", -1);
  9238. ggml_build_forward_expand(gf, cur);
  9239. return gf;
  9240. }
  9241. struct ggml_cgraph * build_gpt2() {
  9242. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9243. const int64_t n_embd_head = hparams.n_embd_head_v;
  9244. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9245. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9246. struct ggml_tensor * cur;
  9247. struct ggml_tensor * pos;
  9248. struct ggml_tensor * inpL;
  9249. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9250. // inp_pos - contains the positions
  9251. struct ggml_tensor * inp_pos = build_inp_pos();
  9252. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9253. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9254. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  9255. cb(pos, "pos_embd", -1);
  9256. inpL = ggml_add(ctx0, inpL, pos);
  9257. cb(inpL, "inpL", -1);
  9258. for (int il = 0; il < n_layer; ++il) {
  9259. cur = llm_build_norm(ctx0, inpL, hparams,
  9260. model.layers[il].attn_norm,
  9261. model.layers[il].attn_norm_b,
  9262. LLM_NORM, cb, il);
  9263. cb(cur, "attn_norm", il);
  9264. // self-attention
  9265. {
  9266. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9267. cb(cur, "wqkv", il);
  9268. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9269. cb(cur, "bqkv", il);
  9270. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9271. 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)));
  9272. 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)));
  9273. cb(Qcur, "Qcur", il);
  9274. cb(Kcur, "Kcur", il);
  9275. cb(Vcur, "Vcur", il);
  9276. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9277. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9278. model.layers[il].wo, model.layers[il].bo,
  9279. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9280. }
  9281. if (il == n_layer - 1) {
  9282. // skip computing output for unused tokens
  9283. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9284. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9285. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9286. }
  9287. // add the input
  9288. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9289. cb(ffn_inp, "ffn_inp", il);
  9290. // FF
  9291. {
  9292. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9293. model.layers[il].ffn_norm,
  9294. model.layers[il].ffn_norm_b,
  9295. LLM_NORM, cb, il);
  9296. cb(cur, "ffn_norm", il);
  9297. cur = llm_build_ffn(ctx0, lctx, cur,
  9298. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9299. NULL, NULL, NULL,
  9300. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9301. NULL,
  9302. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9303. cb(cur, "ffn_out", il);
  9304. }
  9305. cur = ggml_add(ctx0, cur, ffn_inp);
  9306. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9307. cb(cur, "l_out", il);
  9308. // input for next layer
  9309. inpL = cur;
  9310. }
  9311. cur = llm_build_norm(ctx0, inpL, hparams,
  9312. model.output_norm,
  9313. model.output_norm_b,
  9314. LLM_NORM, cb, -1);
  9315. cb(cur, "result_norm", -1);
  9316. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9317. cb(cur, "result_output", -1);
  9318. ggml_build_forward_expand(gf, cur);
  9319. return gf;
  9320. }
  9321. struct ggml_cgraph * build_codeshell() {
  9322. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9323. const int64_t n_embd_head = hparams.n_embd_head_v;
  9324. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9325. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9326. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9327. struct ggml_tensor * cur;
  9328. struct ggml_tensor * inpL;
  9329. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9330. // inp_pos - contains the positions
  9331. struct ggml_tensor * inp_pos = build_inp_pos();
  9332. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9333. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9334. for (int il = 0; il < n_layer; ++il) {
  9335. cur = llm_build_norm(ctx0, inpL, hparams,
  9336. model.layers[il].attn_norm,
  9337. model.layers[il].attn_norm_b,
  9338. LLM_NORM, cb, il);
  9339. cb(cur, "attn_norm", il);
  9340. // self-attention
  9341. {
  9342. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9343. cb(cur, "wqkv", il);
  9344. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9345. cb(cur, "bqkv", il);
  9346. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9347. 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)));
  9348. 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)));
  9349. cb(tmpq, "tmpq", il);
  9350. cb(tmpk, "tmpk", il);
  9351. cb(Vcur, "Vcur", il);
  9352. struct ggml_tensor * Qcur = ggml_rope_ext(
  9353. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9354. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9355. ext_factor, attn_factor, beta_fast, beta_slow
  9356. );
  9357. cb(Qcur, "Qcur", il);
  9358. struct ggml_tensor * Kcur = ggml_rope_ext(
  9359. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9360. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9361. ext_factor, attn_factor, beta_fast, beta_slow
  9362. );
  9363. cb(Kcur, "Kcur", il);
  9364. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9365. model.layers[il].wo, model.layers[il].bo,
  9366. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9367. }
  9368. if (il == n_layer - 1) {
  9369. // skip computing output for unused tokens
  9370. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9371. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9372. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9373. }
  9374. // add the input
  9375. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9376. cb(ffn_inp, "ffn_inp", il);
  9377. // FF
  9378. {
  9379. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9380. model.layers[il].ffn_norm,
  9381. model.layers[il].ffn_norm_b,
  9382. LLM_NORM, cb, il);
  9383. cb(cur, "ffn_norm", il);
  9384. cur = llm_build_ffn(ctx0, lctx, cur,
  9385. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9386. NULL, NULL, NULL,
  9387. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9388. NULL,
  9389. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9390. cb(cur, "ffn_out", il);
  9391. }
  9392. cur = ggml_add(ctx0, cur, ffn_inp);
  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 = llm_build_norm(ctx0, inpL, hparams,
  9399. model.output_norm,
  9400. model.output_norm_b,
  9401. LLM_NORM, cb, -1);
  9402. cb(cur, "result_norm", -1);
  9403. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9404. cb(cur, "result_output", -1);
  9405. ggml_build_forward_expand(gf, cur);
  9406. return gf;
  9407. }
  9408. struct ggml_cgraph * build_orion() {
  9409. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9410. const int64_t n_embd_head = hparams.n_embd_head_v;
  9411. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9412. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9413. struct ggml_tensor * cur;
  9414. struct ggml_tensor * inpL;
  9415. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9416. // inp_pos - contains the positions
  9417. struct ggml_tensor * inp_pos = build_inp_pos();
  9418. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9419. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9420. for (int il = 0; il < n_layer; ++il) {
  9421. struct ggml_tensor * inpSA = inpL;
  9422. // norm
  9423. cur = llm_build_norm(ctx0, inpL, hparams,
  9424. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9425. LLM_NORM, cb, il);
  9426. cb(cur, "attn_norm", il);
  9427. // self-attention
  9428. {
  9429. // compute Q and K and RoPE them
  9430. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9431. cb(Qcur, "Qcur", il);
  9432. // if (model.layers[il].bq) {
  9433. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9434. // cb(Qcur, "Qcur", il);
  9435. // }
  9436. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9437. cb(Kcur, "Kcur", il);
  9438. // if (model.layers[il].bk) {
  9439. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9440. // cb(Kcur, "Kcur", il);
  9441. // }
  9442. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9443. cb(Vcur, "Vcur", il);
  9444. // if (model.layers[il].bv) {
  9445. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9446. // cb(Vcur, "Vcur", il);
  9447. // }
  9448. Qcur = ggml_rope_ext(
  9449. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9450. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9451. ext_factor, attn_factor, beta_fast, beta_slow
  9452. );
  9453. cb(Qcur, "Qcur", il);
  9454. Kcur = ggml_rope_ext(
  9455. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, 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(Kcur, "Kcur", il);
  9460. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9461. model.layers[il].wo, NULL,
  9462. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9463. }
  9464. if (il == n_layer - 1) {
  9465. // skip computing output for unused tokens
  9466. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9467. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9468. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9469. }
  9470. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9471. cb(ffn_inp, "ffn_inp", il);
  9472. // feed-forward network
  9473. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9474. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9475. LLM_NORM, cb, il);
  9476. cb(cur, "ffn_norm", il);
  9477. cur = llm_build_ffn(ctx0, lctx, cur,
  9478. model.layers[il].ffn_up, NULL, NULL,
  9479. model.layers[il].ffn_gate, NULL, NULL,
  9480. model.layers[il].ffn_down, NULL, NULL,
  9481. NULL,
  9482. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9483. cb(cur, "ffn_out", il);
  9484. cur = ggml_add(ctx0, cur, ffn_inp);
  9485. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9486. cb(cur, "l_out", il);
  9487. // input for next layer
  9488. inpL = cur;
  9489. }
  9490. cur = inpL;
  9491. cur = llm_build_norm(ctx0, cur, hparams,
  9492. model.output_norm, model.output_norm_b,
  9493. LLM_NORM, cb, -1);
  9494. cb(cur, "result_norm", -1);
  9495. // lm_head
  9496. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9497. cb(cur, "result_output", -1);
  9498. ggml_build_forward_expand(gf, cur);
  9499. return gf;
  9500. }
  9501. struct ggml_cgraph * build_internlm2() {
  9502. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9503. const int64_t n_embd_head = hparams.n_embd_head_v;
  9504. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9505. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9506. struct ggml_tensor * cur;
  9507. struct ggml_tensor * inpL;
  9508. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9509. // inp_pos - contains the positions
  9510. struct ggml_tensor * inp_pos = build_inp_pos();
  9511. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9512. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9513. for (int il = 0; il < n_layer; ++il) {
  9514. struct ggml_tensor * inpSA = inpL;
  9515. // norm
  9516. cur = llm_build_norm(ctx0, inpL, hparams,
  9517. model.layers[il].attn_norm, NULL,
  9518. LLM_NORM_RMS, cb, il);
  9519. cb(cur, "attn_norm", il);
  9520. // self-attention
  9521. {
  9522. // compute Q and K and RoPE them
  9523. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9524. cb(Qcur, "Qcur", il);
  9525. if (model.layers[il].bq) {
  9526. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9527. cb(Qcur, "Qcur", il);
  9528. }
  9529. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9530. cb(Kcur, "Kcur", il);
  9531. if (model.layers[il].bk) {
  9532. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9533. cb(Kcur, "Kcur", il);
  9534. }
  9535. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9536. cb(Vcur, "Vcur", il);
  9537. if (model.layers[il].bv) {
  9538. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9539. cb(Vcur, "Vcur", il);
  9540. }
  9541. Qcur = ggml_rope_ext(
  9542. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9543. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9544. ext_factor, attn_factor, beta_fast, beta_slow
  9545. );
  9546. cb(Qcur, "Qcur", il);
  9547. Kcur = ggml_rope_ext(
  9548. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9549. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9550. ext_factor, attn_factor, beta_fast, beta_slow
  9551. );
  9552. cb(Kcur, "Kcur", il);
  9553. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9554. model.layers[il].wo, model.layers[il].bo,
  9555. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9556. }
  9557. if (il == n_layer - 1) {
  9558. // skip computing output for unused tokens
  9559. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9560. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9561. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9562. }
  9563. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9564. cb(ffn_inp, "ffn_inp", il);
  9565. // feed-forward network
  9566. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9567. model.layers[il].ffn_norm, NULL,
  9568. LLM_NORM_RMS, cb, il);
  9569. cb(cur, "ffn_norm", il);
  9570. cur = llm_build_ffn(ctx0, lctx, cur,
  9571. model.layers[il].ffn_up, NULL, NULL,
  9572. model.layers[il].ffn_gate, NULL, NULL,
  9573. model.layers[il].ffn_down, NULL, NULL,
  9574. NULL,
  9575. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9576. cb(cur, "ffn_out", il);
  9577. cur = ggml_add(ctx0, cur, ffn_inp);
  9578. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9579. cb(cur, "l_out", il);
  9580. // input for next layer
  9581. inpL = cur;
  9582. }
  9583. cur = inpL;
  9584. cur = llm_build_norm(ctx0, cur, hparams,
  9585. model.output_norm, NULL,
  9586. LLM_NORM_RMS, cb, -1);
  9587. cb(cur, "result_norm", -1);
  9588. // lm_head
  9589. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9590. cb(cur, "result_output", -1);
  9591. ggml_build_forward_expand(gf, cur);
  9592. return gf;
  9593. }
  9594. // ref: https://arxiv.org/abs/2203.03466
  9595. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  9596. // based on the original build_llama() function
  9597. struct ggml_cgraph * build_minicpm() {
  9598. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9599. const int64_t n_embd_head = hparams.n_embd_head_v;
  9600. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9601. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9602. const int64_t n_embd = hparams.n_embd;
  9603. //TODO: if the model varies, these parameters need to be read from the model
  9604. const int64_t n_embd_base = 256;
  9605. const float scale_embd = 12.0f;
  9606. const float scale_depth = 1.4f;
  9607. struct ggml_tensor * cur;
  9608. struct ggml_tensor * inpL;
  9609. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9610. // scale the input embeddings
  9611. inpL = ggml_scale(ctx0, inpL, scale_embd);
  9612. cb(inpL, "inp_scaled", -1);
  9613. // inp_pos - contains the positions
  9614. struct ggml_tensor * inp_pos = build_inp_pos();
  9615. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9616. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9617. for (int il = 0; il < n_layer; ++il) {
  9618. struct ggml_tensor * inpSA = inpL;
  9619. // norm
  9620. cur = llm_build_norm(ctx0, inpL, hparams,
  9621. model.layers[il].attn_norm, NULL,
  9622. LLM_NORM_RMS, cb, il);
  9623. cb(cur, "attn_norm", il);
  9624. // self-attention
  9625. {
  9626. // compute Q and K and RoPE them
  9627. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9628. cb(Qcur, "Qcur", il);
  9629. if (model.layers[il].bq) {
  9630. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9631. cb(Qcur, "Qcur", il);
  9632. }
  9633. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9634. cb(Kcur, "Kcur", il);
  9635. if (model.layers[il].bk) {
  9636. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9637. cb(Kcur, "Kcur", il);
  9638. }
  9639. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9640. cb(Vcur, "Vcur", il);
  9641. if (model.layers[il].bv) {
  9642. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9643. cb(Vcur, "Vcur", il);
  9644. }
  9645. Qcur = ggml_rope_ext(
  9646. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9647. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9648. ext_factor, attn_factor, beta_fast, beta_slow
  9649. );
  9650. cb(Qcur, "Qcur", il);
  9651. Kcur = ggml_rope_ext(
  9652. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9653. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9654. ext_factor, attn_factor, beta_fast, beta_slow
  9655. );
  9656. cb(Kcur, "Kcur", il);
  9657. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9658. model.layers[il].wo, model.layers[il].bo,
  9659. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9660. }
  9661. if (il == n_layer - 1) {
  9662. // skip computing output for unused tokens
  9663. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9664. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9665. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9666. }
  9667. // scale_res - scale the hidden states for residual connection
  9668. const float scale_res = scale_depth/sqrtf(float(n_layer));
  9669. cur = ggml_scale(ctx0, cur, scale_res);
  9670. cb(cur, "hidden_scaled", -1);
  9671. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9672. cb(ffn_inp, "ffn_inp", il);
  9673. // feed-forward network
  9674. {
  9675. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9676. model.layers[il].ffn_norm, NULL,
  9677. LLM_NORM_RMS, cb, il);
  9678. cb(cur, "ffn_norm", il);
  9679. cur = llm_build_ffn(ctx0, lctx, cur,
  9680. model.layers[il].ffn_up, NULL, NULL,
  9681. model.layers[il].ffn_gate, NULL, NULL,
  9682. model.layers[il].ffn_down, NULL, NULL,
  9683. NULL,
  9684. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9685. cb(cur, "ffn_out", il);
  9686. }
  9687. // scale the hidden states for residual connection
  9688. cur = ggml_scale(ctx0, cur, scale_res);
  9689. cb(cur, "hidden_scaled_ffn", -1);
  9690. cur = ggml_add(ctx0, cur, ffn_inp);
  9691. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9692. cb(cur, "l_out", il);
  9693. // input for next layer
  9694. inpL = cur;
  9695. }
  9696. cur = inpL;
  9697. cur = llm_build_norm(ctx0, cur, hparams,
  9698. model.output_norm, NULL,
  9699. LLM_NORM_RMS, cb, -1);
  9700. cb(cur, "result_norm", -1);
  9701. // lm_head scaling
  9702. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  9703. cur = ggml_scale(ctx0, cur, scale_lmhead);
  9704. cb(cur, "lmhead_scaling", -1);
  9705. // lm_head
  9706. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9707. cb(cur, "result_output", -1);
  9708. ggml_build_forward_expand(gf, cur);
  9709. return gf;
  9710. }
  9711. struct ggml_cgraph * build_gemma() {
  9712. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9713. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9714. struct ggml_tensor * cur;
  9715. struct ggml_tensor * inpL;
  9716. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9717. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9718. cb(inpL, "inp_scaled", -1);
  9719. // inp_pos - contains the positions
  9720. struct ggml_tensor * inp_pos = build_inp_pos();
  9721. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9722. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9723. for (int il = 0; il < n_layer; ++il) {
  9724. // norm
  9725. cur = llm_build_norm(ctx0, inpL, hparams,
  9726. model.layers[il].attn_norm, NULL,
  9727. LLM_NORM_RMS, cb, il);
  9728. cb(cur, "attn_norm", il);
  9729. // self-attention
  9730. {
  9731. // compute Q and K and RoPE them
  9732. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9733. cb(Qcur, "Qcur", il);
  9734. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9735. cb(Kcur, "Kcur", il);
  9736. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9737. cb(Vcur, "Vcur", il);
  9738. Qcur = ggml_rope_ext(
  9739. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9740. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9741. ext_factor, attn_factor, beta_fast, beta_slow);
  9742. cb(Qcur, "Qcur", il);
  9743. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  9744. cb(Qcur, "Qcur_scaled", il);
  9745. Kcur = ggml_rope_ext(
  9746. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9747. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9748. ext_factor, attn_factor, beta_fast, beta_slow);
  9749. cb(Kcur, "Kcur", il);
  9750. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9751. model.layers[il].wo, NULL,
  9752. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9753. }
  9754. if (il == n_layer - 1) {
  9755. // skip computing output for unused tokens
  9756. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9757. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9758. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9759. }
  9760. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9761. cb(sa_out, "sa_out", il);
  9762. cur = llm_build_norm(ctx0, sa_out, hparams,
  9763. model.layers[il].ffn_norm, NULL,
  9764. LLM_NORM_RMS, cb, il);
  9765. cb(cur, "ffn_norm", il);
  9766. // feed-forward network
  9767. {
  9768. cur = llm_build_ffn(ctx0, lctx, cur,
  9769. model.layers[il].ffn_up, NULL, NULL,
  9770. model.layers[il].ffn_gate, NULL, NULL,
  9771. model.layers[il].ffn_down, NULL, NULL,
  9772. NULL,
  9773. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9774. cb(cur, "ffn_out", il);
  9775. }
  9776. cur = ggml_add(ctx0, cur, sa_out);
  9777. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9778. cb(cur, "l_out", il);
  9779. // input for next layer
  9780. inpL = cur;
  9781. }
  9782. cur = inpL;
  9783. cur = llm_build_norm(ctx0, cur, hparams,
  9784. model.output_norm, NULL,
  9785. LLM_NORM_RMS, cb, -1);
  9786. cb(cur, "result_norm", -1);
  9787. // lm_head
  9788. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9789. cb(cur, "result_output", -1);
  9790. ggml_build_forward_expand(gf, cur);
  9791. return gf;
  9792. }
  9793. struct ggml_cgraph * build_gemma2() {
  9794. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9795. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9796. struct ggml_tensor * cur;
  9797. struct ggml_tensor * inpL;
  9798. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9799. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9800. cb(inpL, "inp_scaled", -1);
  9801. // inp_pos - contains the positions
  9802. struct ggml_tensor * inp_pos = build_inp_pos();
  9803. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9804. // gemma 2 requires different mask for layers using sliding window (SWA)
  9805. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  9806. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  9807. for (int il = 0; il < n_layer; ++il) {
  9808. // (il % 2) layers use SWA
  9809. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  9810. // norm
  9811. cur = llm_build_norm(ctx0, inpL, hparams,
  9812. model.layers[il].attn_norm, NULL,
  9813. LLM_NORM_RMS, cb, il);
  9814. cb(cur, "attn_norm", il);
  9815. // self-attention
  9816. {
  9817. // compute Q and K and RoPE them
  9818. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9819. cb(Qcur, "Qcur", il);
  9820. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9821. cb(Kcur, "Kcur", il);
  9822. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9823. cb(Vcur, "Vcur", il);
  9824. Qcur = ggml_rope_ext(
  9825. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9826. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9827. ext_factor, attn_factor, beta_fast, beta_slow);
  9828. cb(Qcur, "Qcur", il);
  9829. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  9830. switch (model.type) {
  9831. case e_model::MODEL_2B:
  9832. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  9833. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  9834. default: GGML_ABORT("fatal error");
  9835. };
  9836. cb(Qcur, "Qcur_scaled", il);
  9837. Kcur = ggml_rope_ext(
  9838. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9839. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9840. ext_factor, attn_factor, beta_fast, beta_slow);
  9841. cb(Kcur, "Kcur", il);
  9842. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9843. model.layers[il].wo, NULL,
  9844. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9845. }
  9846. cur = llm_build_norm(ctx0, cur, hparams,
  9847. model.layers[il].attn_post_norm, NULL,
  9848. LLM_NORM_RMS, cb, il);
  9849. cb(cur, "attn_post_norm", il);
  9850. if (il == n_layer - 1) {
  9851. // skip computing output for unused tokens
  9852. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9853. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9854. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9855. }
  9856. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9857. cb(sa_out, "sa_out", il);
  9858. cur = llm_build_norm(ctx0, sa_out, hparams,
  9859. model.layers[il].ffn_norm, NULL,
  9860. LLM_NORM_RMS, cb, il);
  9861. cb(cur, "ffn_norm", il);
  9862. // feed-forward network
  9863. {
  9864. cur = llm_build_ffn(ctx0, lctx, cur,
  9865. model.layers[il].ffn_up, NULL, NULL,
  9866. model.layers[il].ffn_gate, NULL, NULL,
  9867. model.layers[il].ffn_down, NULL, NULL,
  9868. NULL,
  9869. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9870. cb(cur, "ffn_out", il);
  9871. }
  9872. cur = llm_build_norm(ctx0, cur, hparams,
  9873. model.layers[il].ffn_post_norm, NULL,
  9874. LLM_NORM_RMS, cb, -1);
  9875. cb(cur, "ffn_post_norm", -1);
  9876. cur = ggml_add(ctx0, cur, sa_out);
  9877. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9878. cb(cur, "l_out", il);
  9879. // input for next layer
  9880. inpL = cur;
  9881. }
  9882. cur = inpL;
  9883. cur = llm_build_norm(ctx0, cur, hparams,
  9884. model.output_norm, NULL,
  9885. LLM_NORM_RMS, cb, -1);
  9886. cb(cur, "result_norm", -1);
  9887. // lm_head
  9888. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9889. // final logit soft-capping
  9890. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  9891. cur = ggml_tanh(ctx0, cur);
  9892. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  9893. cb(cur, "result_output", -1);
  9894. ggml_build_forward_expand(gf, cur);
  9895. return gf;
  9896. }
  9897. struct ggml_cgraph * build_starcoder2() {
  9898. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9899. const int64_t n_embd_head = hparams.n_embd_head_v;
  9900. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9901. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9902. struct ggml_tensor * cur;
  9903. struct ggml_tensor * inpL;
  9904. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9905. // inp_pos - contains the positions
  9906. struct ggml_tensor * inp_pos = build_inp_pos();
  9907. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9908. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9909. for (int il = 0; il < n_layer; ++il) {
  9910. struct ggml_tensor * inpSA = inpL;
  9911. // norm
  9912. cur = llm_build_norm(ctx0, inpL, hparams,
  9913. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9914. LLM_NORM, cb, il);
  9915. cb(cur, "attn_norm", il);
  9916. // self-attention
  9917. {
  9918. // compute Q and K and RoPE them
  9919. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9920. cb(Qcur, "Qcur", il);
  9921. if (model.layers[il].bq) {
  9922. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9923. cb(Qcur, "Qcur", il);
  9924. }
  9925. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9926. cb(Kcur, "Kcur", il);
  9927. if (model.layers[il].bk) {
  9928. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9929. cb(Kcur, "Kcur", il);
  9930. }
  9931. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9932. cb(Vcur, "Vcur", il);
  9933. if (model.layers[il].bv) {
  9934. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9935. cb(Vcur, "Vcur", il);
  9936. }
  9937. Qcur = ggml_rope_ext(
  9938. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9939. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9940. ext_factor, attn_factor, beta_fast, beta_slow
  9941. );
  9942. cb(Qcur, "Qcur", il);
  9943. Kcur = ggml_rope_ext(
  9944. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9945. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9946. ext_factor, attn_factor, beta_fast, beta_slow
  9947. );
  9948. cb(Kcur, "Kcur", il);
  9949. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9950. model.layers[il].wo, model.layers[il].bo,
  9951. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9952. }
  9953. if (il == n_layer - 1) {
  9954. // skip computing output for unused tokens
  9955. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9956. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9957. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9958. }
  9959. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9960. cb(ffn_inp, "ffn_inp", il);
  9961. // feed-forward network
  9962. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9963. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9964. LLM_NORM, cb, il);
  9965. cb(cur, "ffn_norm", il);
  9966. cur = llm_build_ffn(ctx0, lctx, cur,
  9967. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9968. NULL, NULL, NULL,
  9969. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9970. NULL,
  9971. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9972. cb(cur, "ffn_out", il);
  9973. cur = ggml_add(ctx0, cur, ffn_inp);
  9974. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9975. cb(cur, "l_out", il);
  9976. // input for next layer
  9977. inpL = cur;
  9978. }
  9979. cur = inpL;
  9980. cur = llm_build_norm(ctx0, cur, hparams,
  9981. model.output_norm, model.output_norm_b,
  9982. LLM_NORM, cb, -1);
  9983. cb(cur, "result_norm", -1);
  9984. // lm_head
  9985. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9986. cb(cur, "result_output", -1);
  9987. ggml_build_forward_expand(gf, cur);
  9988. return gf;
  9989. }
  9990. struct ggml_cgraph * build_mamba() {
  9991. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9992. const int64_t d_model = n_embd;
  9993. const int64_t d_conv = hparams.ssm_d_conv;
  9994. const int64_t d_inner = hparams.ssm_d_inner;
  9995. GGML_ASSERT(2 * d_model == d_inner);
  9996. const int64_t d_state = hparams.ssm_d_state;
  9997. const int64_t dt_rank = hparams.ssm_dt_rank;
  9998. struct ggml_tensor * cur;
  9999. struct ggml_tensor * inpL;
  10000. // {n_embd, n_tokens}
  10001. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10002. struct ggml_tensor * state_mask = build_inp_s_mask();
  10003. struct ggml_tensor * state_seq = build_inp_s_seq();
  10004. for (int il = 0; il < n_layer; ++il) {
  10005. // (ab)using the KV cache to store the states
  10006. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  10007. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  10008. // clear states of sequences which are starting at the beginning of this batch
  10009. {
  10010. conv_states = ggml_mul(ctx0,
  10011. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  10012. state_mask);
  10013. ssm_states = ggml_mul(ctx0,
  10014. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  10015. state_mask);
  10016. }
  10017. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  10018. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  10019. // norm
  10020. cur = llm_build_norm(ctx0, inpL, hparams,
  10021. model.layers[il].attn_norm, NULL,
  10022. LLM_NORM_RMS, cb, il);
  10023. cb(cur, "attn_norm", il);
  10024. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  10025. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_in, cur);
  10026. // split the above in two
  10027. // => {d_inner, n_tokens}
  10028. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  10029. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  10030. // conv
  10031. {
  10032. // Custom operator which is needed only to ease simultaneous sequence processing.
  10033. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  10034. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  10035. // then element-wise multiply that with the conv1d weigth,
  10036. // then sum the elements of each row,
  10037. // (the last two steps are a dot product over rows (also doable with mul_mat))
  10038. // then permute away the ne[0] dimension,
  10039. // and then you're left with the resulting x tensor.
  10040. // The new conv_states is the last (d_conv - 1) columns
  10041. // of the last 3rd dimensional "layer" of the self-overlapping view.
  10042. // For simultaneous sequences, it's more complicated.
  10043. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  10044. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  10045. ggml_build_forward_expand(gf,
  10046. ggml_cpy(ctx0,
  10047. ggml_view_2d(ctx0, x_conv, d_conv - 1, d_inner*n_kv, d_conv*ggml_element_size(x_conv), (1+d_inner*n_tokens)*ggml_element_size(x_conv)),
  10048. ggml_view_1d(ctx0, kv_self.k_l[il], (d_conv - 1)*(d_inner)*(n_kv), kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(x_conv))));
  10049. // extract x from x_conv
  10050. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  10051. // bias
  10052. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  10053. x = ggml_silu(ctx0, x);
  10054. }
  10055. // ssm
  10056. {
  10057. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  10058. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_x, x);
  10059. // split
  10060. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  10061. struct ggml_tensor * B = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*dt_rank);
  10062. struct ggml_tensor * C = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*(dt_rank+d_state));
  10063. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  10064. dt = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_dt, dt);
  10065. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  10066. // Custom operator to optimize the parallel associative scan
  10067. // as described in the Annex D of the Mamba paper.
  10068. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  10069. // because only a single tensor can be returned.
  10070. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  10071. // store last states (the second part of y_ssm_states)
  10072. ggml_build_forward_expand(gf,
  10073. ggml_cpy(ctx0,
  10074. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  10075. ggml_view_1d(ctx0, kv_self.v_l[il], d_state*d_inner*n_kv, kv_head*d_state*d_inner*ggml_element_size(ssm_states))));
  10076. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  10077. if (il == n_layer - 1) {
  10078. // skip computing output for unused tokens
  10079. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10080. x = ggml_get_rows(ctx0, x, inp_out_ids);
  10081. y = ggml_get_rows(ctx0, y, inp_out_ids);
  10082. z = ggml_get_rows(ctx0, z, inp_out_ids);
  10083. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10084. }
  10085. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  10086. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  10087. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  10088. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  10089. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_out, y);
  10090. }
  10091. // residual
  10092. cur = ggml_add(ctx0, cur, inpL);
  10093. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10094. cb(cur, "l_out", il);
  10095. // input for next layer
  10096. inpL = cur;
  10097. }
  10098. // final rmsnorm
  10099. cur = llm_build_norm(ctx0, inpL, hparams,
  10100. model.output_norm, NULL,
  10101. LLM_NORM_RMS, cb, -1);
  10102. cb(cur, "result_norm", -1);
  10103. // lm_head
  10104. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10105. cb(cur, "result_output", -1);
  10106. ggml_build_forward_expand(gf, cur);
  10107. return gf;
  10108. }
  10109. struct ggml_cgraph * build_command_r() {
  10110. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10111. const int64_t n_embd_head = hparams.n_embd_head_v;
  10112. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10113. const float f_logit_scale = hparams.f_logit_scale;
  10114. struct ggml_tensor * cur;
  10115. struct ggml_tensor * inpL;
  10116. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10117. // inp_pos - contains the positions
  10118. struct ggml_tensor * inp_pos = build_inp_pos();
  10119. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10120. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10121. for (int il = 0; il < n_layer; ++il) {
  10122. // norm
  10123. cur = llm_build_norm(ctx0, inpL, hparams,
  10124. model.layers[il].attn_norm, NULL,
  10125. LLM_NORM, cb, il);
  10126. cb(cur, "attn_norm", il);
  10127. struct ggml_tensor * ffn_inp = cur;
  10128. // self-attention
  10129. {
  10130. // compute Q and K and RoPE them
  10131. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10132. cb(Qcur, "Qcur", il);
  10133. if (model.layers[il].bq) {
  10134. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10135. cb(Qcur, "Qcur", il);
  10136. }
  10137. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10138. cb(Kcur, "Kcur", il);
  10139. if (model.layers[il].bk) {
  10140. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10141. cb(Kcur, "Kcur", il);
  10142. }
  10143. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10144. cb(Vcur, "Vcur", il);
  10145. if (model.layers[il].bv) {
  10146. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10147. cb(Vcur, "Vcur", il);
  10148. }
  10149. if (model.layers[il].attn_q_norm) {
  10150. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  10151. ggml_element_size(Qcur) * n_embd_head,
  10152. ggml_element_size(Qcur) * n_embd_head * n_head,
  10153. 0);
  10154. cb(Qcur, "Qcur", il);
  10155. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  10156. ggml_element_size(Kcur) * n_embd_head,
  10157. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  10158. 0);
  10159. cb(Kcur, "Kcur", il);
  10160. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10161. model.layers[il].attn_q_norm,
  10162. NULL,
  10163. LLM_NORM, cb, il);
  10164. cb(Qcur, "Qcur", il);
  10165. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10166. model.layers[il].attn_k_norm,
  10167. NULL,
  10168. LLM_NORM, cb, il);
  10169. cb(Kcur, "Kcur", il);
  10170. }
  10171. Qcur = ggml_rope_ext(
  10172. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10173. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10174. ext_factor, attn_factor, beta_fast, beta_slow
  10175. );
  10176. cb(Qcur, "Qcur", il);
  10177. Kcur = ggml_rope_ext(
  10178. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10179. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10180. ext_factor, attn_factor, beta_fast, beta_slow
  10181. );
  10182. cb(Kcur, "Kcur", il);
  10183. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10184. model.layers[il].wo, model.layers[il].bo,
  10185. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10186. }
  10187. if (il == n_layer - 1) {
  10188. // skip computing output for unused tokens
  10189. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10190. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10191. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10192. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  10193. }
  10194. struct ggml_tensor * attn_out = cur;
  10195. // feed-forward network
  10196. {
  10197. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  10198. model.layers[il].ffn_up, NULL, NULL,
  10199. model.layers[il].ffn_gate, NULL, NULL,
  10200. model.layers[il].ffn_down, NULL, NULL,
  10201. NULL,
  10202. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10203. cb(cur, "ffn_out", il);
  10204. }
  10205. // add together residual + FFN + self-attention
  10206. cur = ggml_add(ctx0, cur, inpL);
  10207. cur = ggml_add(ctx0, cur, attn_out);
  10208. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10209. cb(cur, "l_out", il);
  10210. // input for next layer
  10211. inpL = cur;
  10212. }
  10213. cur = inpL;
  10214. cur = llm_build_norm(ctx0, cur, hparams,
  10215. model.output_norm, NULL,
  10216. LLM_NORM, cb, -1);
  10217. cb(cur, "result_norm", -1);
  10218. // lm_head
  10219. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10220. if (f_logit_scale) {
  10221. cur = ggml_scale(ctx0, cur, f_logit_scale);
  10222. }
  10223. cb(cur, "result_output", -1);
  10224. ggml_build_forward_expand(gf, cur);
  10225. return gf;
  10226. }
  10227. // ref: https://allenai.org/olmo
  10228. // based on the original build_llama() function, changes:
  10229. // * non-parametric layer norm
  10230. // * clamp qkv
  10231. // * removed bias
  10232. // * removed MoE
  10233. struct ggml_cgraph * build_olmo() {
  10234. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10235. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10236. int32_t n_tokens = this->n_tokens;
  10237. const int64_t n_embd_head = hparams.n_embd_head_v;
  10238. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10239. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10240. struct ggml_tensor * cur;
  10241. struct ggml_tensor * inpL;
  10242. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10243. // inp_pos - contains the positions
  10244. struct ggml_tensor * inp_pos = build_inp_pos();
  10245. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10246. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10247. for (int il = 0; il < n_layer; ++il) {
  10248. struct ggml_tensor * inpSA = inpL;
  10249. // norm
  10250. cur = llm_build_norm(ctx0, inpL, hparams,
  10251. NULL, NULL,
  10252. LLM_NORM, cb, il);
  10253. cb(cur, "attn_norm", il);
  10254. // self-attention
  10255. {
  10256. // compute Q and K and RoPE them
  10257. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10258. cb(Qcur, "Qcur", il);
  10259. if (hparams.f_clamp_kqv > 0.0f) {
  10260. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10261. cb(Qcur, "Qcur", il);
  10262. }
  10263. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10264. cb(Kcur, "Kcur", il);
  10265. if (hparams.f_clamp_kqv > 0.0f) {
  10266. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10267. cb(Kcur, "Kcur", il);
  10268. }
  10269. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10270. cb(Vcur, "Vcur", il);
  10271. if (hparams.f_clamp_kqv > 0.0f) {
  10272. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10273. cb(Vcur, "Vcur", il);
  10274. }
  10275. Qcur = ggml_rope_ext(
  10276. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10277. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10278. ext_factor, attn_factor, beta_fast, beta_slow
  10279. );
  10280. cb(Qcur, "Qcur", il);
  10281. Kcur = ggml_rope_ext(
  10282. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10283. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10284. ext_factor, attn_factor, beta_fast, beta_slow
  10285. );
  10286. cb(Kcur, "Kcur", il);
  10287. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10288. model.layers[il].wo, nullptr,
  10289. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10290. }
  10291. if (il == n_layer - 1) {
  10292. // skip computing output for unused tokens
  10293. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10294. n_tokens = n_outputs;
  10295. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10296. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10297. }
  10298. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10299. cb(ffn_inp, "ffn_inp", il);
  10300. // feed-forward network
  10301. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10302. NULL, NULL,
  10303. LLM_NORM, cb, il);
  10304. cb(cur, "ffn_norm", il);
  10305. cur = llm_build_ffn(ctx0, lctx, cur,
  10306. model.layers[il].ffn_up, NULL, NULL,
  10307. model.layers[il].ffn_gate, NULL, NULL,
  10308. model.layers[il].ffn_down, NULL, NULL,
  10309. NULL,
  10310. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10311. cb(cur, "ffn_out", il);
  10312. cur = ggml_add(ctx0, cur, ffn_inp);
  10313. cb(cur, "ffn_out", il);
  10314. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10315. cb(cur, "l_out", il);
  10316. // input for next layer
  10317. inpL = cur;
  10318. }
  10319. cur = inpL;
  10320. cur = llm_build_norm(ctx0, cur, hparams,
  10321. NULL, NULL,
  10322. LLM_NORM, cb, -1);
  10323. cb(cur, "result_norm", -1);
  10324. // lm_head
  10325. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10326. cb(cur, "result_output", -1);
  10327. ggml_build_forward_expand(gf, cur);
  10328. return gf;
  10329. }
  10330. struct ggml_cgraph * build_openelm() {
  10331. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10332. const int64_t n_embd_head = hparams.n_embd_head_v;
  10333. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10334. struct ggml_tensor * cur;
  10335. struct ggml_tensor * inpL;
  10336. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10337. // inp_pos - contains the positions
  10338. struct ggml_tensor * inp_pos = build_inp_pos();
  10339. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10340. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10341. for (int il = 0; il < n_layer; ++il) {
  10342. const int64_t n_head = hparams.n_head(il);
  10343. const int64_t n_head_kv = hparams.n_head_kv(il);
  10344. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  10345. cur = inpL;
  10346. struct ggml_tensor * residual = cur;
  10347. // norm
  10348. cur = llm_build_norm(ctx0, inpL, hparams,
  10349. model.layers[il].attn_norm, NULL,
  10350. LLM_NORM_RMS, cb, il);
  10351. cb(cur, "attn_norm", il);
  10352. // self-attention
  10353. {
  10354. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10355. cb(cur, "wqkv", il);
  10356. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  10357. 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));
  10358. cb(Qcur, "Qcur", il);
  10359. 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));
  10360. cb(Kcur, "Kcur", il);
  10361. 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)));
  10362. cb(Vcur, "Vcur", il);
  10363. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10364. model.layers[il].attn_q_norm, NULL,
  10365. LLM_NORM_RMS, cb, il);
  10366. cb(Qcur, "Qcur", il);
  10367. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10368. model.layers[il].attn_k_norm, NULL,
  10369. LLM_NORM_RMS, cb, il);
  10370. cb(Kcur, "Kcur", il);
  10371. Qcur = ggml_rope_ext(
  10372. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10373. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10374. );
  10375. cb(Qcur, "Qcur", il);
  10376. Kcur = ggml_rope_ext(
  10377. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10378. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10379. );
  10380. cb(Kcur, "Kcur", il);
  10381. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  10382. cb(Qcur, "Vcur", il);
  10383. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10384. model.layers[il].wo, NULL,
  10385. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10386. }
  10387. if (il == n_layer - 1) {
  10388. // skip computing output for unused tokens
  10389. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10390. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  10391. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10392. }
  10393. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  10394. cb(ffn_inp, "ffn_inp", il);
  10395. // feed-forward network
  10396. {
  10397. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10398. model.layers[il].ffn_norm, NULL,
  10399. LLM_NORM_RMS, cb, il);
  10400. cb(cur, "ffn_norm", il);
  10401. cur = llm_build_ffn(ctx0, lctx, cur,
  10402. model.layers[il].ffn_up, NULL, NULL,
  10403. model.layers[il].ffn_gate, NULL, NULL,
  10404. model.layers[il].ffn_down, NULL, NULL,
  10405. NULL,
  10406. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10407. cb(cur, "ffn_out", il);
  10408. }
  10409. cur = ggml_add(ctx0, cur, ffn_inp);
  10410. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10411. cb(cur, "l_out", il);
  10412. inpL = cur;
  10413. }
  10414. cur = inpL;
  10415. // norm
  10416. cur = llm_build_norm(ctx0, cur, hparams,
  10417. model.output_norm, NULL,
  10418. LLM_NORM_RMS, cb, -1);
  10419. cb(cur, "result_norm", -1);
  10420. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10421. cb(cur, "result_output", -1);
  10422. ggml_build_forward_expand(gf, cur);
  10423. return gf;
  10424. }
  10425. struct ggml_cgraph * build_gptneox() {
  10426. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10427. const int64_t n_embd_head = hparams.n_embd_head_v;
  10428. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10429. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10430. struct ggml_tensor * cur;
  10431. struct ggml_tensor * inpL;
  10432. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10433. // inp_pos - contains the positions
  10434. struct ggml_tensor * inp_pos = build_inp_pos();
  10435. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10436. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10437. for (int il = 0; il < n_layer; ++il) {
  10438. cur = llm_build_norm(ctx0, inpL, hparams,
  10439. model.layers[il].attn_norm,
  10440. model.layers[il].attn_norm_b,
  10441. LLM_NORM, cb, il);
  10442. cb(cur, "attn_norm", il);
  10443. // self-attention
  10444. {
  10445. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10446. cb(cur, "wqkv", il);
  10447. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10448. cb(cur, "bqkv", il);
  10449. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10450. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  10451. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  10452. cb(Qcur, "Qcur", il);
  10453. cb(Kcur, "Kcur", il);
  10454. cb(Vcur, "Vcur", il);
  10455. Qcur = ggml_rope_ext(
  10456. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10457. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10458. ext_factor, attn_factor, beta_fast, beta_slow
  10459. );
  10460. cb(Qcur, "Qcur", il);
  10461. Kcur = ggml_rope_ext(
  10462. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10463. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10464. ext_factor, attn_factor, beta_fast, beta_slow
  10465. );
  10466. cb(Kcur, "Kcur", il);
  10467. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10468. model.layers[il].wo, model.layers[il].bo,
  10469. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10470. }
  10471. if (il == n_layer - 1) {
  10472. // skip computing output for unused tokens
  10473. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10474. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10475. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10476. }
  10477. // ffn
  10478. if (hparams.use_par_res) {
  10479. // attention and ffn are computed in parallel
  10480. // x = x + attn(ln1(x)) + ffn(ln2(x))
  10481. struct ggml_tensor * attn_out = cur;
  10482. cur = llm_build_norm(ctx0, inpL, hparams,
  10483. model.layers[il].ffn_norm,
  10484. model.layers[il].ffn_norm_b,
  10485. LLM_NORM, cb, il);
  10486. cb(cur, "ffn_norm", il);
  10487. cur = llm_build_ffn(ctx0, lctx, cur,
  10488. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10489. NULL, NULL, NULL,
  10490. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10491. NULL,
  10492. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10493. cb(cur, "ffn_out", il);
  10494. cur = ggml_add(ctx0, cur, inpL);
  10495. cb(cur, "ffn_out", il);
  10496. cur = ggml_add(ctx0, cur, attn_out);
  10497. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10498. cb(cur, "l_out", il);
  10499. // input for next layer
  10500. inpL = cur;
  10501. } else {
  10502. // attention and ffn are computed sequentially
  10503. // x = x + attn(ln1(x))
  10504. // x = x + ffn(ln2(x))
  10505. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10506. cb(ffn_inp, "ffn_inp", il);
  10507. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10508. model.layers[il].ffn_norm,
  10509. model.layers[il].ffn_norm_b,
  10510. LLM_NORM, cb, il);
  10511. cb(cur, "ffn_norm", il);
  10512. cur = llm_build_ffn(ctx0, lctx, cur,
  10513. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10514. NULL, NULL, NULL,
  10515. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10516. NULL,
  10517. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10518. cb(cur, "ffn_out", il);
  10519. cur = ggml_add(ctx0, cur, ffn_inp);
  10520. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10521. cb(cur, "l_out", il);
  10522. // input for next layer
  10523. inpL = cur;
  10524. }
  10525. }
  10526. cur = llm_build_norm(ctx0, inpL, hparams,
  10527. model.output_norm,
  10528. model.output_norm_b,
  10529. LLM_NORM, cb, -1);
  10530. cb(cur, "result_norm", -1);
  10531. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10532. cb(cur, "result_output", -1);
  10533. ggml_build_forward_expand(gf, cur);
  10534. return gf;
  10535. }
  10536. struct ggml_cgraph * build_arctic() {
  10537. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10538. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10539. int32_t n_tokens = this->n_tokens;
  10540. const int64_t n_embd_head = hparams.n_embd_head_v;
  10541. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10542. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10543. struct ggml_tensor * cur;
  10544. struct ggml_tensor * inpL;
  10545. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10546. // inp_pos - contains the positions
  10547. struct ggml_tensor * inp_pos = build_inp_pos();
  10548. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10549. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10550. for (int il = 0; il < n_layer; ++il) {
  10551. struct ggml_tensor * inpSA = inpL;
  10552. // norm
  10553. cur = llm_build_norm(ctx0, inpL, hparams,
  10554. model.layers[il].attn_norm, NULL,
  10555. LLM_NORM_RMS, cb, il);
  10556. cb(cur, "attn_norm", il);
  10557. // self-attention
  10558. {
  10559. // compute Q and K and RoPE them
  10560. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10561. cb(Qcur, "Qcur", il);
  10562. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10563. cb(Kcur, "Kcur", il);
  10564. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10565. cb(Vcur, "Vcur", il);
  10566. Qcur = ggml_rope_ext(
  10567. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10568. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10569. ext_factor, attn_factor, beta_fast, beta_slow
  10570. );
  10571. cb(Qcur, "Qcur", il);
  10572. Kcur = ggml_rope_ext(
  10573. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10574. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10575. ext_factor, attn_factor, beta_fast, beta_slow
  10576. );
  10577. cb(Kcur, "Kcur", il);
  10578. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10579. model.layers[il].wo, NULL,
  10580. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10581. }
  10582. if (il == n_layer - 1) {
  10583. // skip computing output for unused tokens
  10584. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10585. n_tokens = n_outputs;
  10586. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10587. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10588. }
  10589. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10590. cb(ffn_inp, "ffn_inp", il);
  10591. // feed-forward network
  10592. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10593. model.layers[il].ffn_norm, NULL,
  10594. LLM_NORM_RMS, cb, il);
  10595. cb(cur, "ffn_norm", il);
  10596. cur = llm_build_ffn(ctx0, lctx, cur,
  10597. model.layers[il].ffn_up, NULL, NULL,
  10598. model.layers[il].ffn_gate, NULL, NULL,
  10599. model.layers[il].ffn_down, NULL, NULL,
  10600. NULL,
  10601. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10602. cb(cur, "ffn_out", il);
  10603. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  10604. cb(ffn_out, "ffn_out", il);
  10605. // MoE
  10606. cur = llm_build_norm(ctx0, inpSA, hparams,
  10607. model.layers[il].ffn_norm_exps, NULL,
  10608. LLM_NORM_RMS, cb, il);
  10609. cb(cur, "ffn_norm_exps", il);
  10610. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10611. model.layers[il].ffn_gate_inp,
  10612. model.layers[il].ffn_up_exps,
  10613. model.layers[il].ffn_gate_exps,
  10614. model.layers[il].ffn_down_exps,
  10615. n_expert, n_expert_used,
  10616. LLM_FFN_SILU, true,
  10617. false, 0.0,
  10618. cb, il);
  10619. cb(cur, "ffn_moe_out", il);
  10620. cur = ggml_add(ctx0, cur, ffn_out);
  10621. cb(cur, "ffn_out", il);
  10622. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10623. cb(cur, "l_out", il);
  10624. // input for next layer
  10625. inpL = cur;
  10626. }
  10627. cur = inpL;
  10628. cur = llm_build_norm(ctx0, cur, hparams,
  10629. model.output_norm, NULL,
  10630. LLM_NORM_RMS, cb, -1);
  10631. cb(cur, "result_norm", -1);
  10632. // lm_head
  10633. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10634. cb(cur, "result_output", -1);
  10635. ggml_build_forward_expand(gf, cur);
  10636. return gf;
  10637. }
  10638. struct ggml_cgraph * build_deepseek2() {
  10639. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10640. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10641. int32_t n_tokens = this->n_tokens;
  10642. bool is_lite = (hparams.n_layer == 27);
  10643. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  10644. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  10645. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  10646. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  10647. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  10648. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  10649. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  10650. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  10651. struct ggml_tensor * cur;
  10652. struct ggml_tensor * inpL;
  10653. // {n_embd, n_tokens}
  10654. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10655. // inp_pos - contains the positions
  10656. struct ggml_tensor * inp_pos = build_inp_pos();
  10657. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10658. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10659. for (int il = 0; il < n_layer; ++il) {
  10660. struct ggml_tensor * inpSA = inpL;
  10661. // norm
  10662. cur = llm_build_norm(ctx0, inpL, hparams,
  10663. model.layers[il].attn_norm, NULL,
  10664. LLM_NORM_RMS, cb, il);
  10665. cb(cur, "attn_norm", il);
  10666. // self_attention
  10667. {
  10668. struct ggml_tensor * q = NULL;
  10669. if (!is_lite) {
  10670. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  10671. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  10672. cb(q, "q", il);
  10673. q = llm_build_norm(ctx0, q, hparams,
  10674. model.layers[il].attn_q_a_norm, NULL,
  10675. LLM_NORM_RMS, cb, il);
  10676. cb(q, "q", il);
  10677. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  10678. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  10679. cb(q, "q", il);
  10680. } else {
  10681. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  10682. cb(q, "q", il);
  10683. }
  10684. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10685. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  10686. ggml_row_size(q->type, hparams.n_embd_head_k),
  10687. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10688. 0);
  10689. cb(q_nope, "q_nope", il);
  10690. // and {n_head * n_embd_head_qk_rope, n_tokens}
  10691. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  10692. ggml_row_size(q->type, hparams.n_embd_head_k),
  10693. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10694. ggml_row_size(q->type, n_embd_head_qk_nope));
  10695. cb(q_pe, "q_pe", il);
  10696. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  10697. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  10698. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  10699. // split into {kv_lora_rank, n_tokens}
  10700. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  10701. kv_pe_compresseed->nb[1],
  10702. 0);
  10703. cb(kv_compressed, "kv_compressed", il);
  10704. // and {n_embd_head_qk_rope, n_tokens}
  10705. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  10706. kv_pe_compresseed->nb[1],
  10707. kv_pe_compresseed->nb[1],
  10708. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  10709. cb(k_pe, "k_pe", il);
  10710. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  10711. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  10712. model.layers[il].attn_kv_a_norm, NULL,
  10713. LLM_NORM_RMS, cb, il);
  10714. cb(kv_compressed, "kv_compressed", il);
  10715. // {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}
  10716. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  10717. cb(kv, "kv", il);
  10718. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10719. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  10720. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  10721. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10722. 0);
  10723. cb(k_nope, "k_nope", il);
  10724. // and {n_head * n_embd_head_v, n_tokens}
  10725. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  10726. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10727. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  10728. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  10729. cb(v_states, "v_states", il);
  10730. v_states = ggml_cont(ctx0, v_states);
  10731. cb(v_states, "v_states", il);
  10732. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  10733. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  10734. 0);
  10735. cb(v_states, "v_states", il);
  10736. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10737. q_pe = ggml_rope_ext(
  10738. ctx0, q_pe, inp_pos, nullptr,
  10739. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10740. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10741. );
  10742. cb(q_pe, "q_pe", il);
  10743. // shared RoPE key
  10744. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10745. k_pe = ggml_rope_ext(
  10746. ctx0, k_pe, inp_pos, nullptr,
  10747. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10748. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10749. );
  10750. cb(k_pe, "k_pe", il);
  10751. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  10752. cb(q_states, "q_states", il);
  10753. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  10754. cb(k_states, "k_states", il);
  10755. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10756. model.layers[il].wo, NULL,
  10757. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  10758. }
  10759. if (il == n_layer - 1) {
  10760. // skip computing output for unused tokens
  10761. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10762. n_tokens = n_outputs;
  10763. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10764. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10765. }
  10766. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10767. cb(ffn_inp, "ffn_inp", il);
  10768. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10769. model.layers[il].ffn_norm, NULL,
  10770. LLM_NORM_RMS, cb, il);
  10771. cb(cur, "ffn_norm", il);
  10772. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  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. } else {
  10781. // MoE branch
  10782. ggml_tensor * moe_out =
  10783. llm_build_moe_ffn(ctx0, lctx, cur,
  10784. model.layers[il].ffn_gate_inp,
  10785. model.layers[il].ffn_up_exps,
  10786. model.layers[il].ffn_gate_exps,
  10787. model.layers[il].ffn_down_exps,
  10788. n_expert, n_expert_used,
  10789. LLM_FFN_SILU, false,
  10790. true, hparams.expert_weights_scale,
  10791. cb, il);
  10792. cb(moe_out, "ffn_moe_out", il);
  10793. // FFN shared expert
  10794. {
  10795. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  10796. model.layers[il].ffn_up_shexp, NULL, NULL,
  10797. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10798. model.layers[il].ffn_down_shexp, NULL, NULL,
  10799. NULL,
  10800. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10801. cb(ffn_shexp, "ffn_shexp", il);
  10802. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  10803. cb(cur, "ffn_out", il);
  10804. }
  10805. }
  10806. cur = ggml_add(ctx0, cur, ffn_inp);
  10807. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10808. cb(cur, "l_out", il);
  10809. // input for next layer
  10810. inpL = cur;
  10811. }
  10812. cur = inpL;
  10813. cur = llm_build_norm(ctx0, cur, hparams,
  10814. model.output_norm, NULL,
  10815. LLM_NORM_RMS, cb, -1);
  10816. cb(cur, "result_norm", -1);
  10817. // lm_head
  10818. cur = ggml_mul_mat(ctx0, model.output, cur);
  10819. cb(cur, "result_output", -1);
  10820. ggml_build_forward_expand(gf, cur);
  10821. return gf;
  10822. }
  10823. struct ggml_cgraph * build_bitnet() {
  10824. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10825. const int64_t n_embd_head = hparams.n_embd_head_v;
  10826. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10827. struct ggml_tensor * cur;
  10828. struct ggml_tensor * inpL;
  10829. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10830. // inp_pos - contains the positions
  10831. struct ggml_tensor * inp_pos = build_inp_pos();
  10832. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10833. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10834. for (int il = 0; il < n_layer; ++il) {
  10835. struct ggml_tensor * inpSA = inpL;
  10836. cur = llm_build_norm(ctx0, inpL, hparams,
  10837. model.layers[il].attn_norm, NULL,
  10838. LLM_NORM_RMS, cb, il);
  10839. cb(cur, "attn_norm", il);
  10840. // self-attention
  10841. {
  10842. // compute Q and K and RoPE them
  10843. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10844. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  10845. cb(Qcur, "Qcur", il);
  10846. if (model.layers[il].bq) {
  10847. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10848. cb(Qcur, "Qcur", il);
  10849. }
  10850. // B1.K
  10851. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10852. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  10853. cb(Kcur, "Kcur", il);
  10854. if (model.layers[il].bk) {
  10855. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10856. cb(Kcur, "Kcur", il);
  10857. }
  10858. // B1.V
  10859. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10860. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  10861. cb(Vcur, "Vcur", il);
  10862. if (model.layers[il].bv) {
  10863. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10864. cb(Vcur, "Vcur", il);
  10865. }
  10866. Qcur = ggml_rope_ext(
  10867. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10868. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10869. ext_factor, attn_factor, beta_fast, beta_slow
  10870. );
  10871. cb(Qcur, "Qcur", il);
  10872. Kcur = ggml_rope_ext(
  10873. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10874. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10875. ext_factor, attn_factor, beta_fast, beta_slow
  10876. );
  10877. cb(Kcur, "Kcur", il);
  10878. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10879. NULL, NULL,
  10880. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10881. cur = llm_build_norm(ctx0, cur, hparams,
  10882. model.layers[il].attn_sub_norm, NULL,
  10883. LLM_NORM_RMS, cb, il);
  10884. cb(cur, "attn_sub_norm", il);
  10885. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10886. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  10887. if (model.layers[il].bo) {
  10888. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10889. }
  10890. cb(cur, "attn_o_out", il);
  10891. }
  10892. if (il == n_layer - 1) {
  10893. // skip computing output for unused tokens
  10894. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10895. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10896. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10897. }
  10898. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10899. cb(ffn_inp, "ffn_inp", il);
  10900. // feed-forward forward
  10901. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10902. model.layers[il].ffn_norm, NULL,
  10903. LLM_NORM_RMS, cb, il);
  10904. cb(cur, "ffn_norm", il);
  10905. cur = llm_build_ffn(ctx0, lctx, cur,
  10906. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  10907. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  10908. NULL, NULL, NULL,
  10909. NULL,
  10910. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10911. cb(cur, "ffn_sub_out", il);
  10912. cur = llm_build_norm(ctx0, cur, hparams,
  10913. model.layers[il].ffn_sub_norm, NULL,
  10914. LLM_NORM_RMS, cb, il);
  10915. cb(cur, "ffn_sub_norm", il);
  10916. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  10917. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  10918. cb(cur, "ffn_down", il);
  10919. cur = ggml_add(ctx0, cur, ffn_inp);
  10920. cb(cur, "l_out", il);
  10921. // input for next layer
  10922. inpL = cur;
  10923. }
  10924. cur = inpL;
  10925. cur = llm_build_norm(ctx0, cur, hparams,
  10926. model.output_norm, NULL,
  10927. LLM_NORM_RMS, cb, -1);
  10928. cb(cur, "result_norm", -1);
  10929. // lm_head
  10930. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  10931. cb(cur, "result_output", -1);
  10932. ggml_build_forward_expand(gf, cur);
  10933. return gf;
  10934. }
  10935. struct ggml_cgraph * build_t5() {
  10936. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10937. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10938. int32_t n_tokens = this->n_tokens;
  10939. const int64_t n_embd_head = hparams.n_embd_head_v;
  10940. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10941. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10942. struct ggml_tensor * cur;
  10943. struct ggml_tensor * inpL;
  10944. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10945. if (lctx.is_encoding) {
  10946. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  10947. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10948. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  10949. for (int il = 0; il < n_layer; ++il) {
  10950. struct ggml_tensor * inpSA = inpL;
  10951. // norm
  10952. cur = llm_build_norm(ctx0, inpL, hparams,
  10953. model.layers[il].attn_norm_enc, NULL,
  10954. LLM_NORM_RMS, cb, il);
  10955. cb(cur, "attn_norm", il);
  10956. // self-attention
  10957. {
  10958. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_enc, cur);
  10959. cb(Qcur, "Qcur", il);
  10960. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_enc, cur);
  10961. cb(Kcur, "Kcur", il);
  10962. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_enc, cur);
  10963. cb(Vcur, "Vcur", il);
  10964. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10965. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10966. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10967. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10968. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10969. cb(kq, "kq", il);
  10970. 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;
  10971. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  10972. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  10973. cb(kq_b, "kq_b", il);
  10974. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  10975. cb(kq, "kq_soft_max_ext", il);
  10976. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10977. cb(v, "v", il);
  10978. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10979. cb(kqv, "kqv", il);
  10980. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10981. cb(kqv_merged, "kqv_merged", il);
  10982. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10983. cb(cur, "kqv_merged_cont", il);
  10984. ggml_build_forward_expand(gf, cur);
  10985. cur = ggml_mul_mat(ctx0, model.layers[il].wo_enc, cur);
  10986. cb(cur, "kqv_out", il);
  10987. }
  10988. if (il == n_layer - 1) {
  10989. // skip computing output for unused tokens
  10990. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10991. n_tokens = n_outputs;
  10992. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10993. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10994. }
  10995. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10996. cb(ffn_inp, "ffn_inp", il);
  10997. // feed-forward network
  10998. {
  10999. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11000. model.layers[il].ffn_norm_enc, NULL,
  11001. LLM_NORM_RMS, cb, il);
  11002. cb(cur, "ffn_norm", il);
  11003. // T5 uses relu, flan-T5 uses gelu-gated
  11004. cur = llm_build_ffn(ctx0, lctx, cur,
  11005. model.layers[il].ffn_up_enc, NULL, NULL,
  11006. model.layers[il].ffn_gate_enc, NULL, NULL,
  11007. model.layers[il].ffn_down_enc, NULL, NULL,
  11008. NULL,
  11009. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11010. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11011. cb, il);
  11012. cb(cur, "ffn_out", il);
  11013. }
  11014. cur = ggml_add(ctx0, cur, ffn_inp);
  11015. cb(cur, "ffn_out", il);
  11016. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11017. if (layer_dir != nullptr) {
  11018. cur = ggml_add(ctx0, cur, layer_dir);
  11019. }
  11020. cb(cur, "l_out", il);
  11021. // input for next layer
  11022. inpL = cur;
  11023. }
  11024. cur = inpL;
  11025. cb(cur, "result_embd", -1);
  11026. cur = llm_build_norm(ctx0, cur, hparams,
  11027. model.output_norm_enc, NULL,
  11028. LLM_NORM_RMS, cb, -1);
  11029. cb(cur, "result_norm", -1);
  11030. } else {
  11031. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  11032. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  11033. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  11034. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  11035. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  11036. for (int il = 0; il < n_layer; ++il) {
  11037. struct ggml_tensor * inpSA = inpL;
  11038. // norm
  11039. cur = llm_build_norm(ctx0, inpL, hparams,
  11040. model.layers[il].attn_norm, NULL,
  11041. LLM_NORM_RMS, cb, il);
  11042. cb(cur, "attn_norm", il);
  11043. // self-attention
  11044. {
  11045. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  11046. cb(Qcur, "Qcur", il);
  11047. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  11048. cb(Kcur, "Kcur", il);
  11049. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  11050. cb(Vcur, "Vcur", il);
  11051. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  11052. struct ggml_tensor * k =
  11053. ggml_view_3d(ctx0, kv_self.k_l[il],
  11054. n_embd_head_k, n_kv, n_head_kv,
  11055. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  11056. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  11057. 0);
  11058. cb(k, "k", il);
  11059. struct ggml_tensor * v =
  11060. ggml_view_3d(ctx0, kv_self.v_l[il],
  11061. n_kv, n_embd_head_v, n_head_kv,
  11062. ggml_element_size(kv_self.v_l[il])*n_ctx,
  11063. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  11064. 0);
  11065. cb(v, "v", il);
  11066. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11067. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11068. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11069. cb(kq, "kq", il);
  11070. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  11071. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  11072. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11073. cb(kq_b, "kq_b", il);
  11074. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  11075. cb(kq, "kq_soft_max_ext", il);
  11076. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  11077. cb(kqv, "kqv", il);
  11078. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11079. cb(kqv_merged, "kqv_merged", il);
  11080. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11081. cb(cur, "kqv_merged_cont", il);
  11082. ggml_build_forward_expand(gf, cur);
  11083. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  11084. cb(cur, "kqv_out", il);
  11085. }
  11086. cur = ggml_add(ctx0, cur, inpSA);
  11087. cb(cur, "cross_inp", il);
  11088. struct ggml_tensor * inpCA = cur;
  11089. // norm
  11090. cur = llm_build_norm(ctx0, cur, hparams,
  11091. model.layers[il].attn_norm_cross, NULL,
  11092. LLM_NORM_RMS, cb, il);
  11093. cb(cur, "attn_norm_cross", il);
  11094. // cross-attention
  11095. {
  11096. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_cross, cur);
  11097. cb(Qcur, "Qcur", il);
  11098. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_cross, embd_enc);
  11099. cb(Kcur, "Kcur", il);
  11100. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_cross, embd_enc);
  11101. cb(Vcur, "Vcur", il);
  11102. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11103. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  11104. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11105. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  11106. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11107. cb(kq, "kq", il);
  11108. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  11109. cb(kq, "kq_soft_max_ext", il);
  11110. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  11111. cb(v, "v", il);
  11112. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  11113. cb(kqv, "kqv", il);
  11114. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11115. cb(kqv_merged, "kqv_merged", il);
  11116. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11117. cb(cur, "kqv_merged_cont", il);
  11118. ggml_build_forward_expand(gf, cur);
  11119. cur = ggml_mul_mat(ctx0, model.layers[il].wo_cross, cur);
  11120. cb(cur, "kqv_out", il);
  11121. }
  11122. if (il == n_layer - 1) {
  11123. // skip computing output for unused tokens
  11124. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11125. n_tokens = n_outputs;
  11126. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11127. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11128. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  11129. }
  11130. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  11131. cb(ffn_inp, "ffn_inp", il);
  11132. // feed-forward network
  11133. {
  11134. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11135. model.layers[il].ffn_norm, NULL,
  11136. LLM_NORM_RMS, cb, il);
  11137. cb(cur, "ffn_norm", il);
  11138. // T5 uses relu, flan-T5 uses gelu-gated
  11139. cur = llm_build_ffn(ctx0, lctx, cur,
  11140. model.layers[il].ffn_up, NULL, NULL,
  11141. model.layers[il].ffn_gate, NULL, NULL,
  11142. model.layers[il].ffn_down, NULL, NULL,
  11143. NULL,
  11144. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11145. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11146. cb, il);
  11147. cb(cur, "ffn_out", il);
  11148. }
  11149. cur = ggml_add(ctx0, cur, ffn_inp);
  11150. cb(cur, "ffn_out", il);
  11151. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11152. if (layer_dir != nullptr) {
  11153. cur = ggml_add(ctx0, cur, layer_dir);
  11154. }
  11155. cb(cur, "l_out", il);
  11156. // input for next layer
  11157. inpL = cur;
  11158. }
  11159. cur = inpL;
  11160. cb(cur, "result_embd", -1);
  11161. cur = llm_build_norm(ctx0, cur, hparams,
  11162. model.output_norm, NULL,
  11163. LLM_NORM_RMS, cb, -1);
  11164. cb(cur, "result_norm", -1);
  11165. // lm_head
  11166. cur = ggml_mul_mat(ctx0, model.output, cur);
  11167. cb(cur, "result_output", -1);
  11168. }
  11169. ggml_build_forward_expand(gf, cur);
  11170. return gf;
  11171. }
  11172. struct ggml_cgraph * build_jais() {
  11173. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11174. const int64_t n_embd_head = hparams.n_embd_head_v;
  11175. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11176. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11177. struct ggml_tensor * cur;
  11178. struct ggml_tensor * inpL;
  11179. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11180. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11181. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11182. for (int il = 0; il < n_layer; ++il) {
  11183. cur = llm_build_norm(ctx0, inpL, hparams,
  11184. model.layers[il].attn_norm,
  11185. model.layers[il].attn_norm_b,
  11186. LLM_NORM, cb, il);
  11187. cb(cur, "attn_norm", il);
  11188. // self-attention
  11189. {
  11190. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11191. cb(cur, "wqkv", il);
  11192. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11193. cb(cur, "bqkv", il);
  11194. 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)));
  11195. 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)));
  11196. 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)));
  11197. cb(Qcur, "Qcur", il);
  11198. cb(Kcur, "Kcur", il);
  11199. cb(Vcur, "Vcur", il);
  11200. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11201. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11202. model.layers[il].wo, model.layers[il].bo,
  11203. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  11204. }
  11205. if (il == n_layer - 1) {
  11206. // skip computing output for unused tokens
  11207. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11208. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11209. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11210. }
  11211. // add the input
  11212. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11213. cb(ffn_inp, "ffn_inp", il);
  11214. // FF
  11215. {
  11216. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11217. model.layers[il].ffn_norm,
  11218. model.layers[il].ffn_norm_b,
  11219. LLM_NORM, cb, il);
  11220. cb(cur, "ffn_norm", il);
  11221. cur = llm_build_ffn(ctx0, lctx, cur,
  11222. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11223. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  11224. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11225. NULL,
  11226. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11227. cb(cur, "ffn_out", il);
  11228. }
  11229. inpL = ggml_add(ctx0, cur, ffn_inp);
  11230. cb(inpL, "l_out", il);
  11231. }
  11232. cur = llm_build_norm(ctx0, inpL, hparams,
  11233. model.output_norm,
  11234. model.output_norm_b,
  11235. LLM_NORM, cb, -1);
  11236. cb(cur, "result_norm", -1);
  11237. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11238. cb(cur, "result_output", -1);
  11239. ggml_build_forward_expand(gf, cur);
  11240. return gf;
  11241. }
  11242. struct ggml_cgraph * build_chatglm() {
  11243. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11244. const int64_t n_embd_head = hparams.n_embd_head_v;
  11245. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11246. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11247. struct ggml_tensor * cur;
  11248. struct ggml_tensor * inpL;
  11249. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11250. // inp_pos - contains the positions
  11251. struct ggml_tensor * inp_pos = build_inp_pos();
  11252. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11253. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11254. for (int il = 0; il < n_layer; ++il) {
  11255. struct ggml_tensor * inpSA = inpL;
  11256. cur = llm_build_norm(ctx0, inpL, hparams,
  11257. model.layers[il].attn_norm,
  11258. NULL,
  11259. LLM_NORM_RMS, cb, il);
  11260. cb(cur, "attn_norm", il);
  11261. // self-attention
  11262. {
  11263. struct ggml_tensor * Qcur = nullptr;
  11264. struct ggml_tensor * Kcur = nullptr;
  11265. struct ggml_tensor * Vcur = nullptr;
  11266. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11267. cb(cur, "wqkv", il);
  11268. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11269. cb(cur, "bqkv", il);
  11270. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11271. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11272. 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)));
  11273. cb(Qcur, "Qcur", il);
  11274. cb(Kcur, "Kcur", il);
  11275. cb(Vcur, "Vcur", il);
  11276. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  11277. Qcur = ggml_rope_ext(
  11278. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11279. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11280. ext_factor, attn_factor, beta_fast, beta_slow
  11281. );
  11282. cb(Qcur, "Qcur_rope", il);
  11283. Kcur = ggml_rope_ext(
  11284. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11285. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11286. ext_factor, attn_factor, beta_fast, beta_slow
  11287. );
  11288. cb(Kcur, "Kcur_rope", il);
  11289. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11290. model.layers[il].wo, NULL,
  11291. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11292. }
  11293. if (il == n_layer - 1) {
  11294. // skip computing output for unused tokens
  11295. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11296. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11297. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11298. }
  11299. // Add the input
  11300. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11301. cb(ffn_inp, "ffn_inp", il);
  11302. // FF
  11303. {
  11304. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11305. model.layers[il].ffn_norm,
  11306. NULL,
  11307. LLM_NORM_RMS, cb, il);
  11308. cb(cur, "ffn_norm", il);
  11309. cur = llm_build_ffn(ctx0, lctx, cur,
  11310. model.layers[il].ffn_up, NULL, NULL,
  11311. NULL, NULL, NULL,
  11312. model.layers[il].ffn_down, NULL, NULL,
  11313. NULL,
  11314. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11315. cb(cur, "ffn_out", il);
  11316. }
  11317. inpL = ggml_add(ctx0, cur, ffn_inp);
  11318. cb(inpL, "l_out", il);
  11319. }
  11320. cur = llm_build_norm(ctx0, inpL, hparams,
  11321. model.output_norm,
  11322. NULL,
  11323. LLM_NORM_RMS, cb, -1);
  11324. cb(cur, "result_norm", -1);
  11325. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11326. cb(cur, "result_output", -1);
  11327. ggml_build_forward_expand(gf, cur);
  11328. return gf;
  11329. }
  11330. };
  11331. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  11332. llama_batch dummy;
  11333. dummy.n_tokens = 0;
  11334. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11335. struct llm_build_context llm(lctx, dummy, cb, false);
  11336. llm.init();
  11337. struct ggml_cgraph * result = llm.build_defrag(ids);
  11338. llm.free();
  11339. return result;
  11340. }
  11341. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  11342. llama_batch dummy;
  11343. dummy.n_tokens = 0;
  11344. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11345. struct llm_build_context llm(lctx, dummy, cb, false);
  11346. llm.init();
  11347. struct ggml_cgraph * result = llm.build_k_shift();
  11348. llm.free();
  11349. return result;
  11350. }
  11351. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  11352. llama_batch dummy;
  11353. dummy.n_tokens = 0;
  11354. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11355. struct llm_build_context llm(lctx, dummy, cb, false);
  11356. llm.init();
  11357. struct ggml_cgraph * result = llm.build_s_copy();
  11358. llm.free();
  11359. return result;
  11360. }
  11361. static struct ggml_cgraph * llama_build_graph(
  11362. llama_context & lctx,
  11363. const llama_batch & batch,
  11364. bool worst_case) {
  11365. const auto & model = lctx.model;
  11366. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  11367. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  11368. if (il >= 0) {
  11369. ggml_format_name(cur, "%s-%d", name, il);
  11370. } else {
  11371. ggml_set_name(cur, name);
  11372. }
  11373. if (!lctx.cparams.offload_kqv) {
  11374. if (strcmp(name, "kqv_merged_cont") == 0) {
  11375. // all nodes between the KV store and the attention output are run on the CPU
  11376. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  11377. }
  11378. }
  11379. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  11380. // FIXME: fix in ggml_backend_sched
  11381. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  11382. if (batch.n_tokens < 32 || full_offload) {
  11383. if (il != -1 && strcmp(name, "norm") == 0) {
  11384. for (auto * backend : lctx.backends) {
  11385. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  11386. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  11387. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  11388. break;
  11389. }
  11390. }
  11391. }
  11392. }
  11393. };
  11394. struct ggml_cgraph * result = NULL;
  11395. struct llm_build_context llm(lctx, batch, cb, worst_case);
  11396. llm.init();
  11397. switch (model.arch) {
  11398. case LLM_ARCH_LLAMA:
  11399. {
  11400. result = llm.build_llama();
  11401. } break;
  11402. case LLM_ARCH_BAICHUAN:
  11403. {
  11404. result = llm.build_baichuan();
  11405. } break;
  11406. case LLM_ARCH_FALCON:
  11407. {
  11408. result = llm.build_falcon();
  11409. } break;
  11410. case LLM_ARCH_GROK:
  11411. {
  11412. result = llm.build_grok();
  11413. } break;
  11414. case LLM_ARCH_STARCODER:
  11415. {
  11416. result = llm.build_starcoder();
  11417. } break;
  11418. case LLM_ARCH_REFACT:
  11419. {
  11420. result = llm.build_refact();
  11421. } break;
  11422. case LLM_ARCH_BERT:
  11423. case LLM_ARCH_JINA_BERT_V2:
  11424. case LLM_ARCH_NOMIC_BERT:
  11425. {
  11426. result = llm.build_bert();
  11427. } break;
  11428. case LLM_ARCH_BLOOM:
  11429. {
  11430. result = llm.build_bloom();
  11431. } break;
  11432. case LLM_ARCH_MPT:
  11433. {
  11434. result = llm.build_mpt();
  11435. } break;
  11436. case LLM_ARCH_STABLELM:
  11437. {
  11438. result = llm.build_stablelm();
  11439. } break;
  11440. case LLM_ARCH_QWEN:
  11441. {
  11442. result = llm.build_qwen();
  11443. } break;
  11444. case LLM_ARCH_QWEN2:
  11445. {
  11446. result = llm.build_qwen2();
  11447. } break;
  11448. case LLM_ARCH_QWEN2MOE:
  11449. {
  11450. result = llm.build_qwen2moe();
  11451. } break;
  11452. case LLM_ARCH_PHI2:
  11453. {
  11454. result = llm.build_phi2();
  11455. } break;
  11456. case LLM_ARCH_PHI3:
  11457. {
  11458. result = llm.build_phi3();
  11459. } break;
  11460. case LLM_ARCH_PLAMO:
  11461. {
  11462. result = llm.build_plamo();
  11463. } break;
  11464. case LLM_ARCH_GPT2:
  11465. {
  11466. result = llm.build_gpt2();
  11467. } break;
  11468. case LLM_ARCH_CODESHELL:
  11469. {
  11470. result = llm.build_codeshell();
  11471. } break;
  11472. case LLM_ARCH_ORION:
  11473. {
  11474. result = llm.build_orion();
  11475. } break;
  11476. case LLM_ARCH_INTERNLM2:
  11477. {
  11478. result = llm.build_internlm2();
  11479. } break;
  11480. case LLM_ARCH_MINICPM:
  11481. {
  11482. result = llm.build_minicpm();
  11483. } break;
  11484. case LLM_ARCH_GEMMA:
  11485. {
  11486. result = llm.build_gemma();
  11487. } break;
  11488. case LLM_ARCH_GEMMA2:
  11489. {
  11490. result = llm.build_gemma2();
  11491. } break;
  11492. case LLM_ARCH_STARCODER2:
  11493. {
  11494. result = llm.build_starcoder2();
  11495. } break;
  11496. case LLM_ARCH_MAMBA:
  11497. {
  11498. result = llm.build_mamba();
  11499. } break;
  11500. case LLM_ARCH_XVERSE:
  11501. {
  11502. result = llm.build_xverse();
  11503. } break;
  11504. case LLM_ARCH_COMMAND_R:
  11505. {
  11506. result = llm.build_command_r();
  11507. } break;
  11508. case LLM_ARCH_DBRX:
  11509. {
  11510. result = llm.build_dbrx();
  11511. } break;
  11512. case LLM_ARCH_OLMO:
  11513. {
  11514. result = llm.build_olmo();
  11515. } break;
  11516. case LLM_ARCH_OPENELM:
  11517. {
  11518. result = llm.build_openelm();
  11519. } break;
  11520. case LLM_ARCH_GPTNEOX:
  11521. {
  11522. result = llm.build_gptneox();
  11523. } break;
  11524. case LLM_ARCH_ARCTIC:
  11525. {
  11526. result = llm.build_arctic();
  11527. } break;
  11528. case LLM_ARCH_DEEPSEEK2:
  11529. {
  11530. result = llm.build_deepseek2();
  11531. } break;
  11532. case LLM_ARCH_CHATGLM:
  11533. {
  11534. result = llm.build_chatglm();
  11535. } break;
  11536. case LLM_ARCH_BITNET:
  11537. {
  11538. result = llm.build_bitnet();
  11539. } break;
  11540. case LLM_ARCH_T5:
  11541. {
  11542. result = llm.build_t5();
  11543. } break;
  11544. case LLM_ARCH_JAIS:
  11545. {
  11546. result = llm.build_jais();
  11547. } break;
  11548. default:
  11549. GGML_ABORT("fatal error");
  11550. }
  11551. // add on pooling layer
  11552. if (lctx.cparams.embeddings) {
  11553. result = llm.append_pooling(result);
  11554. }
  11555. llm.free();
  11556. return result;
  11557. }
  11558. static void llama_set_k_shift(llama_context & lctx) {
  11559. const int64_t kv_size = lctx.kv_self.size;
  11560. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  11561. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  11562. for (int i = 0; i < kv_size; ++i) {
  11563. data[i] = lctx.kv_self.cells[i].delta;
  11564. }
  11565. }
  11566. static void llama_set_s_copy(llama_context & lctx) {
  11567. const int64_t kv_size = lctx.kv_self.size;
  11568. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  11569. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  11570. for (int i = 0; i < kv_size; ++i) {
  11571. data[i] = lctx.kv_self.cells[i].src;
  11572. }
  11573. }
  11574. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  11575. // TODO move to hparams if a T5 variant appears that uses a different value
  11576. const int64_t max_distance = 128;
  11577. if (bidirectional) {
  11578. n_buckets >>= 1;
  11579. }
  11580. const int64_t max_exact = n_buckets >> 1;
  11581. int32_t relative_position = x - y;
  11582. int32_t relative_bucket = 0;
  11583. if (bidirectional) {
  11584. relative_bucket += (relative_position > 0) * n_buckets;
  11585. relative_position = abs(relative_position);
  11586. } else {
  11587. relative_position = -std::min<int32_t>(relative_position, 0);
  11588. }
  11589. 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));
  11590. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  11591. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  11592. return relative_bucket;
  11593. }
  11594. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  11595. //
  11596. // set input data
  11597. //
  11598. const auto & hparams = lctx.model.hparams;
  11599. const auto & cparams = lctx.cparams;
  11600. const auto & kv_self = lctx.kv_self;
  11601. if (batch.token) {
  11602. const int64_t n_tokens = batch.n_tokens;
  11603. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  11604. }
  11605. if (batch.embd) {
  11606. const int64_t n_embd = hparams.n_embd;
  11607. const int64_t n_tokens = batch.n_tokens;
  11608. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  11609. }
  11610. if (batch.pos && lctx.inp_pos) {
  11611. const int64_t n_tokens = batch.n_tokens;
  11612. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  11613. }
  11614. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  11615. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  11616. const int64_t n_tokens = batch.n_tokens;
  11617. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  11618. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  11619. if (lctx.n_outputs == n_tokens) {
  11620. for (int i = 0; i < n_tokens; ++i) {
  11621. data[i] = i;
  11622. }
  11623. } else if (batch.logits) {
  11624. int32_t n_outputs = 0;
  11625. for (int i = 0; i < n_tokens; ++i) {
  11626. if (batch.logits[i]) {
  11627. data[n_outputs++] = i;
  11628. }
  11629. }
  11630. // the graph needs to have been passed the correct number of outputs
  11631. GGML_ASSERT(lctx.n_outputs == n_outputs);
  11632. } else if (lctx.n_outputs == 1) {
  11633. // only keep last output
  11634. data[0] = n_tokens - 1;
  11635. } else {
  11636. GGML_ASSERT(lctx.n_outputs == 0);
  11637. }
  11638. }
  11639. GGML_ASSERT(
  11640. // (!a || b) is a logical implication (a -> b)
  11641. // !hparams.causal_attn -> !cparams.causal_attn
  11642. (hparams.causal_attn || !cparams.causal_attn) &&
  11643. "causal attention is not supported by this model"
  11644. );
  11645. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  11646. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  11647. if (cparams.causal_attn && !lctx.is_encoding) {
  11648. const int64_t n_kv = kv_self.n;
  11649. const int64_t n_tokens = batch.n_tokens;
  11650. float * data = nullptr;
  11651. float * data_swa = nullptr;
  11652. if (lctx.inp_KQ_mask) {
  11653. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11654. data = (float *) lctx.inp_KQ_mask->data;
  11655. }
  11656. if (lctx.inp_KQ_mask_swa) {
  11657. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  11658. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  11659. }
  11660. // For causal attention, use only the previous KV cells
  11661. // of the correct sequence for each token of the batch.
  11662. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  11663. for (int h = 0; h < 1; ++h) {
  11664. for (int j = 0; j < n_tokens; ++j) {
  11665. const llama_pos pos = batch.pos[j];
  11666. const llama_seq_id seq_id = batch.seq_id[j][0];
  11667. for (int i = 0; i < n_kv; ++i) {
  11668. float f;
  11669. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  11670. f = -INFINITY;
  11671. } else {
  11672. if (hparams.use_alibi) {
  11673. f = -std::abs(lctx.kv_self.cells[i].pos - pos);
  11674. } else {
  11675. f = 0.0f;
  11676. }
  11677. }
  11678. if (data) {
  11679. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11680. }
  11681. // may need to cut off old tokens for sliding window
  11682. if (data_swa) {
  11683. if (pos - lctx.kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  11684. f = -INFINITY;
  11685. }
  11686. data_swa[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11687. }
  11688. }
  11689. }
  11690. if (data) {
  11691. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11692. for (int j = 0; j < n_kv; ++j) {
  11693. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11694. }
  11695. }
  11696. }
  11697. if (data_swa) {
  11698. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11699. for (int j = 0; j < n_kv; ++j) {
  11700. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11701. }
  11702. }
  11703. }
  11704. }
  11705. } else {
  11706. // when using kv cache, the mask needs to match the kv cache size
  11707. const int64_t n_tokens = batch.n_tokens;
  11708. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  11709. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11710. float * data = (float *) lctx.inp_KQ_mask->data;
  11711. for (int h = 0; h < 1; ++h) {
  11712. for (int j = 0; j < n_tokens; ++j) {
  11713. const llama_seq_id seq_id = batch.seq_id[j][0];
  11714. for (int i = 0; i < n_tokens; ++i) {
  11715. float f = -INFINITY;
  11716. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  11717. if (batch.seq_id[i][s] == seq_id) {
  11718. if (hparams.use_alibi) {
  11719. f = -std::abs(batch.pos[i] - batch.pos[j]);
  11720. } else {
  11721. f = 0.0f;
  11722. }
  11723. break;
  11724. }
  11725. }
  11726. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  11727. }
  11728. for (int i = n_tokens; i < n_stride; ++i) {
  11729. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  11730. }
  11731. }
  11732. }
  11733. }
  11734. }
  11735. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  11736. const int64_t n_tokens = batch.n_tokens;
  11737. GGML_ASSERT(lctx.inp_mean);
  11738. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  11739. float * data = (float *) lctx.inp_mean->data;
  11740. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  11741. std::vector<uint64_t> sum(n_tokens, 0);
  11742. for (int i = 0; i < n_tokens; ++i) {
  11743. const llama_seq_id seq_id = batch.seq_id[i][0];
  11744. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  11745. sum[seq_id] += 1;
  11746. }
  11747. std::vector<float> div(n_tokens, 0.0f);
  11748. for (int i = 0; i < n_tokens; ++i) {
  11749. const uint64_t s = sum[i];
  11750. if (s > 0) {
  11751. div[i] = 1.0f/float(s);
  11752. }
  11753. }
  11754. for (int i = 0; i < n_tokens; ++i) {
  11755. const llama_seq_id seq_id = batch.seq_id[i][0];
  11756. data[seq_id*n_tokens + i] = div[seq_id];
  11757. }
  11758. }
  11759. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  11760. const int64_t n_tokens = batch.n_tokens;
  11761. GGML_ASSERT(lctx.inp_cls);
  11762. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11763. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11764. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11765. for (int i = 0; i < n_tokens; ++i) {
  11766. const llama_seq_id seq_id = batch.seq_id[i][0];
  11767. const llama_pos pos = batch.pos[i];
  11768. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  11769. if (pos == 0) {
  11770. data[seq_id] = i;
  11771. }
  11772. }
  11773. }
  11774. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  11775. const int64_t n_tokens = batch.n_tokens;
  11776. GGML_ASSERT(lctx.inp_cls);
  11777. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11778. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11779. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11780. std::vector<int> last_pos(n_tokens, -1);
  11781. std::vector<int> last_row(n_tokens, -1);
  11782. for (int i = 0; i < n_tokens; ++i) {
  11783. const llama_seq_id seq_id = batch.seq_id[i][0];
  11784. const llama_pos pos = batch.pos[i];
  11785. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  11786. if (pos >= last_pos[seq_id]) {
  11787. last_pos[seq_id] = pos;
  11788. last_row[seq_id] = i;
  11789. }
  11790. }
  11791. for (int i = 0; i < n_tokens; ++i) {
  11792. if (last_row[i] >= 0) {
  11793. data[i] = last_row[i];
  11794. }
  11795. }
  11796. }
  11797. if (kv_self.recurrent) {
  11798. const int64_t n_kv = kv_self.n;
  11799. if (lctx.inp_s_mask) {
  11800. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  11801. float * data = (float *) lctx.inp_s_mask->data;
  11802. // states which are not affected by the current batch are left untouched
  11803. for (int i = 0; i < n_kv; ++i) {
  11804. llama_seq_id seq_id = i + lctx.kv_self.head;
  11805. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  11806. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  11807. data[i] = (float) has_self_seq;
  11808. // ensure current sequences will be kept
  11809. if (!has_self_seq && kv_cell.pos >= 0) {
  11810. kv_cell.seq_id.insert(seq_id);
  11811. }
  11812. }
  11813. }
  11814. // For Mamba (and other recurrent architectures),
  11815. // update the correct state(s)/sequence(s) for each token of the batch.
  11816. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  11817. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  11818. if (lctx.inp_s_seq) {
  11819. const int64_t n_tokens = batch.n_tokens;
  11820. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  11821. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  11822. for (int j = 0; j < n_tokens; ++j) {
  11823. const int32_t n_seq = batch.n_seq_id[j];
  11824. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  11825. for (int i = 0; i < n_kv; ++i) {
  11826. if (i < n_seq) {
  11827. // for this type of model, the head is the minimum seq_id of the batch
  11828. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  11829. } else {
  11830. data[j*n_kv + i] = -1;
  11831. }
  11832. }
  11833. }
  11834. }
  11835. }
  11836. if (lctx.inp_pos_bucket) {
  11837. const int64_t n_tokens = batch.n_tokens;
  11838. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  11839. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  11840. if (!lctx.is_encoding) {
  11841. const int64_t n_kv = kv_self.n;
  11842. for (int h = 0; h < 1; ++h) {
  11843. for (int j = 0; j < n_tokens; ++j) {
  11844. for (int i = 0; i < n_kv; ++i) {
  11845. 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);
  11846. }
  11847. }
  11848. }
  11849. } else {
  11850. for (int h = 0; h < 1; ++h) {
  11851. for (int j = 0; j < n_tokens; ++j) {
  11852. for (int i = 0; i < n_tokens; ++i) {
  11853. 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);
  11854. }
  11855. }
  11856. }
  11857. }
  11858. }
  11859. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  11860. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  11861. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  11862. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  11863. }
  11864. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  11865. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  11866. const int64_t n_tokens = batch.n_tokens;
  11867. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  11868. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  11869. for (int h = 0; h < 1; ++h) {
  11870. for (int j = 0; j < n_tokens; ++j) {
  11871. for (int i = 0; i < n_output_enc; ++i) {
  11872. float f = -INFINITY;
  11873. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  11874. const llama_seq_id seq_id = batch.seq_id[j][s];
  11875. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  11876. f = 0.0f;
  11877. }
  11878. }
  11879. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  11880. }
  11881. }
  11882. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11883. for (int j = 0; j < n_output_enc; ++j) {
  11884. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  11885. }
  11886. }
  11887. }
  11888. }
  11889. }
  11890. // Make sure enough space is available for outputs.
  11891. // Returns max number of outputs for which space was reserved.
  11892. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  11893. const auto & cparams = lctx.cparams;
  11894. const auto & hparams = lctx.model.hparams;
  11895. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  11896. const auto n_batch = cparams.n_batch;
  11897. const auto n_vocab = hparams.n_vocab;
  11898. const auto n_embd = hparams.n_embd;
  11899. // TODO: use a per-batch flag for logits presence instead
  11900. const bool has_logits = !cparams.embeddings;
  11901. const bool has_embd = lctx.is_encoding || (cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE));
  11902. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  11903. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  11904. if (lctx.output_ids.empty()) {
  11905. // init, never resized afterwards
  11906. lctx.output_ids.resize(n_batch);
  11907. }
  11908. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  11909. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  11910. // alloc only when more than the current capacity is required
  11911. // TODO: also consider shrinking the buffer
  11912. if (!lctx.buf_output || prev_size < new_size) {
  11913. if (lctx.buf_output) {
  11914. #ifndef NDEBUG
  11915. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  11916. 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);
  11917. #endif
  11918. ggml_backend_buffer_free(lctx.buf_output);
  11919. lctx.buf_output = nullptr;
  11920. lctx.logits = nullptr;
  11921. lctx.embd = nullptr;
  11922. }
  11923. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  11924. if (lctx.buf_output == nullptr) {
  11925. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  11926. return 0;
  11927. }
  11928. }
  11929. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  11930. lctx.logits = has_logits ? output_base : nullptr;
  11931. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  11932. lctx.output_size = n_outputs_max;
  11933. lctx.logits_size = logits_size;
  11934. lctx.embd_size = embd_size;
  11935. // set all ids as invalid (negative)
  11936. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  11937. ggml_backend_buffer_clear(lctx.buf_output, 0);
  11938. lctx.n_outputs = 0;
  11939. return n_outputs_max;
  11940. }
  11941. static void llama_graph_compute(
  11942. llama_context & lctx,
  11943. ggml_cgraph * gf,
  11944. int n_threads) {
  11945. #ifdef GGML_USE_METAL
  11946. if (ggml_backend_is_metal(lctx.backend_metal)) {
  11947. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  11948. }
  11949. #endif
  11950. if (lctx.backend_cpu != nullptr) {
  11951. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  11952. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  11953. }
  11954. #ifdef GGML_USE_BLAS
  11955. if (lctx.backend_blas != nullptr) {
  11956. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  11957. }
  11958. #endif
  11959. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  11960. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  11961. }
  11962. // decode a batch of tokens by evaluating the transformer
  11963. //
  11964. // - lctx: llama context
  11965. // - batch: batch to evaluate
  11966. //
  11967. // return 0 on success
  11968. // return positive int on warning
  11969. // return negative int on error
  11970. //
  11971. static int llama_decode_internal(
  11972. llama_context & lctx,
  11973. llama_batch batch_all) { // TODO: rename back to batch
  11974. lctx.is_encoding = false;
  11975. const uint32_t n_tokens_all = batch_all.n_tokens;
  11976. if (n_tokens_all == 0) {
  11977. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  11978. return -1;
  11979. }
  11980. const auto & model = lctx.model;
  11981. const auto & hparams = model.hparams;
  11982. const auto & cparams = lctx.cparams;
  11983. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  11984. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  11985. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  11986. if (lctx.t_compute_start_us == 0) {
  11987. lctx.t_compute_start_us = ggml_time_us();
  11988. }
  11989. lctx.n_queued_tokens += n_tokens_all;
  11990. auto & kv_self = lctx.kv_self;
  11991. const int64_t n_embd = hparams.n_embd;
  11992. const int64_t n_vocab = hparams.n_vocab;
  11993. uint32_t n_outputs = 0;
  11994. uint32_t n_outputs_prev = 0;
  11995. const auto n_ubatch = cparams.n_ubatch;
  11996. // TODO: simplify or deprecate
  11997. std::vector<llama_pos> pos;
  11998. std::vector<int32_t> n_seq_id;
  11999. std::vector<llama_seq_id *> seq_id_arr;
  12000. std::vector<std::vector<llama_seq_id>> seq_id;
  12001. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  12002. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  12003. // count outputs
  12004. if (batch_all.logits && !embd_pooled) {
  12005. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12006. n_outputs += batch_all.logits[i] != 0;
  12007. }
  12008. } else if (lctx.logits_all || embd_pooled) {
  12009. n_outputs = n_tokens_all;
  12010. } else {
  12011. // keep last output only
  12012. n_outputs = 1;
  12013. }
  12014. // reserve output buffer
  12015. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  12016. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  12017. return -2;
  12018. };
  12019. // set output mappings
  12020. if (batch_all.logits) {
  12021. int32_t i_logits = 0;
  12022. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12023. if (batch_all.logits[i]) {
  12024. lctx.output_ids[i] = i_logits++;
  12025. }
  12026. }
  12027. } else {
  12028. for (uint32_t i = 0; i < n_outputs; ++i) {
  12029. lctx.output_ids[i] = i;
  12030. }
  12031. }
  12032. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  12033. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  12034. llama_batch u_batch = {
  12035. /* .n_tokens = */ (int32_t) n_tokens,
  12036. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  12037. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  12038. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  12039. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  12040. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  12041. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  12042. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  12043. /* .all_pos_1 = */ batch_all.all_pos_1,
  12044. /* .all_seq_id = */ batch_all.all_seq_id,
  12045. };
  12046. // count the outputs in this u_batch
  12047. {
  12048. int32_t n_outputs_new = 0;
  12049. if (u_batch.logits && !embd_pooled) {
  12050. for (uint32_t i = 0; i < n_tokens; i++) {
  12051. n_outputs_new += u_batch.logits[i] != 0;
  12052. }
  12053. } else if (n_outputs == n_tokens_all) {
  12054. n_outputs_new = n_tokens;
  12055. } else {
  12056. // keep last output only
  12057. if (cur_token + n_tokens >= n_tokens_all) {
  12058. n_outputs_new = 1;
  12059. }
  12060. }
  12061. // needs to happen before the graph is built
  12062. lctx.n_outputs = n_outputs_new;
  12063. }
  12064. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12065. GGML_ASSERT(n_threads > 0);
  12066. // helpers for smoother batch API transition
  12067. // after deprecating the llama_eval calls, these will be removed
  12068. if (u_batch.pos == nullptr) {
  12069. pos.resize(n_tokens);
  12070. for (uint32_t i = 0; i < n_tokens; i++) {
  12071. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  12072. }
  12073. u_batch.pos = pos.data();
  12074. }
  12075. if (u_batch.seq_id == nullptr) {
  12076. n_seq_id.resize(n_tokens);
  12077. seq_id.resize(n_tokens);
  12078. seq_id_arr.resize(n_tokens);
  12079. for (uint32_t i = 0; i < n_tokens; i++) {
  12080. n_seq_id[i] = 1;
  12081. seq_id[i].resize(1);
  12082. seq_id[i][0] = u_batch.all_seq_id;
  12083. seq_id_arr[i] = seq_id[i].data();
  12084. }
  12085. u_batch.n_seq_id = n_seq_id.data();
  12086. u_batch.seq_id = seq_id_arr.data();
  12087. }
  12088. // non-causal masks do not use the KV cache
  12089. if (hparams.causal_attn) {
  12090. llama_kv_cache_update(&lctx);
  12091. // if we have enough unused cells before the current head ->
  12092. // better to start searching from the beginning of the cache, hoping to fill it
  12093. if (kv_self.head > kv_self.used + 2*n_tokens) {
  12094. kv_self.head = 0;
  12095. }
  12096. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  12097. return 1;
  12098. }
  12099. if (!kv_self.recurrent) {
  12100. // a heuristic, to avoid attending the full cache if it is not yet utilized
  12101. // after enough generations, the benefit from this heuristic disappears
  12102. // if we start defragmenting the cache, the benefit from this will be more important
  12103. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  12104. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  12105. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  12106. }
  12107. }
  12108. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  12109. ggml_backend_sched_reset(lctx.sched);
  12110. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12111. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  12112. // the output is always the last tensor in the graph
  12113. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  12114. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  12115. if (lctx.n_outputs == 0) {
  12116. // no output
  12117. res = nullptr;
  12118. embd = nullptr;
  12119. } else if (cparams.embeddings) {
  12120. res = nullptr; // do not extract logits for embedding case
  12121. embd = gf->nodes[gf->n_nodes - 1];
  12122. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  12123. embd = gf->nodes[gf->n_nodes - 2];
  12124. }
  12125. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  12126. } else {
  12127. embd = nullptr; // do not extract embeddings when not needed
  12128. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  12129. }
  12130. // 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);
  12131. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12132. llama_set_inputs(lctx, u_batch);
  12133. llama_graph_compute(lctx, gf, n_threads);
  12134. // update the kv ring buffer
  12135. {
  12136. kv_self.head += n_tokens;
  12137. // Ensure kv cache head points to a valid index.
  12138. if (kv_self.head >= kv_self.size) {
  12139. kv_self.head = 0;
  12140. }
  12141. }
  12142. // plot the computation graph in dot format (for debugging purposes)
  12143. //if (n_past%100 == 0) {
  12144. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  12145. //}
  12146. // extract logits
  12147. if (res) {
  12148. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  12149. GGML_ASSERT(backend_res != nullptr);
  12150. GGML_ASSERT(lctx.logits != nullptr);
  12151. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  12152. const int32_t n_outputs_new = lctx.n_outputs;
  12153. if (n_outputs_new) {
  12154. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12155. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  12156. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  12157. }
  12158. }
  12159. // extract embeddings
  12160. if (embd) {
  12161. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12162. GGML_ASSERT(backend_embd != nullptr);
  12163. switch (cparams.pooling_type) {
  12164. case LLAMA_POOLING_TYPE_NONE:
  12165. {
  12166. // extract token embeddings
  12167. GGML_ASSERT(lctx.embd != nullptr);
  12168. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  12169. const int32_t n_outputs_new = lctx.n_outputs;
  12170. if (n_outputs_new) {
  12171. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12172. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  12173. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  12174. }
  12175. } break;
  12176. case LLAMA_POOLING_TYPE_MEAN:
  12177. case LLAMA_POOLING_TYPE_CLS:
  12178. case LLAMA_POOLING_TYPE_LAST:
  12179. {
  12180. // extract sequence embeddings
  12181. auto & embd_seq_out = lctx.embd_seq;
  12182. embd_seq_out.clear();
  12183. for (uint32_t i = 0; i < n_tokens; i++) {
  12184. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  12185. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  12186. continue;
  12187. }
  12188. embd_seq_out[seq_id].resize(n_embd);
  12189. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  12190. }
  12191. } break;
  12192. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  12193. {
  12194. GGML_ABORT("unknown pooling type");
  12195. }
  12196. }
  12197. }
  12198. n_outputs_prev += lctx.n_outputs;
  12199. }
  12200. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  12201. lctx.n_outputs = n_outputs;
  12202. // wait for the computation to finish (automatically done when obtaining the model output)
  12203. //llama_synchronize(&lctx);
  12204. // decide if we need to defrag the kv cache
  12205. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  12206. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  12207. // queue defragmentation for next llama_kv_cache_update
  12208. if (fragmentation > cparams.defrag_thold) {
  12209. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  12210. llama_kv_cache_defrag(kv_self);
  12211. }
  12212. }
  12213. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12214. // overlap with device computation.
  12215. ggml_backend_sched_reset(lctx.sched);
  12216. return 0;
  12217. }
  12218. // encode a batch of tokens by evaluating the encoder part of the transformer
  12219. //
  12220. // - lctx: llama context
  12221. // - batch: batch to evaluate
  12222. //
  12223. // return 0 on success
  12224. // return positive int on warning
  12225. // return negative int on error
  12226. //
  12227. static int llama_encode_internal(
  12228. llama_context & lctx,
  12229. llama_batch batch) {
  12230. lctx.is_encoding = true;
  12231. const uint32_t n_tokens = batch.n_tokens;
  12232. if (n_tokens == 0) {
  12233. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  12234. return -1;
  12235. }
  12236. const auto & model = lctx.model;
  12237. const auto & hparams = model.hparams;
  12238. const auto & cparams = lctx.cparams;
  12239. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  12240. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  12241. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  12242. if (lctx.t_compute_start_us == 0) {
  12243. lctx.t_compute_start_us = ggml_time_us();
  12244. }
  12245. lctx.n_queued_tokens += n_tokens;
  12246. const int64_t n_embd = hparams.n_embd;
  12247. // TODO: simplify or deprecate
  12248. std::vector<llama_pos> pos;
  12249. std::vector<int32_t> n_seq_id;
  12250. std::vector<llama_seq_id *> seq_id_arr;
  12251. std::vector<std::vector<llama_seq_id>> seq_id;
  12252. // reserve output buffer
  12253. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  12254. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  12255. return -2;
  12256. };
  12257. for (uint32_t i = 0; i < n_tokens; ++i) {
  12258. lctx.output_ids[i] = i;
  12259. }
  12260. lctx.inp_embd_enc = NULL;
  12261. lctx.n_outputs = n_tokens;
  12262. const int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12263. GGML_ASSERT(n_threads > 0);
  12264. // helpers for smoother batch API transition
  12265. // after deprecating the llama_eval calls, these will be removed
  12266. if (batch.pos == nullptr) {
  12267. pos.resize(n_tokens);
  12268. for (uint32_t i = 0; i < n_tokens; i++) {
  12269. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  12270. }
  12271. batch.pos = pos.data();
  12272. }
  12273. if (batch.seq_id == nullptr) {
  12274. n_seq_id.resize(n_tokens);
  12275. seq_id.resize(n_tokens);
  12276. seq_id_arr.resize(n_tokens);
  12277. for (uint32_t i = 0; i < n_tokens; i++) {
  12278. n_seq_id[i] = 1;
  12279. seq_id[i].resize(1);
  12280. seq_id[i][0] = batch.all_seq_id;
  12281. seq_id_arr[i] = seq_id[i].data();
  12282. }
  12283. batch.n_seq_id = n_seq_id.data();
  12284. batch.seq_id = seq_id_arr.data();
  12285. }
  12286. ggml_backend_sched_reset(lctx.sched);
  12287. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12288. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  12289. // the output embeddings after the final encoder normalization
  12290. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 1];
  12291. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  12292. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12293. llama_set_inputs(lctx, batch);
  12294. llama_graph_compute(lctx, gf, n_threads);
  12295. // extract embeddings
  12296. if (embd) {
  12297. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12298. GGML_ASSERT(backend_embd != nullptr);
  12299. // extract token embeddings
  12300. GGML_ASSERT(lctx.embd != nullptr);
  12301. lctx.embd_enc.resize(n_tokens*n_embd);
  12302. float * embd_out = lctx.embd_enc.data();
  12303. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  12304. // remember the sequence ids used during the encoding - needed for cross attention later
  12305. lctx.seq_ids_enc.resize(n_tokens);
  12306. for (uint32_t i = 0; i < n_tokens; i++) {
  12307. for (int s = 0; s < batch.n_seq_id[i]; s++) {
  12308. llama_seq_id seq_id = batch.seq_id[i][s];
  12309. lctx.seq_ids_enc[i].insert(seq_id);
  12310. }
  12311. }
  12312. }
  12313. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12314. // overlap with device computation.
  12315. ggml_backend_sched_reset(lctx.sched);
  12316. return 0;
  12317. }
  12318. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  12319. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  12320. auto & kv_self = lctx.kv_self;
  12321. const auto & hparams = lctx.model.hparams;
  12322. const uint32_t n_layer = hparams.n_layer;
  12323. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  12324. const uint32_t n_used = kv_self.used;
  12325. assert(n_used <= n_kv);
  12326. //const int64_t t_start = ggml_time_us();
  12327. // number of cells moved
  12328. uint32_t n_moves = 0;
  12329. // each move requires 6*n_layer tensors (see build_defrag)
  12330. // - source view, destination view, copy operation
  12331. // - x2 for keys and values
  12332. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  12333. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  12334. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  12335. // determine which KV cells to move where
  12336. //
  12337. // cell i moves to ids[i]
  12338. //
  12339. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  12340. //
  12341. std::vector<uint32_t> ids(n_kv, n_kv);
  12342. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  12343. const auto & cell0 = kv_self.cells[i0];
  12344. if (!cell0.is_empty()) {
  12345. ids[i0] = i0;
  12346. continue;
  12347. }
  12348. // found a hole - fill it with data from the end of the cache
  12349. uint32_t nh = 1;
  12350. // determine the size of the hole
  12351. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  12352. nh++;
  12353. }
  12354. uint32_t nf = 0;
  12355. uint32_t is = n_kv - 1;
  12356. // starting from the end, find nh non-empty cells
  12357. for (; is > i0; --is) {
  12358. const auto & cell1 = kv_self.cells[is];
  12359. if (cell1.is_empty() || ids[is] != n_kv) {
  12360. continue;
  12361. }
  12362. // non-empty cell which is not yet moved
  12363. nf++;
  12364. if (nf == nh) {
  12365. break;
  12366. }
  12367. }
  12368. // this can only happen if `n_used` is not accurate, which would be a bug
  12369. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  12370. nf = 0;
  12371. uint32_t i1 = is;
  12372. // are we moving a continuous block of memory?
  12373. bool cont = false;
  12374. // should we stop searching for the next move?
  12375. bool stop = false;
  12376. // go back and move the nf cells to the hole
  12377. for (; i1 < n_kv; ++i1) {
  12378. auto & cell1 = kv_self.cells[i1];
  12379. if (cell1.is_empty() || ids[i1] != n_kv) {
  12380. if (n_moves == max_moves) {
  12381. stop = true;
  12382. break;
  12383. }
  12384. cont = false;
  12385. continue;
  12386. }
  12387. // this cell goes to (i0 + nf)
  12388. ids[i1] = i0 + nf;
  12389. // move the cell meta data
  12390. kv_self.cells[i0 + nf] = cell1;
  12391. // clear the old cell and move the head there
  12392. cell1 = llama_kv_cell();
  12393. kv_self.head = n_used;
  12394. if (!cont) {
  12395. n_moves++;
  12396. cont = true;
  12397. }
  12398. nf++;
  12399. if (nf == nh) {
  12400. break;
  12401. }
  12402. }
  12403. if (stop || n_moves == max_moves) {
  12404. break;
  12405. }
  12406. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  12407. i0 += nh - 1;
  12408. }
  12409. if (n_moves == 0) {
  12410. return;
  12411. }
  12412. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  12413. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  12414. #if 0
  12415. // CPU defrag
  12416. //
  12417. // TODO: optimizations are possible:
  12418. // - multiple threads
  12419. // - avoid copying to the host memory when already there
  12420. //
  12421. // likely not worth the effort, as we have ggml_graph based defrag
  12422. //
  12423. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  12424. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  12425. const uint32_t kv_size = kv_self.size;
  12426. std::vector<uint8_t> buf_k;
  12427. std::vector<uint8_t> buf_v;
  12428. for (uint32_t il = 0; il < n_layer; ++il) {
  12429. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12430. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  12431. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12432. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  12433. buf_k.resize(k_size);
  12434. buf_v.resize(v_size);
  12435. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12436. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12437. // batch move [i, i+nm) to [id, id+nm)
  12438. // note: cells can move only to a lower index
  12439. for (uint32_t i = 0; i < n_kv; ++i) {
  12440. const uint32_t id = ids[i];
  12441. if (i == id || id == n_kv) {
  12442. continue;
  12443. }
  12444. uint32_t nm = 1;
  12445. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  12446. nm++;
  12447. }
  12448. // move keys
  12449. {
  12450. const int64_t os = i*k_size_row;
  12451. const int64_t od = id*k_size_row;
  12452. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  12453. }
  12454. // move values (note: they are transposed)
  12455. {
  12456. const int64_t os = i;
  12457. const int64_t od = id;
  12458. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  12459. 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);
  12460. }
  12461. }
  12462. i += nm - 1;
  12463. }
  12464. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12465. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12466. }
  12467. #else
  12468. // ggml_graph defrag
  12469. ggml_backend_sched_reset(lctx.sched);
  12470. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  12471. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12472. #endif
  12473. //const int64_t t_end = ggml_time_us();
  12474. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  12475. }
  12476. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  12477. bool need_reserve = false;
  12478. // apply K-shift if needed
  12479. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  12480. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  12481. GGML_ABORT("Deepseek2 does not support K-shift");
  12482. }
  12483. {
  12484. ggml_backend_sched_reset(lctx.sched);
  12485. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  12486. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12487. llama_set_k_shift(lctx);
  12488. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12489. need_reserve = true;
  12490. }
  12491. {
  12492. auto & kv_self = lctx.kv_self;
  12493. kv_self.has_shift = false;
  12494. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12495. kv_self.cells[i].delta = 0;
  12496. }
  12497. }
  12498. }
  12499. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  12500. {
  12501. ggml_backend_sched_reset(lctx.sched);
  12502. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  12503. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12504. llama_set_s_copy(lctx);
  12505. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12506. need_reserve = true;
  12507. }
  12508. {
  12509. auto & kv_self = lctx.kv_self;
  12510. kv_self.do_copy = false;
  12511. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12512. kv_self.cells[i].src = i;
  12513. }
  12514. }
  12515. }
  12516. // defragment the KV cache if needed
  12517. if (lctx.kv_self.do_defrag) {
  12518. llama_kv_cache_defrag_internal(lctx);
  12519. need_reserve = true;
  12520. lctx.kv_self.do_defrag = false;
  12521. }
  12522. // reserve a worst case graph again
  12523. if (need_reserve) {
  12524. // TODO: extract to a function
  12525. // build worst-case graph
  12526. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  12527. int n_past = lctx.cparams.n_ctx - n_tokens;
  12528. 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
  12529. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12530. // initialize scheduler with the worst-case graph
  12531. ggml_backend_sched_reset(lctx.sched);
  12532. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  12533. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12534. }
  12535. }
  12536. }
  12537. //
  12538. // quantization
  12539. //
  12540. struct quantize_state_internal {
  12541. const llama_model & model;
  12542. const llama_model_quantize_params * params;
  12543. int n_attention_wv = 0;
  12544. int n_ffn_down = 0;
  12545. int n_ffn_gate = 0;
  12546. int n_ffn_up = 0;
  12547. int i_attention_wv = 0;
  12548. int i_ffn_down = 0;
  12549. int i_ffn_gate = 0;
  12550. int i_ffn_up = 0;
  12551. int n_k_quantized = 0;
  12552. int n_fallback = 0;
  12553. bool has_imatrix = false;
  12554. // used to figure out if a model shares tok_embd with the output weight
  12555. bool has_output = false;
  12556. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  12557. : model(model)
  12558. , params(params)
  12559. {}
  12560. };
  12561. static void llama_tensor_dequantize_internal(
  12562. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  12563. const size_t nelements, const int nthread
  12564. ) {
  12565. if (output.size() < nelements) {
  12566. output.resize(nelements);
  12567. }
  12568. float * f32_output = (float *) output.data();
  12569. ggml_type_traits_t qtype;
  12570. if (ggml_is_quantized(tensor->type)) {
  12571. qtype = ggml_internal_get_type_traits(tensor->type);
  12572. if (qtype.to_float == NULL) {
  12573. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  12574. }
  12575. } else if (tensor->type != GGML_TYPE_F16 &&
  12576. tensor->type != GGML_TYPE_BF16) {
  12577. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  12578. }
  12579. if (nthread < 2) {
  12580. if (tensor->type == GGML_TYPE_F16) {
  12581. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  12582. } else if (tensor->type == GGML_TYPE_BF16) {
  12583. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  12584. } else if (ggml_is_quantized(tensor->type)) {
  12585. qtype.to_float(tensor->data, f32_output, nelements);
  12586. } else {
  12587. GGML_ABORT("fatal error"); // unreachable
  12588. }
  12589. return;
  12590. }
  12591. size_t block_size;
  12592. if (tensor->type == GGML_TYPE_F16 ||
  12593. tensor->type == GGML_TYPE_BF16) {
  12594. block_size = 1;
  12595. } else {
  12596. block_size = (size_t)ggml_blck_size(tensor->type);
  12597. }
  12598. size_t block_size_bytes = ggml_type_size(tensor->type);
  12599. GGML_ASSERT(nelements % block_size == 0);
  12600. size_t nblocks = nelements / block_size;
  12601. size_t blocks_per_thread = nblocks / nthread;
  12602. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  12603. size_t in_buff_offs = 0;
  12604. size_t out_buff_offs = 0;
  12605. for (int tnum = 0; tnum < nthread; tnum++) {
  12606. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  12607. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  12608. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  12609. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  12610. if (typ == GGML_TYPE_F16) {
  12611. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  12612. } else if (typ == GGML_TYPE_BF16) {
  12613. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  12614. } else {
  12615. qtype.to_float(inbuf, outbuf, nels);
  12616. }
  12617. };
  12618. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  12619. in_buff_offs += thr_block_bytes;
  12620. out_buff_offs += thr_elems;
  12621. }
  12622. for (auto & w : workers) { w.join(); }
  12623. workers.clear();
  12624. }
  12625. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  12626. const std::string name = ggml_get_name(tensor);
  12627. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12628. const llm_arch arch = qs.model.arch;
  12629. const auto tn = LLM_TN(arch);
  12630. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  12631. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  12632. };
  12633. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  12634. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  12635. if (n_expert > 1) {
  12636. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  12637. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  12638. // for getting the current layer as I initially thought, and we need to resort to parsing the
  12639. // tensor name.
  12640. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  12641. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  12642. }
  12643. if (i_layer < 0 || i_layer >= n_layer) {
  12644. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  12645. }
  12646. }
  12647. return std::make_pair(i_layer, n_layer);
  12648. };
  12649. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  12650. // with the quantization of the output tensor
  12651. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  12652. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  12653. new_type = qs.params->output_tensor_type;
  12654. } else {
  12655. int nx = tensor->ne[0];
  12656. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  12657. new_type = GGML_TYPE_Q8_0;
  12658. }
  12659. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12660. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  12661. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12662. new_type = GGML_TYPE_Q5_K;
  12663. }
  12664. else if (new_type != GGML_TYPE_Q8_0) {
  12665. new_type = GGML_TYPE_Q6_K;
  12666. }
  12667. }
  12668. } else if (name == "token_embd.weight") {
  12669. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  12670. new_type = qs.params->token_embedding_type;
  12671. } else {
  12672. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  12673. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12674. new_type = GGML_TYPE_Q2_K;
  12675. }
  12676. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  12677. new_type = GGML_TYPE_IQ3_S;
  12678. }
  12679. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12680. new_type = GGML_TYPE_IQ3_S;
  12681. }
  12682. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  12683. new_type == GGML_TYPE_Q4_0_8_8) {
  12684. new_type = GGML_TYPE_Q4_0;
  12685. }
  12686. }
  12687. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  12688. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12689. if (name.find("attn_v.weight") != std::string::npos) {
  12690. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  12691. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12692. ++qs.i_attention_wv;
  12693. }
  12694. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  12695. new_type = GGML_TYPE_Q4_K;
  12696. }
  12697. else if (name.find("ffn_down") != std::string::npos) {
  12698. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  12699. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12700. }
  12701. ++qs.i_ffn_down;
  12702. }
  12703. else if (name.find("attn_output.weight") != std::string::npos) {
  12704. if (qs.model.hparams.n_expert == 8) {
  12705. new_type = GGML_TYPE_Q5_K;
  12706. } else {
  12707. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  12708. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  12709. }
  12710. }
  12711. } else if (name.find("attn_v.weight") != std::string::npos) {
  12712. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  12713. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12714. }
  12715. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  12716. new_type = GGML_TYPE_Q4_K;
  12717. }
  12718. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12719. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  12720. }
  12721. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  12722. new_type = GGML_TYPE_Q4_K;
  12723. }
  12724. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12725. new_type = GGML_TYPE_Q4_K;
  12726. }
  12727. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12728. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12729. }
  12730. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  12731. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  12732. new_type = GGML_TYPE_Q5_K;
  12733. }
  12734. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  12735. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  12736. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  12737. if (qs.model.type == MODEL_70B) {
  12738. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  12739. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  12740. // nearly negligible increase in model size by quantizing this tensor with more bits:
  12741. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  12742. }
  12743. if (qs.model.hparams.n_expert == 8) {
  12744. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12745. // TODO: explore better strategies
  12746. new_type = GGML_TYPE_Q8_0;
  12747. }
  12748. ++qs.i_attention_wv;
  12749. } else if (name.find("attn_k.weight") != std::string::npos) {
  12750. if (qs.model.hparams.n_expert == 8) {
  12751. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12752. // TODO: explore better strategies
  12753. new_type = GGML_TYPE_Q8_0;
  12754. }
  12755. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12756. new_type = GGML_TYPE_IQ3_XXS;
  12757. }
  12758. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12759. new_type = GGML_TYPE_IQ2_S;
  12760. }
  12761. } else if (name.find("attn_q.weight") != std::string::npos) {
  12762. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12763. new_type = GGML_TYPE_IQ3_XXS;
  12764. }
  12765. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12766. new_type = GGML_TYPE_IQ2_S;
  12767. }
  12768. } else if (name.find("ffn_down") != std::string::npos) {
  12769. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  12770. int i_layer = info.first, n_layer = info.second;
  12771. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12772. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  12773. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  12774. }
  12775. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  12776. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12777. }
  12778. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12779. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  12780. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  12781. : GGML_TYPE_Q3_K;
  12782. }
  12783. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  12784. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  12785. new_type = GGML_TYPE_Q4_K;
  12786. }
  12787. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  12788. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  12789. }
  12790. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  12791. if (arch == LLM_ARCH_FALCON) {
  12792. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  12793. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12794. } else {
  12795. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12796. }
  12797. }
  12798. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  12799. new_type = GGML_TYPE_Q5_K;
  12800. }
  12801. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12802. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  12803. new_type = GGML_TYPE_Q5_K;
  12804. }
  12805. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  12806. && qs.has_imatrix && i_layer < n_layer/8) {
  12807. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  12808. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  12809. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  12810. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  12811. }
  12812. ++qs.i_ffn_down;
  12813. } else if (name.find("attn_output.weight") != std::string::npos) {
  12814. if (arch != LLM_ARCH_FALCON) {
  12815. if (qs.model.hparams.n_expert == 8) {
  12816. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12817. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  12818. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  12819. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  12820. new_type = GGML_TYPE_Q5_K;
  12821. }
  12822. } else {
  12823. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  12824. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  12825. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  12826. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  12827. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  12828. }
  12829. } else {
  12830. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  12831. }
  12832. }
  12833. else if (name.find("attn_qkv.weight") != std::string::npos) {
  12834. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12835. new_type = GGML_TYPE_Q4_K;
  12836. }
  12837. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  12838. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  12839. }
  12840. else if (name.find("ffn_gate") != std::string::npos) {
  12841. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  12842. int i_layer = info.first, n_layer = info.second;
  12843. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12844. new_type = GGML_TYPE_IQ3_XXS;
  12845. }
  12846. ++qs.i_ffn_gate;
  12847. }
  12848. else if (name.find("ffn_up") != std::string::npos) {
  12849. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  12850. int i_layer = info.first, n_layer = info.second;
  12851. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12852. new_type = GGML_TYPE_IQ3_XXS;
  12853. }
  12854. ++qs.i_ffn_up;
  12855. }
  12856. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12857. //}
  12858. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  12859. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  12860. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12861. //}
  12862. // This can be used to reduce the size of the Q5_K_S model.
  12863. // The associated PPL increase is fully in line with the size reduction
  12864. //else {
  12865. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  12866. //}
  12867. bool convert_incompatible_tensor = false;
  12868. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  12869. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  12870. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  12871. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  12872. new_type == GGML_TYPE_IQ1_M) {
  12873. int nx = tensor->ne[0];
  12874. int ny = tensor->ne[1];
  12875. if (nx % QK_K != 0) {
  12876. 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));
  12877. convert_incompatible_tensor = true;
  12878. } else {
  12879. ++qs.n_k_quantized;
  12880. }
  12881. }
  12882. if (convert_incompatible_tensor) {
  12883. switch (new_type) {
  12884. case GGML_TYPE_IQ2_XXS:
  12885. case GGML_TYPE_IQ2_XS:
  12886. case GGML_TYPE_IQ2_S:
  12887. case GGML_TYPE_IQ3_XXS:
  12888. case GGML_TYPE_IQ3_S:
  12889. case GGML_TYPE_IQ1_S:
  12890. case GGML_TYPE_IQ1_M:
  12891. case GGML_TYPE_Q2_K:
  12892. case GGML_TYPE_Q3_K:
  12893. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  12894. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  12895. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  12896. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  12897. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  12898. }
  12899. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  12900. ++qs.n_fallback;
  12901. }
  12902. return new_type;
  12903. }
  12904. 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) {
  12905. if (nthread < 2) {
  12906. // single-thread
  12907. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  12908. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  12909. throw std::runtime_error("quantized data validation failed");
  12910. }
  12911. return new_size;
  12912. }
  12913. std::mutex mutex;
  12914. int64_t counter = 0;
  12915. size_t new_size = 0;
  12916. bool valid = true;
  12917. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  12918. nrows, n_per_row, imatrix]() {
  12919. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  12920. size_t local_size = 0;
  12921. while (true) {
  12922. std::unique_lock<std::mutex> lock(mutex);
  12923. int64_t first_row = counter; counter += nrows_per_chunk;
  12924. if (first_row >= nrows) {
  12925. if (local_size > 0) {
  12926. new_size += local_size;
  12927. }
  12928. break;
  12929. }
  12930. lock.unlock();
  12931. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  12932. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  12933. local_size += this_size;
  12934. // validate the quantized data
  12935. const size_t row_size = ggml_row_size(new_type, n_per_row);
  12936. void * this_data = (char *) new_data + first_row * row_size;
  12937. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  12938. std::unique_lock<std::mutex> lock(mutex);
  12939. valid = false;
  12940. break;
  12941. }
  12942. }
  12943. };
  12944. for (int it = 0; it < nthread - 1; ++it) {
  12945. workers.emplace_back(compute);
  12946. }
  12947. compute();
  12948. for (auto & w : workers) { w.join(); }
  12949. workers.clear();
  12950. if (!valid) {
  12951. throw std::runtime_error("quantized data validation failed");
  12952. }
  12953. return new_size;
  12954. }
  12955. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  12956. ggml_type default_type;
  12957. llama_ftype ftype = params->ftype;
  12958. switch (params->ftype) {
  12959. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  12960. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  12961. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  12962. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  12963. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  12964. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  12965. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  12966. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  12967. // K-quants
  12968. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  12969. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  12970. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  12971. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  12972. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  12973. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  12974. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  12975. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  12976. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  12977. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  12978. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  12979. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  12980. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  12981. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  12982. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  12983. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  12984. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  12985. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  12986. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  12987. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  12988. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  12989. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  12990. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  12991. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  12992. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  12993. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  12994. }
  12995. int nthread = params->nthread;
  12996. if (nthread <= 0) {
  12997. nthread = std::thread::hardware_concurrency();
  12998. }
  12999. // mmap consistently increases speed Linux, and also increases speed on Windows with
  13000. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  13001. #if defined(__linux__) || defined(_WIN32)
  13002. constexpr bool use_mmap = true;
  13003. #else
  13004. constexpr bool use_mmap = false;
  13005. #endif
  13006. llama_model_kv_override * kv_overrides = nullptr;
  13007. if (params->kv_overrides) {
  13008. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  13009. kv_overrides = v->data();
  13010. }
  13011. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  13012. ml.init_mappings(false); // no prefetching
  13013. llama_model model;
  13014. llm_load_arch(ml, model);
  13015. llm_load_hparams(ml, model);
  13016. struct quantize_state_internal qs(model, params);
  13017. if (params->only_copy) {
  13018. ftype = model.ftype;
  13019. }
  13020. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  13021. if (params->imatrix) {
  13022. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  13023. if (imatrix_data) {
  13024. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  13025. qs.has_imatrix = true;
  13026. // check imatrix for nans or infs
  13027. for (const auto & kv : *imatrix_data) {
  13028. for (float f : kv.second) {
  13029. if (!std::isfinite(f)) {
  13030. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  13031. }
  13032. }
  13033. }
  13034. }
  13035. }
  13036. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  13037. struct gguf_context * ctx_out = gguf_init_empty();
  13038. // copy the KV pairs from the input file
  13039. gguf_set_kv (ctx_out, ml.meta);
  13040. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  13041. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  13042. // Remove split metadata
  13043. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  13044. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  13045. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  13046. if (params->kv_overrides) {
  13047. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  13048. for (auto & o : overrides) {
  13049. if (o.key[0] == 0) break;
  13050. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  13051. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  13052. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  13053. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  13054. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  13055. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  13056. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  13057. gguf_set_val_str(ctx_out, o.key, o.val_str);
  13058. } else {
  13059. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  13060. }
  13061. }
  13062. }
  13063. for (int i = 0; i < ml.n_tensors; ++i) {
  13064. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  13065. const std::string name = ggml_get_name(meta);
  13066. // TODO: avoid hardcoded tensor names - use the TN_* constants
  13067. if (name.find("attn_v.weight") != std::string::npos ||
  13068. name.find("attn_qkv.weight") != std::string::npos) {
  13069. ++qs.n_attention_wv;
  13070. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  13071. qs.has_output = true;
  13072. }
  13073. }
  13074. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  13075. // sanity checks
  13076. //
  13077. // - qs.n_attention_wv == 0 for Mamba models
  13078. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  13079. // - qs.n_attention_wv == 3 * model.hparams.n_layer for Encoder-Decoder models
  13080. //
  13081. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer || qs.n_attention_wv == 3 * (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  13082. size_t total_size_org = 0;
  13083. size_t total_size_new = 0;
  13084. std::vector<std::thread> workers;
  13085. workers.reserve(nthread);
  13086. int idx = 0;
  13087. std::vector<no_init<uint8_t>> read_data;
  13088. std::vector<no_init<uint8_t>> work;
  13089. std::vector<no_init<float>> f32_conv_buf;
  13090. uint16_t n_split = 1;
  13091. // Assume split index is continuous
  13092. if (params->keep_split) {
  13093. for (int i = 0; i < ml.n_tensors; ++i) {
  13094. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  13095. }
  13096. }
  13097. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  13098. ctx_outs[0] = ctx_out;
  13099. // populate the original tensors so we get an initial meta data
  13100. for (int i = 0; i < ml.n_tensors; ++i) {
  13101. auto weight = ml.get_weight(i);
  13102. uint16_t i_split = params->keep_split ? weight->idx : 0;
  13103. struct ggml_tensor * tensor = weight->tensor;
  13104. if (ctx_outs[i_split] == NULL) {
  13105. ctx_outs[i_split] = gguf_init_empty();
  13106. }
  13107. gguf_add_tensor(ctx_outs[i_split], tensor);
  13108. }
  13109. // Set split info if needed
  13110. if (n_split > 1) {
  13111. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  13112. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  13113. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  13114. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  13115. }
  13116. }
  13117. int cur_split = -1;
  13118. std::ofstream fout;
  13119. auto close_ofstream = [&]() {
  13120. // Write metadata and close file handler
  13121. if (fout.is_open()) {
  13122. fout.seekp(0);
  13123. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  13124. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  13125. fout.write((const char *) data.data(), data.size());
  13126. fout.close();
  13127. }
  13128. };
  13129. auto new_ofstream = [&](int index) {
  13130. cur_split = index;
  13131. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  13132. std::string fname = fname_out;
  13133. if (params->keep_split) {
  13134. char split_path[PATH_MAX] = {0};
  13135. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  13136. fname = std::string(split_path);
  13137. }
  13138. fout = std::ofstream(fname, std::ios::binary);
  13139. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  13140. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  13141. // placeholder for the meta data
  13142. ::zeros(fout, meta_size);
  13143. };
  13144. const auto tn = LLM_TN(model.arch);
  13145. new_ofstream(0);
  13146. for (int i = 0; i < ml.n_tensors; ++i) {
  13147. auto weight = ml.get_weight(i);
  13148. struct ggml_tensor * tensor = weight->tensor;
  13149. if (weight->idx != cur_split && params->keep_split) {
  13150. close_ofstream();
  13151. new_ofstream(weight->idx);
  13152. }
  13153. const std::string name = ggml_get_name(tensor);
  13154. if (!ml.use_mmap) {
  13155. if (read_data.size() < ggml_nbytes(tensor)) {
  13156. read_data.resize(ggml_nbytes(tensor));
  13157. }
  13158. tensor->data = read_data.data();
  13159. }
  13160. ml.load_data_for(tensor);
  13161. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  13162. ++idx, ml.n_tensors,
  13163. ggml_get_name(tensor),
  13164. llama_format_tensor_shape(tensor).c_str(),
  13165. ggml_type_name(tensor->type));
  13166. // This used to be a regex, but <regex> has an extreme cost to compile times.
  13167. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  13168. // quantize only 2D and 3D tensors (experts)
  13169. quantize &= (ggml_n_dims(tensor) >= 2);
  13170. // do not quantize norm tensors
  13171. quantize &= name.find("_norm.weight") == std::string::npos;
  13172. quantize &= params->quantize_output_tensor || name != "output.weight";
  13173. quantize &= !params->only_copy;
  13174. // do not quantize expert gating tensors
  13175. // NOTE: can't use LLM_TN here because the layer number is not known
  13176. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  13177. // do not quantize positional embeddings and token types (BERT)
  13178. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  13179. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  13180. // do not quantize Mamba's small yet 2D weights
  13181. // NOTE: can't use LLM_TN here because the layer number is not known
  13182. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  13183. quantize &= name.find("ssm_x.weight") == std::string::npos;
  13184. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  13185. // do not quantize relative position bias (T5)
  13186. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  13187. enum ggml_type new_type;
  13188. void * new_data;
  13189. size_t new_size;
  13190. if (quantize) {
  13191. new_type = default_type;
  13192. // get more optimal quantization type based on the tensor shape, layer, etc.
  13193. if (!params->pure && ggml_is_quantized(default_type)) {
  13194. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  13195. }
  13196. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  13197. new_type = params->token_embedding_type;
  13198. }
  13199. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  13200. new_type = params->output_tensor_type;
  13201. }
  13202. // If we've decided to quantize to the same type the tensor is already
  13203. // in then there's nothing to do.
  13204. quantize = tensor->type != new_type;
  13205. }
  13206. if (!quantize) {
  13207. new_type = tensor->type;
  13208. new_data = tensor->data;
  13209. new_size = ggml_nbytes(tensor);
  13210. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  13211. } else {
  13212. const int64_t nelements = ggml_nelements(tensor);
  13213. const float * imatrix = nullptr;
  13214. if (imatrix_data) {
  13215. auto it = imatrix_data->find(tensor->name);
  13216. if (it == imatrix_data->end()) {
  13217. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  13218. } else {
  13219. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  13220. imatrix = it->second.data();
  13221. } else {
  13222. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  13223. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  13224. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  13225. // this is a significant error and it may be good idea to abort the process if this happens,
  13226. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  13227. // tok_embd should be ignored in this case, since it always causes this warning
  13228. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  13229. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  13230. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  13231. }
  13232. }
  13233. }
  13234. }
  13235. if ((new_type == GGML_TYPE_IQ2_XXS ||
  13236. new_type == GGML_TYPE_IQ2_XS ||
  13237. new_type == GGML_TYPE_IQ2_S ||
  13238. new_type == GGML_TYPE_IQ1_S ||
  13239. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  13240. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  13241. LLAMA_LOG_ERROR("\n\n============================================================\n");
  13242. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  13243. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  13244. LLAMA_LOG_ERROR("============================================================\n\n");
  13245. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  13246. }
  13247. float * f32_data;
  13248. if (tensor->type == GGML_TYPE_F32) {
  13249. f32_data = (float *) tensor->data;
  13250. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  13251. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  13252. } else {
  13253. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  13254. f32_data = (float *) f32_conv_buf.data();
  13255. }
  13256. int chunk_size_multiplier = 1;
  13257. 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) {
  13258. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  13259. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  13260. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  13261. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  13262. }
  13263. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  13264. fflush(stdout);
  13265. if (work.size() < (size_t)nelements * 4) {
  13266. work.resize(nelements * 4); // upper bound on size
  13267. }
  13268. new_data = work.data();
  13269. const int64_t n_per_row = tensor->ne[0];
  13270. const int64_t nrows = tensor->ne[1];
  13271. static const int64_t min_chunk_size = 32 * 512;
  13272. 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)) *
  13273. chunk_size_multiplier;
  13274. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  13275. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  13276. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  13277. // quantize each expert separately since they have different importance matrices
  13278. new_size = 0;
  13279. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  13280. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  13281. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  13282. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  13283. 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);
  13284. }
  13285. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  13286. }
  13287. total_size_org += ggml_nbytes(tensor);
  13288. total_size_new += new_size;
  13289. // update the gguf meta data as we go
  13290. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  13291. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  13292. // write tensor data + padding
  13293. fout.write((const char *) new_data, new_size);
  13294. zeros(fout, GGML_PAD(new_size, align) - new_size);
  13295. }
  13296. close_ofstream();
  13297. for (auto & c:ctx_outs) {
  13298. gguf_free(c);
  13299. }
  13300. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  13301. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  13302. if (qs.n_fallback > 0) {
  13303. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  13304. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  13305. }
  13306. }
  13307. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  13308. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  13309. ggml_context * ctx = nullptr;
  13310. struct gguf_init_params meta_gguf_params = {
  13311. /* .no_alloc = */ true,
  13312. /* .ctx = */ &ctx,
  13313. };
  13314. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  13315. if (!ctx_gguf) {
  13316. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  13317. }
  13318. // check metadata
  13319. {
  13320. auto get_kv_str = [&](const std::string & key) -> std::string {
  13321. int id = gguf_find_key(ctx_gguf, key.c_str());
  13322. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  13323. };
  13324. auto get_kv_f32 = [&](const std::string & key) -> float {
  13325. int id = gguf_find_key(ctx_gguf, key.c_str());
  13326. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  13327. };
  13328. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  13329. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  13330. if (general_type != "adapter") {
  13331. gguf_free(ctx_gguf);
  13332. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  13333. }
  13334. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  13335. auto general_arch = llm_arch_from_string(general_arch_str);
  13336. if (general_arch != model->arch) {
  13337. gguf_free(ctx_gguf);
  13338. throw std::runtime_error("model arch and LoRA arch mismatch");
  13339. }
  13340. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  13341. if (adapter_type != "lora") {
  13342. gguf_free(ctx_gguf);
  13343. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  13344. }
  13345. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  13346. }
  13347. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  13348. // contexts for each buffer type
  13349. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  13350. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  13351. auto it = ctx_map.find(buft);
  13352. if (it == ctx_map.end()) {
  13353. // add a new context
  13354. struct ggml_init_params params = {
  13355. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  13356. /*.mem_buffer =*/ NULL,
  13357. /*.no_alloc =*/ true,
  13358. };
  13359. ggml_context * buft_ctx = ggml_init(params);
  13360. ctx_map[buft] = buft_ctx;
  13361. return buft_ctx;
  13362. };
  13363. return it->second;
  13364. };
  13365. // bundle lora_a and lora_b into pairs
  13366. std::map<std::string, llama_lora_weight> ab_map;
  13367. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  13368. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  13369. };
  13370. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  13371. std::string name(cur->name);
  13372. if (str_endswith(name, ".lora_a")) {
  13373. replace_all(name, ".lora_a", "");
  13374. if (ab_map.find(name) == ab_map.end()) {
  13375. ab_map[name] = llama_lora_weight(cur, nullptr);
  13376. } else {
  13377. ab_map[name].a = cur;
  13378. }
  13379. } else if (str_endswith(name, ".lora_b")) {
  13380. replace_all(name, ".lora_b", "");
  13381. if (ab_map.find(name) == ab_map.end()) {
  13382. ab_map[name] = llama_lora_weight(nullptr, cur);
  13383. } else {
  13384. ab_map[name].b = cur;
  13385. }
  13386. } else {
  13387. gguf_free(ctx_gguf);
  13388. ggml_free(ctx);
  13389. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  13390. }
  13391. }
  13392. // add tensors
  13393. for (auto & it : ab_map) {
  13394. const std::string & name = it.first;
  13395. llama_lora_weight & w = it.second;
  13396. if (!w.a || !w.b) {
  13397. gguf_free(ctx_gguf);
  13398. ggml_free(ctx);
  13399. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  13400. }
  13401. // device buft and device ctx
  13402. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  13403. if (!model_tensor) {
  13404. gguf_free(ctx_gguf);
  13405. ggml_free(ctx);
  13406. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  13407. }
  13408. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  13409. // validate tensor shape
  13410. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  13411. gguf_free(ctx_gguf);
  13412. ggml_free(ctx);
  13413. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  13414. }
  13415. if (w.a->ne[1] != w.b->ne[0]) {
  13416. gguf_free(ctx_gguf);
  13417. ggml_free(ctx);
  13418. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  13419. }
  13420. // save tensor to adapter
  13421. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  13422. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  13423. ggml_set_name(tensor_a, w.a->name);
  13424. ggml_set_name(tensor_b, w.b->name);
  13425. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  13426. }
  13427. // allocate tensors / buffers and zero
  13428. {
  13429. adapter.ctxs.reserve(ctx_map.size());
  13430. adapter.bufs.reserve(ctx_map.size());
  13431. for (auto it : ctx_map) {
  13432. ggml_backend_buffer_type_t buft = it.first;
  13433. ggml_context * ctx_dev = it.second;
  13434. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  13435. if (!buf) {
  13436. gguf_free(ctx_gguf);
  13437. ggml_free(ctx);
  13438. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  13439. }
  13440. 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);
  13441. adapter.ctxs.push_back(ctx_dev);
  13442. adapter.bufs.push_back(buf);
  13443. }
  13444. }
  13445. // set tensor data
  13446. {
  13447. llama_file gguf_file(path_lora, "rb");
  13448. std::vector<uint8_t> read_buf;
  13449. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  13450. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  13451. size_t size = ggml_nbytes(orig);
  13452. read_buf.resize(size);
  13453. gguf_file.seek(offs, SEEK_SET);
  13454. gguf_file.read_raw(read_buf.data(), size);
  13455. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  13456. };
  13457. for (auto & it : adapter.ab_map) {
  13458. auto orig = ab_map[it.first];
  13459. auto dev = it.second;
  13460. set_tensor(orig.a, dev.a);
  13461. set_tensor(orig.b, dev.b);
  13462. }
  13463. }
  13464. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  13465. // free ctx for reading gguf
  13466. gguf_free(ctx_gguf);
  13467. ggml_free(ctx);
  13468. }
  13469. int32_t llama_lora_adapter_set(
  13470. struct llama_context * ctx,
  13471. struct llama_lora_adapter * adapter,
  13472. float scale) {
  13473. if (ctx->cparams.flash_attn) {
  13474. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  13475. return -1;
  13476. }
  13477. ctx->lora_adapters[adapter] = scale;
  13478. return 0;
  13479. }
  13480. int32_t llama_lora_adapter_remove(
  13481. struct llama_context * ctx,
  13482. struct llama_lora_adapter * adapter) {
  13483. auto pos = ctx->lora_adapters.find(adapter);
  13484. if (pos != ctx->lora_adapters.end()) {
  13485. ctx->lora_adapters.erase(pos);
  13486. return 0;
  13487. }
  13488. return -1;
  13489. }
  13490. void llama_lora_adapter_clear(struct llama_context * ctx) {
  13491. ctx->lora_adapters.clear();
  13492. }
  13493. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  13494. delete adapter;
  13495. }
  13496. //
  13497. // interface implementation
  13498. //
  13499. struct llama_model_params llama_model_default_params() {
  13500. struct llama_model_params result = {
  13501. /*.n_gpu_layers =*/ 0,
  13502. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  13503. /*.main_gpu =*/ 0,
  13504. /*.tensor_split =*/ nullptr,
  13505. /*.rpc_servers =*/ nullptr,
  13506. /*.progress_callback =*/ nullptr,
  13507. /*.progress_callback_user_data =*/ nullptr,
  13508. /*.kv_overrides =*/ nullptr,
  13509. /*.vocab_only =*/ false,
  13510. /*.use_mmap =*/ true,
  13511. /*.use_mlock =*/ false,
  13512. /*.check_tensors =*/ false,
  13513. };
  13514. #ifdef GGML_USE_METAL
  13515. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  13516. result.n_gpu_layers = 999;
  13517. #endif
  13518. return result;
  13519. }
  13520. struct llama_context_params llama_context_default_params() {
  13521. struct llama_context_params result = {
  13522. /*.seed =*/ LLAMA_DEFAULT_SEED,
  13523. /*.n_ctx =*/ 512,
  13524. /*.n_batch =*/ 2048,
  13525. /*.n_ubatch =*/ 512,
  13526. /*.n_seq_max =*/ 1,
  13527. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  13528. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  13529. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  13530. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  13531. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  13532. /*.rope_freq_base =*/ 0.0f,
  13533. /*.rope_freq_scale =*/ 0.0f,
  13534. /*.yarn_ext_factor =*/ -1.0f,
  13535. /*.yarn_attn_factor =*/ 1.0f,
  13536. /*.yarn_beta_fast =*/ 32.0f,
  13537. /*.yarn_beta_slow =*/ 1.0f,
  13538. /*.yarn_orig_ctx =*/ 0,
  13539. /*.defrag_thold =*/ -1.0f,
  13540. /*.cb_eval =*/ nullptr,
  13541. /*.cb_eval_user_data =*/ nullptr,
  13542. /*.type_k =*/ GGML_TYPE_F16,
  13543. /*.type_v =*/ GGML_TYPE_F16,
  13544. /*.logits_all =*/ false,
  13545. /*.embeddings =*/ false,
  13546. /*.offload_kqv =*/ true,
  13547. /*.flash_attn =*/ false,
  13548. /*.abort_callback =*/ nullptr,
  13549. /*.abort_callback_data =*/ nullptr,
  13550. };
  13551. return result;
  13552. }
  13553. struct llama_model_quantize_params llama_model_quantize_default_params() {
  13554. struct llama_model_quantize_params result = {
  13555. /*.nthread =*/ 0,
  13556. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  13557. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  13558. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  13559. /*.allow_requantize =*/ false,
  13560. /*.quantize_output_tensor =*/ true,
  13561. /*.only_copy =*/ false,
  13562. /*.pure =*/ false,
  13563. /*.keep_split =*/ false,
  13564. /*.imatrix =*/ nullptr,
  13565. /*.kv_overrides =*/ nullptr,
  13566. };
  13567. return result;
  13568. }
  13569. size_t llama_max_devices(void) {
  13570. #if defined(GGML_USE_RPC)
  13571. return GGML_RPC_MAX_SERVERS;
  13572. #elif defined(GGML_USE_METAL)
  13573. return 1;
  13574. #elif defined(GGML_USE_CUDA)
  13575. return GGML_CUDA_MAX_DEVICES;
  13576. #elif defined(GGML_USE_SYCL)
  13577. return GGML_SYCL_MAX_DEVICES;
  13578. #elif defined(GGML_USE_VULKAN)
  13579. return GGML_VK_MAX_DEVICES;
  13580. #elif defined(GGML_USE_CANN)
  13581. return GGML_CANN_MAX_DEVICES;
  13582. #else
  13583. return 1;
  13584. #endif
  13585. }
  13586. bool llama_supports_mmap(void) {
  13587. return llama_mmap::SUPPORTED;
  13588. }
  13589. bool llama_supports_mlock(void) {
  13590. return llama_mlock::SUPPORTED;
  13591. }
  13592. bool llama_supports_gpu_offload(void) {
  13593. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  13594. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  13595. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  13596. return true;
  13597. #else
  13598. return false;
  13599. #endif
  13600. }
  13601. void llama_backend_init(void) {
  13602. ggml_time_init();
  13603. // needed to initialize f16 tables
  13604. {
  13605. struct ggml_init_params params = { 0, NULL, false };
  13606. struct ggml_context * ctx = ggml_init(params);
  13607. ggml_free(ctx);
  13608. }
  13609. }
  13610. void llama_numa_init(enum ggml_numa_strategy numa) {
  13611. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  13612. ggml_numa_init(numa);
  13613. }
  13614. }
  13615. void llama_backend_free(void) {
  13616. ggml_quantize_free();
  13617. }
  13618. int64_t llama_time_us(void) {
  13619. return ggml_time_us();
  13620. }
  13621. struct llama_model * llama_load_model_from_file(
  13622. const char * path_model,
  13623. struct llama_model_params params) {
  13624. ggml_time_init();
  13625. llama_model * model = new llama_model;
  13626. unsigned cur_percentage = 0;
  13627. if (params.progress_callback == NULL) {
  13628. params.progress_callback_user_data = &cur_percentage;
  13629. params.progress_callback = [](float progress, void * ctx) {
  13630. unsigned * cur_percentage_p = (unsigned *) ctx;
  13631. unsigned percentage = (unsigned) (100 * progress);
  13632. while (percentage > *cur_percentage_p) {
  13633. *cur_percentage_p = percentage;
  13634. LLAMA_LOG_INFO(".");
  13635. if (percentage >= 100) {
  13636. LLAMA_LOG_INFO("\n");
  13637. }
  13638. }
  13639. return true;
  13640. };
  13641. }
  13642. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  13643. // split the servers set them into model->rpc_servers
  13644. std::string servers(params.rpc_servers);
  13645. size_t pos = 0;
  13646. while ((pos = servers.find(",")) != std::string::npos) {
  13647. std::string server = servers.substr(0, pos);
  13648. model->rpc_servers.push_back(server);
  13649. servers.erase(0, pos + 1);
  13650. }
  13651. model->rpc_servers.push_back(servers);
  13652. }
  13653. int status = llama_model_load(path_model, *model, params);
  13654. GGML_ASSERT(status <= 0);
  13655. if (status < 0) {
  13656. if (status == -1) {
  13657. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  13658. } else if (status == -2) {
  13659. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  13660. }
  13661. delete model;
  13662. return nullptr;
  13663. }
  13664. return model;
  13665. }
  13666. void llama_free_model(struct llama_model * model) {
  13667. delete model;
  13668. }
  13669. struct llama_context * llama_new_context_with_model(
  13670. struct llama_model * model,
  13671. struct llama_context_params params) {
  13672. if (!model) {
  13673. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  13674. return nullptr;
  13675. }
  13676. if (params.n_batch == 0 && params.n_ubatch == 0) {
  13677. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  13678. return nullptr;
  13679. }
  13680. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  13681. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  13682. return nullptr;
  13683. }
  13684. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  13685. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  13686. params.flash_attn = false;
  13687. }
  13688. if (params.flash_attn && model->hparams.attn_soft_cap) {
  13689. LLAMA_LOG_WARN("%s: flash_attn is not compatible with attn_soft_cap - forcing off\n", __func__);
  13690. params.flash_attn = false;
  13691. }
  13692. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  13693. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  13694. params.flash_attn = false;
  13695. }
  13696. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  13697. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  13698. return nullptr;
  13699. }
  13700. llama_context * ctx = new llama_context(*model);
  13701. const auto & hparams = model->hparams;
  13702. auto & cparams = ctx->cparams;
  13703. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  13704. cparams.n_threads = params.n_threads;
  13705. cparams.n_threads_batch = params.n_threads_batch;
  13706. cparams.yarn_ext_factor = params.yarn_ext_factor;
  13707. cparams.yarn_attn_factor = params.yarn_attn_factor;
  13708. cparams.yarn_beta_fast = params.yarn_beta_fast;
  13709. cparams.yarn_beta_slow = params.yarn_beta_slow;
  13710. cparams.defrag_thold = params.defrag_thold;
  13711. cparams.embeddings = params.embeddings;
  13712. cparams.offload_kqv = params.offload_kqv;
  13713. cparams.flash_attn = params.flash_attn;
  13714. cparams.pooling_type = params.pooling_type;
  13715. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  13716. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  13717. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  13718. // this is necessary due to kv_self.n being padded later during inference
  13719. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  13720. // with causal attention, the batch size is limited by the context size
  13721. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  13722. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  13723. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  13724. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  13725. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  13726. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  13727. cparams.n_batch = GGML_KQ_MASK_PAD;
  13728. }
  13729. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  13730. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  13731. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  13732. hparams.n_ctx_train;
  13733. cparams.cb_eval = params.cb_eval;
  13734. cparams.cb_eval_user_data = params.cb_eval_user_data;
  13735. auto rope_scaling_type = params.rope_scaling_type;
  13736. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  13737. rope_scaling_type = hparams.rope_scaling_type_train;
  13738. }
  13739. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  13740. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  13741. }
  13742. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  13743. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  13744. }
  13745. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  13746. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13747. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13748. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  13749. } else {
  13750. cparams.pooling_type = hparams.pooling_type;
  13751. }
  13752. }
  13753. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  13754. cparams.causal_attn = hparams.causal_attn;
  13755. } else {
  13756. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  13757. }
  13758. if (params.seed == LLAMA_DEFAULT_SEED) {
  13759. params.seed = time(NULL);
  13760. }
  13761. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  13762. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  13763. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  13764. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  13765. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  13766. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  13767. ctx->abort_callback = params.abort_callback;
  13768. ctx->abort_callback_data = params.abort_callback_data;
  13769. ctx->sampling.rng = std::mt19937(params.seed);
  13770. ctx->logits_all = params.logits_all;
  13771. uint32_t kv_size = cparams.n_ctx;
  13772. ggml_type type_k = params.type_k;
  13773. ggml_type type_v = params.type_v;
  13774. // Mamba only needs a constant number of KV cache cells per sequence
  13775. if (model->arch == LLM_ARCH_MAMBA) {
  13776. // Mamba needs at least as many KV cells as there are sequences kept at any time
  13777. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  13778. // it's probably best to keep as much precision as possible for the states
  13779. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  13780. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  13781. }
  13782. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  13783. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  13784. if (!hparams.vocab_only) {
  13785. // initialize backends
  13786. #if defined(GGML_USE_METAL)
  13787. if (model->n_gpu_layers > 0) {
  13788. ctx->backend_metal = ggml_backend_metal_init();
  13789. if (ctx->backend_metal == nullptr) {
  13790. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  13791. llama_free(ctx);
  13792. return nullptr;
  13793. }
  13794. ctx->backends.push_back(ctx->backend_metal);
  13795. }
  13796. #elif defined(GGML_USE_CUDA)
  13797. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13798. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13799. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  13800. if (backend == nullptr) {
  13801. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  13802. llama_free(ctx);
  13803. return nullptr;
  13804. }
  13805. ctx->backends.push_back(backend);
  13806. } else {
  13807. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13808. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  13809. ggml_backend_t backend = ggml_backend_cuda_init(device);
  13810. if (backend == nullptr) {
  13811. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  13812. llama_free(ctx);
  13813. return nullptr;
  13814. }
  13815. ctx->backends.push_back(backend);
  13816. }
  13817. }
  13818. #elif defined(GGML_USE_VULKAN)
  13819. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13820. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  13821. llama_free(ctx);
  13822. return nullptr;
  13823. }
  13824. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  13825. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  13826. if (backend == nullptr) {
  13827. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  13828. llama_free(ctx);
  13829. return nullptr;
  13830. }
  13831. ctx->backends.push_back(backend);
  13832. } else {
  13833. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  13834. ggml_backend_t backend = ggml_backend_vk_init(device);
  13835. if (backend == nullptr) {
  13836. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  13837. llama_free(ctx);
  13838. return nullptr;
  13839. }
  13840. ctx->backends.push_back(backend);
  13841. }
  13842. }
  13843. #elif defined(GGML_USE_SYCL)
  13844. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13845. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13846. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  13847. if (backend == nullptr) {
  13848. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  13849. llama_free(ctx);
  13850. return nullptr;
  13851. }
  13852. ctx->backends.push_back(backend);
  13853. } else {
  13854. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  13855. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  13856. ggml_backend_t backend = ggml_backend_sycl_init(i);
  13857. if (backend == nullptr) {
  13858. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  13859. llama_free(ctx);
  13860. return nullptr;
  13861. }
  13862. ctx->backends.push_back(backend);
  13863. }
  13864. }
  13865. #elif defined(GGML_USE_KOMPUTE)
  13866. if (model->n_gpu_layers > 0) {
  13867. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  13868. if (backend == nullptr) {
  13869. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  13870. llama_free(ctx);
  13871. return nullptr;
  13872. }
  13873. ctx->backends.push_back(backend);
  13874. }
  13875. #elif defined(GGML_USE_CANN)
  13876. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13877. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  13878. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13879. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  13880. if (backend == nullptr) {
  13881. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  13882. llama_free(ctx);
  13883. return nullptr;
  13884. }
  13885. ctx->backends.push_back(backend);
  13886. } else {
  13887. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13888. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  13889. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  13890. ggml_backend_t backend = ggml_backend_cann_init(device);
  13891. if (backend == nullptr) {
  13892. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  13893. llama_free(ctx);
  13894. return nullptr;
  13895. }
  13896. ctx->backends.push_back(backend);
  13897. }
  13898. }
  13899. #endif
  13900. #ifdef GGML_USE_BLAS
  13901. ctx->backend_blas = ggml_backend_blas_init();
  13902. if (ctx->backend_blas == nullptr) {
  13903. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  13904. } else {
  13905. ctx->backends.push_back(ctx->backend_blas);
  13906. }
  13907. #endif
  13908. #if defined(GGML_USE_RPC)
  13909. if (model->n_gpu_layers > 0) {
  13910. for (const auto & endpoint : model->rpc_servers) {
  13911. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  13912. if (backend == nullptr) {
  13913. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  13914. llama_free(ctx);
  13915. return nullptr;
  13916. }
  13917. ctx->backends.push_back(backend);
  13918. }
  13919. }
  13920. #endif
  13921. ctx->backend_cpu = ggml_backend_cpu_init();
  13922. if (ctx->backend_cpu == nullptr) {
  13923. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  13924. llama_free(ctx);
  13925. return nullptr;
  13926. }
  13927. ctx->backends.push_back(ctx->backend_cpu);
  13928. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  13929. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  13930. llama_free(ctx);
  13931. return nullptr;
  13932. }
  13933. {
  13934. size_t memory_size_k = 0;
  13935. size_t memory_size_v = 0;
  13936. for (auto & k : ctx->kv_self.k_l) {
  13937. memory_size_k += ggml_nbytes(k);
  13938. }
  13939. for (auto & v : ctx->kv_self.v_l) {
  13940. memory_size_v += ggml_nbytes(v);
  13941. }
  13942. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  13943. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  13944. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  13945. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  13946. }
  13947. // graph outputs buffer
  13948. {
  13949. // resized during inference when a batch uses more outputs
  13950. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  13951. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  13952. llama_free(ctx);
  13953. return nullptr;
  13954. }
  13955. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  13956. ggml_backend_buffer_name(ctx->buf_output),
  13957. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  13958. }
  13959. // scheduler and compute buffers
  13960. {
  13961. // buffer types used for the compute buffer of each backend
  13962. std::vector<ggml_backend_buffer_type_t> backend_buft;
  13963. for (auto * backend : ctx->backends) {
  13964. if (ggml_backend_is_cpu(backend)) {
  13965. // use host buffers for the CPU backend compute buffer
  13966. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  13967. } else {
  13968. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  13969. }
  13970. }
  13971. const size_t max_nodes = llama_model_max_nodes(*model);
  13972. // buffer used to store the computation graph and the tensor meta data
  13973. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  13974. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  13975. bool pipeline_parallel =
  13976. llama_get_device_count(*model) > 1 &&
  13977. model->n_gpu_layers > (int)model->hparams.n_layer &&
  13978. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  13979. params.offload_kqv;
  13980. #ifndef GGML_USE_CUDA
  13981. // pipeline parallelism requires support for async compute and events
  13982. // currently this is only implemented in the CUDA backend
  13983. pipeline_parallel = false;
  13984. #endif
  13985. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  13986. if (pipeline_parallel) {
  13987. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  13988. }
  13989. // build worst-case graph
  13990. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  13991. int n_past = cparams.n_ctx - n_tokens;
  13992. 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
  13993. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  13994. // initialize scheduler with the worst-case graph
  13995. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  13996. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  13997. llama_free(ctx);
  13998. return nullptr;
  13999. }
  14000. for (size_t i = 0; i < ctx->backends.size(); i++) {
  14001. ggml_backend_t backend = ctx->backends[i];
  14002. ggml_backend_buffer_type_t buft = backend_buft[i];
  14003. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  14004. if (size > 1) {
  14005. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  14006. ggml_backend_buft_name(buft),
  14007. size / 1024.0 / 1024.0);
  14008. }
  14009. }
  14010. // note: the number of splits during measure is higher than during inference due to the kv shift
  14011. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  14012. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  14013. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  14014. }
  14015. }
  14016. return ctx;
  14017. }
  14018. void llama_free(struct llama_context * ctx) {
  14019. delete ctx;
  14020. }
  14021. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  14022. return &ctx->model;
  14023. }
  14024. const struct llama_vocab * llama_get_vocab(const struct llama_context * ctx) {
  14025. return &ctx->model.vocab;
  14026. }
  14027. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  14028. return ctx->cparams.n_ctx;
  14029. }
  14030. uint32_t llama_n_batch(const struct llama_context * ctx) {
  14031. return ctx->cparams.n_batch;
  14032. }
  14033. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  14034. return ctx->cparams.n_ubatch;
  14035. }
  14036. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  14037. return ctx->kv_self.size;
  14038. }
  14039. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  14040. return model->vocab.type;
  14041. }
  14042. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  14043. switch (model->arch) {
  14044. // these models do not use RoPE
  14045. case LLM_ARCH_GPT2:
  14046. case LLM_ARCH_GPTJ:
  14047. case LLM_ARCH_MPT:
  14048. case LLM_ARCH_REFACT:
  14049. case LLM_ARCH_BLOOM:
  14050. case LLM_ARCH_MAMBA:
  14051. case LLM_ARCH_JINA_BERT_V2:
  14052. case LLM_ARCH_T5:
  14053. case LLM_ARCH_JAIS:
  14054. return LLAMA_ROPE_TYPE_NONE;
  14055. // use what we call a normal RoPE, operating on pairs of consecutive head values
  14056. case LLM_ARCH_LLAMA:
  14057. case LLM_ARCH_BAICHUAN:
  14058. case LLM_ARCH_STARCODER:
  14059. case LLM_ARCH_PLAMO:
  14060. case LLM_ARCH_ORION:
  14061. case LLM_ARCH_INTERNLM2:
  14062. case LLM_ARCH_MINICPM:
  14063. case LLM_ARCH_XVERSE:
  14064. case LLM_ARCH_COMMAND_R:
  14065. case LLM_ARCH_OLMO:
  14066. case LLM_ARCH_ARCTIC:
  14067. case LLM_ARCH_DEEPSEEK2:
  14068. case LLM_ARCH_CHATGLM:
  14069. return LLAMA_ROPE_TYPE_NORM;
  14070. // the pairs of head values are offset by n_rot/2
  14071. case LLM_ARCH_FALCON:
  14072. case LLM_ARCH_GROK:
  14073. case LLM_ARCH_DBRX:
  14074. case LLM_ARCH_BERT:
  14075. case LLM_ARCH_NOMIC_BERT:
  14076. case LLM_ARCH_STABLELM:
  14077. case LLM_ARCH_BITNET:
  14078. case LLM_ARCH_QWEN:
  14079. case LLM_ARCH_QWEN2:
  14080. case LLM_ARCH_QWEN2MOE:
  14081. case LLM_ARCH_PHI2:
  14082. case LLM_ARCH_PHI3:
  14083. case LLM_ARCH_GEMMA:
  14084. case LLM_ARCH_GEMMA2:
  14085. case LLM_ARCH_STARCODER2:
  14086. case LLM_ARCH_OPENELM:
  14087. case LLM_ARCH_GPTNEOX:
  14088. case LLM_ARCH_CODESHELL:
  14089. return LLAMA_ROPE_TYPE_NEOX;
  14090. // all model arches should be listed explicitly here
  14091. case LLM_ARCH_UNKNOWN:
  14092. GGML_ABORT("unknown architecture");
  14093. }
  14094. return LLAMA_ROPE_TYPE_NONE;
  14095. }
  14096. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  14097. return ctx->cparams.pooling_type;
  14098. }
  14099. int32_t llama_n_vocab(const struct llama_model * model) {
  14100. return model->hparams.n_vocab;
  14101. }
  14102. int32_t llama_n_ctx_train(const struct llama_model * model) {
  14103. return model->hparams.n_ctx_train;
  14104. }
  14105. int32_t llama_n_embd(const struct llama_model * model) {
  14106. return model->hparams.n_embd;
  14107. }
  14108. int32_t llama_n_layer(const struct llama_model * model) {
  14109. return model->hparams.n_layer;
  14110. }
  14111. float llama_rope_freq_scale_train(const struct llama_model * model) {
  14112. return model->hparams.rope_freq_scale_train;
  14113. }
  14114. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  14115. const auto & it = model->gguf_kv.find(key);
  14116. if (it == model->gguf_kv.end()) {
  14117. if (buf_size > 0) {
  14118. buf[0] = '\0';
  14119. }
  14120. return -1;
  14121. }
  14122. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14123. }
  14124. int32_t llama_model_meta_count(const struct llama_model * model) {
  14125. return (int)model->gguf_kv.size();
  14126. }
  14127. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  14128. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14129. if (buf_size > 0) {
  14130. buf[0] = '\0';
  14131. }
  14132. return -1;
  14133. }
  14134. auto it = model->gguf_kv.begin();
  14135. std::advance(it, i);
  14136. return snprintf(buf, buf_size, "%s", it->first.c_str());
  14137. }
  14138. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  14139. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14140. if (buf_size > 0) {
  14141. buf[0] = '\0';
  14142. }
  14143. return -1;
  14144. }
  14145. auto it = model->gguf_kv.begin();
  14146. std::advance(it, i);
  14147. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14148. }
  14149. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  14150. return snprintf(buf, buf_size, "%s %s %s",
  14151. llama_model_arch_name(model->arch),
  14152. llama_model_type_name(model->type),
  14153. llama_model_ftype_name(model->ftype).c_str());
  14154. }
  14155. uint64_t llama_model_size(const struct llama_model * model) {
  14156. uint64_t size = 0;
  14157. for (const auto & it : model->tensors_by_name) {
  14158. size += ggml_nbytes(it.second);
  14159. }
  14160. return size;
  14161. }
  14162. uint64_t llama_model_n_params(const struct llama_model * model) {
  14163. uint64_t nparams = 0;
  14164. for (const auto & it : model->tensors_by_name) {
  14165. nparams += ggml_nelements(it.second);
  14166. }
  14167. return nparams;
  14168. }
  14169. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  14170. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  14171. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  14172. return it.first == name;
  14173. });
  14174. if (it == model->tensors_by_name.end()) {
  14175. return nullptr;
  14176. }
  14177. return it->second;
  14178. }
  14179. bool llama_model_has_encoder(const struct llama_model * model) {
  14180. switch (model->arch) {
  14181. case LLM_ARCH_T5: return true;
  14182. default: return false;
  14183. }
  14184. }
  14185. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  14186. return model->hparams.dec_start_token_id;
  14187. }
  14188. uint32_t llama_model_quantize(
  14189. const char * fname_inp,
  14190. const char * fname_out,
  14191. const llama_model_quantize_params * params) {
  14192. try {
  14193. llama_model_quantize_internal(fname_inp, fname_out, params);
  14194. return 0;
  14195. } catch (const std::exception & err) {
  14196. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  14197. return 1;
  14198. }
  14199. }
  14200. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  14201. try {
  14202. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  14203. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  14204. return adapter;
  14205. } catch (const std::exception & err) {
  14206. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  14207. return nullptr;
  14208. }
  14209. }
  14210. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  14211. GGML_ASSERT(cvec.tensors.empty());
  14212. GGML_ASSERT(cvec.ctxs.empty());
  14213. GGML_ASSERT(cvec.bufs.empty());
  14214. // count layer buffer types
  14215. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  14216. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  14217. buft_layer_count[model.buft_layer[i].buft]++;
  14218. }
  14219. // allocate contexts
  14220. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  14221. for (auto & it : buft_layer_count) {
  14222. int n_layers = it.second;
  14223. struct ggml_init_params params = {
  14224. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  14225. /*.mem_buffer =*/ NULL,
  14226. /*.no_alloc =*/ true,
  14227. };
  14228. ggml_context * ctx = ggml_init(params);
  14229. if (!ctx) {
  14230. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  14231. return 1;
  14232. }
  14233. ctx_map[it.first] = ctx;
  14234. }
  14235. // make tensors
  14236. cvec.tensors.reserve(model.hparams.n_layer);
  14237. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  14238. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14239. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  14240. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  14241. cvec.tensors.push_back(tensor);
  14242. }
  14243. // allocate tensors / buffers and zero
  14244. cvec.ctxs.reserve(ctx_map.size());
  14245. cvec.bufs.reserve(ctx_map.size());
  14246. for (auto it : ctx_map) {
  14247. ggml_backend_buffer_type_t buft = it.first;
  14248. ggml_context * ctx = it.second;
  14249. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  14250. if (!buf) {
  14251. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  14252. return false;
  14253. }
  14254. ggml_backend_buffer_clear(buf, 0);
  14255. cvec.ctxs.push_back(ctx);
  14256. cvec.bufs.push_back(buf);
  14257. }
  14258. return true;
  14259. }
  14260. 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) {
  14261. const llama_model & model = lctx->model;
  14262. llama_control_vector & cvec = lctx->cvec;
  14263. if (data == nullptr) {
  14264. // disable the current control vector (but leave allocated for later)
  14265. cvec.layer_start = -1;
  14266. cvec.layer_end = -1;
  14267. return 0;
  14268. }
  14269. if (n_embd != (int) model.hparams.n_embd) {
  14270. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  14271. return 1;
  14272. }
  14273. if (cvec.tensors.empty()) {
  14274. if (!llama_control_vector_init(cvec, model)) {
  14275. return 1;
  14276. }
  14277. }
  14278. cvec.layer_start = il_start;
  14279. cvec.layer_end = il_end;
  14280. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14281. assert(cvec.tensors[il] != nullptr);
  14282. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  14283. if (off + n_embd <= len) {
  14284. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  14285. }
  14286. }
  14287. return 0;
  14288. }
  14289. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  14290. struct llama_kv_cache_view result = {
  14291. /*.n_cells = */ 0,
  14292. /*.n_seq_max = */ n_seq_max,
  14293. /*.token_count = */ 0,
  14294. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  14295. /*.max_contiguous = */ 0,
  14296. /*.max_contiguous_idx = */ -1,
  14297. /*.cells = */ nullptr,
  14298. /*.cells_sequences = */ nullptr,
  14299. };
  14300. return result;
  14301. }
  14302. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  14303. if (view->cells != nullptr) {
  14304. free(view->cells);
  14305. view->cells = nullptr;
  14306. }
  14307. if (view->cells_sequences != nullptr) {
  14308. free(view->cells_sequences);
  14309. view->cells_sequences = nullptr;
  14310. }
  14311. }
  14312. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  14313. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  14314. view->n_cells = int32_t(ctx->kv_self.size);
  14315. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  14316. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  14317. view->cells = (struct llama_kv_cache_view_cell *)p;
  14318. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  14319. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  14320. view->cells_sequences = (llama_seq_id *)p;
  14321. }
  14322. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  14323. llama_kv_cache_view_cell * c_curr = view->cells;
  14324. llama_seq_id * cs_curr = view->cells_sequences;
  14325. int32_t used_cells = 0;
  14326. int32_t token_count = 0;
  14327. int32_t curr_contig_idx = -1;
  14328. uint32_t max_contig = 0;
  14329. int32_t max_contig_idx = -1;
  14330. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  14331. const size_t curr_size = kv_cells[i].seq_id.size();
  14332. token_count += curr_size;
  14333. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  14334. if (curr_size > 0) {
  14335. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  14336. max_contig = i - curr_contig_idx;
  14337. max_contig_idx = curr_contig_idx;
  14338. }
  14339. curr_contig_idx = -1;
  14340. } else if (curr_contig_idx < 0) {
  14341. curr_contig_idx = i;
  14342. }
  14343. int seq_idx = 0;
  14344. for (const llama_seq_id it : kv_cells[i].seq_id) {
  14345. if (seq_idx >= view->n_seq_max) {
  14346. break;
  14347. }
  14348. cs_curr[seq_idx] = it;
  14349. seq_idx++;
  14350. }
  14351. if (seq_idx != 0) {
  14352. used_cells++;
  14353. }
  14354. for (; seq_idx < view->n_seq_max; seq_idx++) {
  14355. cs_curr[seq_idx] = -1;
  14356. }
  14357. }
  14358. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  14359. max_contig_idx = curr_contig_idx;
  14360. max_contig = kv_cells.size() - curr_contig_idx;
  14361. }
  14362. view->max_contiguous = max_contig;
  14363. view->max_contiguous_idx = max_contig_idx;
  14364. view->token_count = token_count;
  14365. view->used_cells = used_cells;
  14366. if (uint32_t(used_cells) != ctx->kv_self.used) {
  14367. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  14368. __func__, ctx->kv_self.used, used_cells);
  14369. }
  14370. }
  14371. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  14372. int result = 0;
  14373. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  14374. result += ctx->kv_self.cells[i].seq_id.size();
  14375. }
  14376. return result;
  14377. }
  14378. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  14379. return ctx->kv_self.used;
  14380. }
  14381. void llama_kv_cache_clear(struct llama_context * ctx) {
  14382. llama_kv_cache_clear(ctx->kv_self);
  14383. }
  14384. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  14385. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  14386. }
  14387. 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) {
  14388. if (seq_id_src == seq_id_dst) {
  14389. return;
  14390. }
  14391. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  14392. }
  14393. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  14394. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  14395. }
  14396. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  14397. if (delta == 0) {
  14398. return;
  14399. }
  14400. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  14401. }
  14402. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  14403. if (d == 1) {
  14404. return;
  14405. }
  14406. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  14407. }
  14408. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  14409. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  14410. }
  14411. void llama_kv_cache_defrag(struct llama_context * ctx) {
  14412. llama_kv_cache_defrag(ctx->kv_self);
  14413. }
  14414. void llama_kv_cache_update(struct llama_context * ctx) {
  14415. llama_kv_cache_update_internal(*ctx);
  14416. }
  14417. // deprecated
  14418. size_t llama_get_state_size(struct llama_context * ctx) {
  14419. return llama_state_get_size(ctx);
  14420. }
  14421. // deprecated
  14422. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  14423. return llama_state_get_data(ctx, dst, -1);
  14424. }
  14425. // deprecated
  14426. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  14427. return llama_state_set_data(ctx, src, -1);
  14428. }
  14429. // deprecated
  14430. 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) {
  14431. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14432. }
  14433. // deprecated
  14434. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14435. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  14436. }
  14437. // TODO: replace all non-fatal assertions with returned errors or exceptions
  14438. struct llama_data_write {
  14439. virtual void write(const void * src, size_t size) = 0;
  14440. virtual size_t get_size_written() = 0;
  14441. virtual ~llama_data_write() = default;
  14442. void write_string(const std::string & str) {
  14443. uint32_t str_size = str.size();
  14444. write(&str_size, sizeof(str_size));
  14445. write(str.data(), str_size);
  14446. }
  14447. void write_model_info(const struct llama_context * ctx) {
  14448. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14449. write_string(arch_str);
  14450. // TODO: add more model-specific info which should prevent loading the session file if not identical
  14451. }
  14452. void write_rng(const std::mt19937 & rng) {
  14453. std::ostringstream rng_ss;
  14454. rng_ss << rng;
  14455. const std::string & rng_str = rng_ss.str();
  14456. write_string(rng_str);
  14457. }
  14458. void write_output_ids(const struct llama_context * ctx) {
  14459. const uint32_t n_outputs = ctx->n_outputs;
  14460. std::vector<int32_t> output_pos;
  14461. const size_t n_batch = ctx->cparams.n_batch;
  14462. const auto & output_ids = ctx->output_ids;
  14463. GGML_ASSERT(n_outputs <= ctx->output_size);
  14464. output_pos.resize(n_outputs);
  14465. // build a more compact representation of the output ids
  14466. for (size_t i = 0; i < n_batch; ++i) {
  14467. // map an output id to a position in the batch
  14468. int32_t pos = output_ids[i];
  14469. if (pos >= 0) {
  14470. GGML_ASSERT((uint32_t) pos < n_outputs);
  14471. output_pos[pos] = i;
  14472. }
  14473. }
  14474. write(&n_outputs, sizeof(n_outputs));
  14475. if (n_outputs) {
  14476. write(output_pos.data(), n_outputs * sizeof(int32_t));
  14477. }
  14478. }
  14479. void write_logits(const struct llama_context * ctx) {
  14480. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  14481. write(&logits_size, sizeof(logits_size));
  14482. if (logits_size) {
  14483. write(ctx->logits, logits_size * sizeof(float));
  14484. }
  14485. }
  14486. void write_embeddings(const struct llama_context * ctx) {
  14487. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  14488. write(&embeddings_size, sizeof(embeddings_size));
  14489. if (embeddings_size) {
  14490. write(ctx->embd, embeddings_size * sizeof(float));
  14491. }
  14492. }
  14493. 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) {
  14494. for (const auto & range : cell_ranges) {
  14495. for (uint32_t i = range.first; i < range.second; ++i) {
  14496. const auto & cell = kv_self.cells[i];
  14497. const llama_pos pos = cell.pos;
  14498. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  14499. write(&pos, sizeof(pos));
  14500. write(&n_seq_id, sizeof(n_seq_id));
  14501. if (n_seq_id) {
  14502. for (auto seq_id : cell.seq_id) {
  14503. write(&seq_id, sizeof(seq_id));
  14504. }
  14505. }
  14506. }
  14507. }
  14508. }
  14509. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  14510. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14511. const struct llama_hparams & hparams = ctx->model.hparams;
  14512. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  14513. const uint32_t n_layer = hparams.n_layer;
  14514. write(&v_trans, sizeof(v_trans));
  14515. write(&n_layer, sizeof(n_layer));
  14516. std::vector<uint8_t> tmp_buf;
  14517. // Iterate and write all the keys first, each row is a cell
  14518. // Get whole range at a time
  14519. for (uint32_t il = 0; il < n_layer; ++il) {
  14520. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14521. // Write key type
  14522. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14523. write(&k_type_i, sizeof(k_type_i));
  14524. // Write row size of key
  14525. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14526. write(&k_size_row, sizeof(k_size_row));
  14527. // Read each range of cells of k_size length each into tmp_buf and write out
  14528. for (const auto & range : cell_ranges) {
  14529. const size_t range_size = range.second - range.first;
  14530. tmp_buf.resize(range_size * k_size_row);
  14531. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  14532. write(tmp_buf.data(), tmp_buf.size());
  14533. }
  14534. }
  14535. if (!kv_self.v_trans) {
  14536. for (uint32_t il = 0; il < n_layer; ++il) {
  14537. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14538. // Write value type
  14539. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14540. write(&v_type_i, sizeof(v_type_i));
  14541. // Write row size of value
  14542. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14543. write(&v_size_row, sizeof(v_size_row));
  14544. // Read each range of cells of v_size length each into tmp_buf and write out
  14545. for (const auto & range : cell_ranges) {
  14546. const size_t range_size = range.second - range.first;
  14547. tmp_buf.resize(range_size * v_size_row);
  14548. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), range.first * v_size_row, range_size * v_size_row);
  14549. write(tmp_buf.data(), tmp_buf.size());
  14550. }
  14551. }
  14552. } else {
  14553. // When v is transposed, we also need the element size and get the element ranges from each row
  14554. const uint32_t kv_size = kv_self.size;
  14555. for (uint32_t il = 0; il < n_layer; ++il) {
  14556. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14557. // Write value type
  14558. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14559. write(&v_type_i, sizeof(v_type_i));
  14560. // Write element size
  14561. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14562. write(&v_size_el, sizeof(v_size_el));
  14563. // Write GQA embedding size
  14564. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  14565. // For each row, we get the element values of each cell
  14566. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14567. // Read each range of cells of v_size_el length each into tmp_buf and write out
  14568. for (const auto & range : cell_ranges) {
  14569. const size_t range_size = range.second - range.first;
  14570. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  14571. tmp_buf.resize(range_size * v_size_el);
  14572. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  14573. write(tmp_buf.data(), tmp_buf.size());
  14574. }
  14575. }
  14576. }
  14577. }
  14578. }
  14579. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14580. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14581. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  14582. uint32_t cell_count = 0;
  14583. // Count the number of cells with the specified seq_id
  14584. // Find all the ranges of cells with this seq id (or all, when -1)
  14585. uint32_t cell_range_begin = kv_self.size;
  14586. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14587. const auto & cell = kv_self.cells[i];
  14588. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  14589. ++cell_count;
  14590. if (cell_range_begin == kv_self.size) {
  14591. cell_range_begin = i;
  14592. }
  14593. } else {
  14594. if (cell_range_begin != kv_self.size) {
  14595. cell_ranges.emplace_back(cell_range_begin, i);
  14596. cell_range_begin = kv_self.size;
  14597. }
  14598. }
  14599. }
  14600. if (cell_range_begin != kv_self.size) {
  14601. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  14602. }
  14603. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  14604. uint32_t cell_count_check = 0;
  14605. for (const auto & range : cell_ranges) {
  14606. cell_count_check += range.second - range.first;
  14607. }
  14608. GGML_ASSERT(cell_count == cell_count_check);
  14609. write(&cell_count, sizeof(cell_count));
  14610. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  14611. write_kv_cache_data(ctx, cell_ranges);
  14612. }
  14613. };
  14614. struct llama_data_read {
  14615. virtual const uint8_t * read(size_t size) = 0;
  14616. virtual void read_to(void * dst, size_t size) = 0;
  14617. virtual size_t get_size_read() = 0;
  14618. virtual ~llama_data_read() = default;
  14619. void read_string(std::string & str) {
  14620. uint32_t str_size;
  14621. read_to(&str_size, sizeof(str_size));
  14622. str.assign((const char *) read(str_size), str_size);
  14623. }
  14624. // validate model information
  14625. void read_model_info(const struct llama_context * ctx) {
  14626. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14627. std::string arch_str;
  14628. read_string(arch_str);
  14629. if (cur_arch_str != arch_str) {
  14630. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  14631. }
  14632. // TODO: add more info which needs to be identical but which is not verified otherwise
  14633. }
  14634. void read_rng(std::mt19937 & rng) {
  14635. std::string rng_str;
  14636. read_string(rng_str);
  14637. std::istringstream rng_ss(rng_str);
  14638. rng_ss >> rng;
  14639. if (rng_ss.fail()) {
  14640. throw std::runtime_error("failed to load RNG state");
  14641. }
  14642. }
  14643. void read_output_ids(struct llama_context * ctx) {
  14644. std::vector<int32_t> output_pos;
  14645. uint32_t n_outputs;
  14646. read_to(&n_outputs, sizeof(n_outputs));
  14647. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  14648. throw std::runtime_error("could not reserve outputs");
  14649. }
  14650. if (n_outputs) {
  14651. output_pos.resize(n_outputs);
  14652. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  14653. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  14654. int32_t id = output_pos[i];
  14655. if ((uint32_t) id >= ctx->cparams.n_batch) {
  14656. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  14657. }
  14658. ctx->output_ids[id] = i;
  14659. }
  14660. ctx->n_outputs = n_outputs;
  14661. }
  14662. }
  14663. void read_logits(struct llama_context * ctx) {
  14664. uint64_t logits_size;
  14665. read_to(&logits_size, sizeof(logits_size));
  14666. if (ctx->logits_size < logits_size) {
  14667. throw std::runtime_error("logits buffer too small");
  14668. }
  14669. if (logits_size) {
  14670. read_to(ctx->logits, logits_size * sizeof(float));
  14671. }
  14672. }
  14673. void read_embeddings(struct llama_context * ctx) {
  14674. uint64_t embeddings_size;
  14675. read_to(&embeddings_size, sizeof(embeddings_size));
  14676. if (ctx->embd_size < embeddings_size) {
  14677. throw std::runtime_error("embeddings buffer too small");
  14678. }
  14679. if (embeddings_size) {
  14680. read_to(ctx->embd, embeddings_size * sizeof(float));
  14681. }
  14682. }
  14683. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  14684. struct llama_kv_cache & kv_self = ctx->kv_self;
  14685. if (dest_seq_id != -1) {
  14686. // single sequence
  14687. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14688. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  14689. batch.n_tokens = cell_count;
  14690. for (uint32_t i = 0; i < cell_count; ++i) {
  14691. llama_pos pos;
  14692. uint32_t n_seq_id;
  14693. read_to(&pos, sizeof(pos));
  14694. read_to(&n_seq_id, sizeof(n_seq_id));
  14695. if (n_seq_id != 0) {
  14696. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  14697. return false;
  14698. }
  14699. batch.pos[i] = pos;
  14700. batch.n_seq_id[i] = 1;
  14701. batch.seq_id[i][0] = dest_seq_id;
  14702. }
  14703. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  14704. llama_batch_free(batch);
  14705. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  14706. return false;
  14707. }
  14708. // 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)
  14709. // Assume that this is one contiguous block of cells
  14710. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  14711. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  14712. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  14713. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  14714. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  14715. // Cleanup
  14716. llama_batch_free(batch);
  14717. } else {
  14718. // whole KV cache restore
  14719. if (cell_count > kv_self.size) {
  14720. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  14721. return false;
  14722. }
  14723. llama_kv_cache_clear(kv_self);
  14724. for (uint32_t i = 0; i < cell_count; ++i) {
  14725. llama_kv_cell & cell = kv_self.cells[i];
  14726. llama_pos pos;
  14727. uint32_t n_seq_id;
  14728. read_to(&pos, sizeof(pos));
  14729. read_to(&n_seq_id, sizeof(n_seq_id));
  14730. cell.pos = pos;
  14731. for (uint32_t j = 0; j < n_seq_id; ++j) {
  14732. llama_seq_id seq_id;
  14733. read_to(&seq_id, sizeof(seq_id));
  14734. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  14735. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  14736. return false;
  14737. }
  14738. cell.seq_id.insert(seq_id);
  14739. }
  14740. }
  14741. kv_self.head = 0;
  14742. kv_self.used = cell_count;
  14743. }
  14744. return true;
  14745. }
  14746. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  14747. const struct llama_hparams & hparams = ctx->model.hparams;
  14748. struct llama_kv_cache & kv_self = ctx->kv_self;
  14749. uint32_t v_trans;
  14750. uint32_t n_layer;
  14751. read_to(&v_trans, sizeof(v_trans));
  14752. read_to(&n_layer, sizeof(n_layer));
  14753. if (n_layer != hparams.n_layer) {
  14754. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  14755. return false;
  14756. }
  14757. if (cell_count > kv_self.size) {
  14758. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  14759. return false;
  14760. }
  14761. if (kv_self.v_trans != (bool) v_trans) {
  14762. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  14763. return false;
  14764. }
  14765. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  14766. for (uint32_t il = 0; il < n_layer; ++il) {
  14767. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14768. // Read type of key
  14769. int32_t k_type_i_ref;
  14770. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  14771. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14772. if (k_type_i != k_type_i_ref) {
  14773. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  14774. return false;
  14775. }
  14776. // Read row size of key
  14777. uint64_t k_size_row_ref;
  14778. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  14779. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14780. if (k_size_row != k_size_row_ref) {
  14781. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  14782. return false;
  14783. }
  14784. if (cell_count) {
  14785. // Read and set the keys for the whole cell range
  14786. 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);
  14787. }
  14788. }
  14789. if (!kv_self.v_trans) {
  14790. for (uint32_t il = 0; il < n_layer; ++il) {
  14791. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14792. // Read type of value
  14793. int32_t v_type_i_ref;
  14794. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14795. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14796. if (v_type_i != v_type_i_ref) {
  14797. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14798. return false;
  14799. }
  14800. // Read row size of value
  14801. uint64_t v_size_row_ref;
  14802. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  14803. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14804. if (v_size_row != v_size_row_ref) {
  14805. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  14806. return false;
  14807. }
  14808. if (cell_count) {
  14809. // Read and set the values for the whole cell range
  14810. 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);
  14811. }
  14812. }
  14813. } else {
  14814. // For each layer, read the values for each cell (transposed)
  14815. for (uint32_t il = 0; il < n_layer; ++il) {
  14816. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14817. // Read type of value
  14818. int32_t v_type_i_ref;
  14819. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14820. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14821. if (v_type_i != v_type_i_ref) {
  14822. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14823. return false;
  14824. }
  14825. // Read element size of value
  14826. uint32_t v_size_el_ref;
  14827. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  14828. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14829. if (v_size_el != v_size_el_ref) {
  14830. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  14831. return false;
  14832. }
  14833. // Read GQA embedding size
  14834. uint32_t n_embd_v_gqa_ref;
  14835. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  14836. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  14837. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  14838. return false;
  14839. }
  14840. if (cell_count) {
  14841. // For each row in the transposed matrix, read the values for the whole cell range
  14842. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14843. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  14844. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  14845. }
  14846. }
  14847. }
  14848. }
  14849. return true;
  14850. }
  14851. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14852. uint32_t cell_count;
  14853. read_to(&cell_count, sizeof(cell_count));
  14854. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  14855. if (!res) {
  14856. if (seq_id == -1) {
  14857. llama_kv_cache_clear(ctx);
  14858. } else {
  14859. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  14860. }
  14861. throw std::runtime_error("failed to restore kv cache");
  14862. }
  14863. }
  14864. };
  14865. struct llama_data_write_dummy : llama_data_write {
  14866. size_t size_written = 0;
  14867. llama_data_write_dummy() {}
  14868. // TODO: avoid unnecessary calls to ggml_backend_tensor_get in a dummy context
  14869. void write(const void * /* src */, size_t size) override {
  14870. size_written += size;
  14871. }
  14872. size_t get_size_written() override {
  14873. return size_written;
  14874. }
  14875. };
  14876. struct llama_data_write_buffer : llama_data_write {
  14877. uint8_t * ptr;
  14878. size_t buf_size = 0;
  14879. size_t size_written = 0;
  14880. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14881. void write(const void * src, size_t size) override {
  14882. if (size > buf_size) {
  14883. throw std::runtime_error("unexpectedly reached end of buffer");
  14884. }
  14885. memcpy(ptr, src, size);
  14886. ptr += size;
  14887. size_written += size;
  14888. buf_size -= size;
  14889. }
  14890. size_t get_size_written() override {
  14891. return size_written;
  14892. }
  14893. };
  14894. struct llama_data_read_buffer : llama_data_read {
  14895. const uint8_t * ptr;
  14896. size_t buf_size = 0;
  14897. size_t size_read = 0;
  14898. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14899. const uint8_t * read(size_t size) override {
  14900. const uint8_t * base_ptr = ptr;
  14901. if (size > buf_size) {
  14902. throw std::runtime_error("unexpectedly reached end of buffer");
  14903. }
  14904. ptr += size;
  14905. size_read += size;
  14906. buf_size -= size;
  14907. return base_ptr;
  14908. }
  14909. void read_to(void * dst, size_t size) override {
  14910. memcpy(dst, read(size), size);
  14911. }
  14912. size_t get_size_read() override {
  14913. return size_read;
  14914. }
  14915. };
  14916. struct llama_data_write_file : llama_data_write {
  14917. llama_file * file;
  14918. size_t size_written = 0;
  14919. llama_data_write_file(llama_file * f) : file(f) {}
  14920. void write(const void * src, size_t size) override {
  14921. file->write_raw(src, size);
  14922. size_written += size;
  14923. }
  14924. size_t get_size_written() override {
  14925. return size_written;
  14926. }
  14927. };
  14928. struct llama_data_read_file : llama_data_read {
  14929. llama_file * file;
  14930. size_t size_read = 0;
  14931. std::vector<uint8_t> temp_buffer;
  14932. llama_data_read_file(llama_file * f) : file(f) {}
  14933. void read_to(void * dst, size_t size) override {
  14934. file->read_raw(dst, size);
  14935. size_read += size;
  14936. }
  14937. const uint8_t * read(size_t size) override {
  14938. temp_buffer.resize(size);
  14939. read_to(temp_buffer.data(), size);
  14940. return temp_buffer.data();
  14941. }
  14942. size_t get_size_read() override {
  14943. return size_read;
  14944. }
  14945. };
  14946. /** copy state data into either a buffer or file depending on the passed in context
  14947. *
  14948. * file context:
  14949. * llama_file file("/path", "wb");
  14950. * llama_data_write_file data_ctx(&file);
  14951. * llama_state_get_data_internal(ctx, data_ctx);
  14952. *
  14953. * buffer context:
  14954. * std::vector<uint8_t> buf(max_size, 0);
  14955. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  14956. * llama_state_get_data_internal(ctx, data_ctx);
  14957. *
  14958. */
  14959. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  14960. llama_synchronize(ctx);
  14961. data_ctx.write_model_info(ctx);
  14962. data_ctx.write_rng(ctx->sampling.rng);
  14963. // copy outputs
  14964. data_ctx.write_output_ids(ctx);
  14965. data_ctx.write_logits(ctx);
  14966. data_ctx.write_embeddings(ctx);
  14967. data_ctx.write_kv_cache(ctx);
  14968. return data_ctx.get_size_written();
  14969. }
  14970. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  14971. llama_data_write_buffer data_ctx(dst, size);
  14972. try {
  14973. return llama_state_get_data_internal(ctx, data_ctx);
  14974. } catch (const std::exception & err) {
  14975. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  14976. return 0;
  14977. }
  14978. }
  14979. // Returns the *actual* size of the state.
  14980. // Intended to be used when saving to state to a buffer.
  14981. size_t llama_state_get_size(struct llama_context * ctx) {
  14982. llama_data_write_dummy data_ctx;
  14983. try {
  14984. return llama_state_get_data_internal(ctx, data_ctx);
  14985. } catch (const std::exception & err) {
  14986. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  14987. return 0;
  14988. }
  14989. }
  14990. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  14991. llama_synchronize(ctx);
  14992. data_ctx.read_model_info(ctx);
  14993. // set rng
  14994. data_ctx.read_rng(ctx->sampling.rng);
  14995. // set outputs
  14996. data_ctx.read_output_ids(ctx);
  14997. data_ctx.read_logits(ctx);
  14998. data_ctx.read_embeddings(ctx);
  14999. data_ctx.read_kv_cache(ctx);
  15000. return data_ctx.get_size_read();
  15001. }
  15002. // Sets the state reading from the specified source address
  15003. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  15004. llama_data_read_buffer data_ctx(src, size);
  15005. try {
  15006. return llama_state_set_data_internal(ctx, data_ctx);
  15007. } catch (const std::exception & err) {
  15008. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  15009. return 0;
  15010. }
  15011. }
  15012. 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) {
  15013. llama_file file(path_session, "rb");
  15014. // sanity checks
  15015. {
  15016. const uint32_t magic = file.read_u32();
  15017. const uint32_t version = file.read_u32();
  15018. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  15019. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  15020. return false;
  15021. }
  15022. }
  15023. // load the prompt
  15024. {
  15025. const uint32_t n_token_count = file.read_u32();
  15026. if (n_token_count > n_token_capacity) {
  15027. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15028. return false;
  15029. }
  15030. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15031. *n_token_count_out = n_token_count;
  15032. }
  15033. // restore the context state
  15034. {
  15035. const size_t n_state_size_cur = file.size - file.tell();
  15036. llama_data_read_file data_ctx(&file);
  15037. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  15038. if (n_read != n_state_size_cur) {
  15039. 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);
  15040. return false;
  15041. }
  15042. }
  15043. return true;
  15044. }
  15045. 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) {
  15046. try {
  15047. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  15048. } catch (const std::exception & err) {
  15049. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  15050. return false;
  15051. }
  15052. }
  15053. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15054. llama_file file(path_session, "wb");
  15055. file.write_u32(LLAMA_SESSION_MAGIC);
  15056. file.write_u32(LLAMA_SESSION_VERSION);
  15057. // save the prompt
  15058. file.write_u32((uint32_t) n_token_count);
  15059. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15060. // save the context state using stream saving
  15061. llama_data_write_file data_ctx(&file);
  15062. llama_state_get_data_internal(ctx, data_ctx);
  15063. return true;
  15064. }
  15065. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15066. try {
  15067. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  15068. } catch (const std::exception & err) {
  15069. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  15070. return false;
  15071. }
  15072. }
  15073. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  15074. llama_synchronize(ctx);
  15075. data_ctx.write_kv_cache(ctx, seq_id);
  15076. return data_ctx.get_size_written();
  15077. }
  15078. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  15079. llama_data_write_dummy data_ctx;
  15080. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15081. }
  15082. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  15083. llama_data_write_buffer data_ctx(dst, size);
  15084. try {
  15085. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15086. } catch (const std::exception & err) {
  15087. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  15088. return 0;
  15089. }
  15090. }
  15091. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  15092. llama_synchronize(ctx);
  15093. data_ctx.read_kv_cache(ctx, dest_seq_id);
  15094. return data_ctx.get_size_read();
  15095. }
  15096. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  15097. llama_data_read_buffer data_ctx(src, size);
  15098. try {
  15099. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15100. } catch (const std::exception & err) {
  15101. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  15102. return 0;
  15103. }
  15104. }
  15105. 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) {
  15106. llama_file file(filepath, "wb");
  15107. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  15108. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  15109. // save the prompt
  15110. file.write_u32((uint32_t) n_token_count);
  15111. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15112. // save the context state using stream saving
  15113. llama_data_write_file data_ctx(&file);
  15114. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15115. const size_t res = file.tell();
  15116. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  15117. return res;
  15118. }
  15119. 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) {
  15120. llama_file file(filepath, "rb");
  15121. // version checks
  15122. {
  15123. const uint32_t magic = file.read_u32();
  15124. const uint32_t version = file.read_u32();
  15125. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  15126. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  15127. return 0;
  15128. }
  15129. }
  15130. // load the prompt
  15131. {
  15132. const uint32_t n_token_count = file.read_u32();
  15133. if (n_token_count > n_token_capacity) {
  15134. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15135. return 0;
  15136. }
  15137. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15138. *n_token_count_out = n_token_count;
  15139. }
  15140. // restore the context state
  15141. {
  15142. const size_t state_size = file.size - file.tell();
  15143. llama_data_read_file data_ctx(&file);
  15144. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15145. if (!nread) {
  15146. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  15147. return 0;
  15148. }
  15149. GGML_ASSERT(nread <= state_size);
  15150. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  15151. }
  15152. return file.tell();
  15153. }
  15154. 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) {
  15155. try {
  15156. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  15157. } catch (const std::exception & err) {
  15158. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  15159. return 0;
  15160. }
  15161. }
  15162. 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) {
  15163. try {
  15164. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  15165. } catch (const std::exception & err) {
  15166. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  15167. return 0;
  15168. }
  15169. }
  15170. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  15171. ctx->cparams.n_threads = n_threads;
  15172. ctx->cparams.n_threads_batch = n_threads_batch;
  15173. }
  15174. uint32_t llama_n_threads(struct llama_context * ctx) {
  15175. return ctx->cparams.n_threads;
  15176. }
  15177. uint32_t llama_n_threads_batch(struct llama_context * ctx) {
  15178. return ctx->cparams.n_threads_batch;
  15179. }
  15180. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  15181. ctx->abort_callback = abort_callback;
  15182. ctx->abort_callback_data = abort_callback_data;
  15183. }
  15184. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  15185. ctx->cparams.embeddings = embeddings;
  15186. }
  15187. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  15188. ctx->cparams.causal_attn = causal_attn;
  15189. }
  15190. struct llama_batch llama_batch_get_one(
  15191. llama_token * tokens,
  15192. int32_t n_tokens,
  15193. llama_pos pos_0,
  15194. llama_seq_id seq_id) {
  15195. return {
  15196. /*n_tokens =*/ n_tokens,
  15197. /*tokens =*/ tokens,
  15198. /*embd =*/ nullptr,
  15199. /*pos =*/ nullptr,
  15200. /*n_seq_id =*/ nullptr,
  15201. /*seq_id =*/ nullptr,
  15202. /*logits =*/ nullptr,
  15203. /*all_pos_0 =*/ pos_0,
  15204. /*all_pos_1 =*/ 1,
  15205. /*all_seq_id =*/ seq_id,
  15206. };
  15207. }
  15208. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  15209. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  15210. if (embd) {
  15211. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  15212. } else {
  15213. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  15214. }
  15215. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  15216. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  15217. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  15218. for (int i = 0; i < n_tokens_alloc; ++i) {
  15219. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  15220. }
  15221. batch.seq_id[n_tokens_alloc] = nullptr;
  15222. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  15223. return batch;
  15224. }
  15225. void llama_batch_free(struct llama_batch batch) {
  15226. if (batch.token) free(batch.token);
  15227. if (batch.embd) free(batch.embd);
  15228. if (batch.pos) free(batch.pos);
  15229. if (batch.n_seq_id) free(batch.n_seq_id);
  15230. if (batch.seq_id) {
  15231. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  15232. free(batch.seq_id[i]);
  15233. }
  15234. free(batch.seq_id);
  15235. }
  15236. if (batch.logits) free(batch.logits);
  15237. }
  15238. int32_t llama_encode(
  15239. struct llama_context * ctx,
  15240. struct llama_batch batch) {
  15241. const int ret = llama_encode_internal(*ctx, batch);
  15242. if (ret < 0) {
  15243. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  15244. }
  15245. return ret;
  15246. }
  15247. int32_t llama_decode(
  15248. struct llama_context * ctx,
  15249. struct llama_batch batch) {
  15250. const int ret = llama_decode_internal(*ctx, batch);
  15251. if (ret < 0) {
  15252. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  15253. }
  15254. return ret;
  15255. }
  15256. void llama_synchronize(struct llama_context * ctx) {
  15257. ggml_backend_sched_synchronize(ctx->sched);
  15258. // FIXME: if multiple single tokens are evaluated without a synchronization,
  15259. // the stats will be added to the prompt evaluation stats
  15260. // this should only happen when using batch size 1 to evaluate a batch
  15261. // add the evaluation to the stats
  15262. if (ctx->n_queued_tokens == 1) {
  15263. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15264. ctx->n_eval++;
  15265. } else if (ctx->n_queued_tokens > 1) {
  15266. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15267. ctx->n_p_eval += ctx->n_queued_tokens;
  15268. }
  15269. // get a more accurate load time, upon first eval
  15270. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  15271. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  15272. ctx->has_evaluated_once = true;
  15273. }
  15274. ctx->n_queued_tokens = 0;
  15275. ctx->t_compute_start_us = 0;
  15276. }
  15277. float * llama_get_logits(struct llama_context * ctx) {
  15278. llama_synchronize(ctx);
  15279. return ctx->logits;
  15280. }
  15281. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  15282. int32_t j = -1;
  15283. llama_synchronize(ctx);
  15284. try {
  15285. if (ctx->logits == nullptr) {
  15286. throw std::runtime_error("no logits");
  15287. }
  15288. if (i < 0) {
  15289. j = ctx->n_outputs + i;
  15290. if (j < 0) {
  15291. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15292. }
  15293. } else if ((size_t) i >= ctx->output_ids.size()) {
  15294. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15295. } else {
  15296. j = ctx->output_ids[i];
  15297. }
  15298. if (j < 0) {
  15299. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15300. }
  15301. if (j >= ctx->n_outputs) {
  15302. // This should not happen
  15303. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15304. }
  15305. return ctx->logits + j*ctx->model.hparams.n_vocab;
  15306. } catch (const std::exception & err) {
  15307. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  15308. #ifndef NDEBUG
  15309. GGML_ABORT("fatal error");
  15310. #endif
  15311. return nullptr;
  15312. }
  15313. }
  15314. float * llama_get_embeddings(struct llama_context * ctx) {
  15315. llama_synchronize(ctx);
  15316. return ctx->embd;
  15317. }
  15318. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  15319. int32_t j = -1;
  15320. llama_synchronize(ctx);
  15321. try {
  15322. if (ctx->embd == nullptr) {
  15323. throw std::runtime_error("no embeddings");
  15324. }
  15325. if (i < 0) {
  15326. j = ctx->n_outputs + i;
  15327. if (j < 0) {
  15328. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15329. }
  15330. } else if ((size_t) i >= ctx->output_ids.size()) {
  15331. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15332. } else {
  15333. j = ctx->output_ids[i];
  15334. }
  15335. if (j < 0) {
  15336. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15337. }
  15338. if (j >= ctx->n_outputs) {
  15339. // This should not happen
  15340. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15341. }
  15342. return ctx->embd + j*ctx->model.hparams.n_embd;
  15343. } catch (const std::exception & err) {
  15344. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  15345. #ifndef NDEBUG
  15346. GGML_ABORT("fatal error");
  15347. #endif
  15348. return nullptr;
  15349. }
  15350. }
  15351. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  15352. llama_synchronize(ctx);
  15353. auto it = ctx->embd_seq.find(seq_id);
  15354. if (it == ctx->embd_seq.end()) {
  15355. return nullptr;
  15356. }
  15357. return it->second.data();
  15358. }
  15359. //
  15360. // vocab
  15361. //
  15362. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  15363. return llama_token_get_text_impl(model->vocab, token);
  15364. }
  15365. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  15366. return llama_token_get_score_impl(model->vocab, token);
  15367. }
  15368. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  15369. return llama_token_get_attr_impl(model->vocab, token);
  15370. }
  15371. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  15372. return llama_token_is_eog_impl(model->vocab, token);
  15373. }
  15374. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  15375. return llama_token_is_control_impl(model->vocab, token);
  15376. }
  15377. llama_token llama_token_bos(const struct llama_model * model) {
  15378. return llama_token_bos_impl(model->vocab);
  15379. }
  15380. llama_token llama_token_eos(const struct llama_model * model) {
  15381. return llama_token_eos_impl(model->vocab);
  15382. }
  15383. llama_token llama_token_cls(const struct llama_model * model) {
  15384. return llama_token_cls_impl(model->vocab);
  15385. }
  15386. llama_token llama_token_sep(const struct llama_model * model) {
  15387. return llama_token_sep_impl(model->vocab);
  15388. }
  15389. llama_token llama_token_nl (const struct llama_model * model) {
  15390. return llama_token_nl_impl(model->vocab);
  15391. }
  15392. llama_token llama_token_pad(const struct llama_model * model) {
  15393. return llama_token_pad_impl(model->vocab);
  15394. }
  15395. int32_t llama_add_bos_token(const struct llama_model * model) {
  15396. return llama_add_bos_token_impl(model->vocab);
  15397. }
  15398. int32_t llama_add_eos_token(const struct llama_model * model) {
  15399. return llama_add_eos_token_impl(model->vocab);
  15400. }
  15401. llama_token llama_token_prefix(const struct llama_model * model) {
  15402. return llama_token_prefix_impl(model->vocab);
  15403. }
  15404. llama_token llama_token_middle(const struct llama_model * model) {
  15405. return llama_token_middle_impl(model->vocab);
  15406. }
  15407. llama_token llama_token_suffix(const struct llama_model * model) {
  15408. return llama_token_suffix_impl(model->vocab);
  15409. }
  15410. llama_token llama_token_eot(const struct llama_model * model) {
  15411. return llama_token_eot_impl(model->vocab);
  15412. }
  15413. //
  15414. // tokenization
  15415. //
  15416. int32_t llama_tokenize(
  15417. const struct llama_model * model,
  15418. const char * text,
  15419. int32_t text_len,
  15420. llama_token * tokens,
  15421. int32_t n_tokens_max,
  15422. bool add_special,
  15423. bool parse_special) {
  15424. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  15425. }
  15426. int32_t llama_token_to_piece(
  15427. const struct llama_model * model,
  15428. llama_token token,
  15429. char * buf,
  15430. int32_t length,
  15431. int32_t lstrip,
  15432. bool special) {
  15433. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  15434. }
  15435. int32_t llama_detokenize(
  15436. const struct llama_model * model,
  15437. const llama_token * tokens,
  15438. int32_t n_tokens,
  15439. char * text,
  15440. int32_t text_len_max,
  15441. bool remove_special,
  15442. bool unparse_special) {
  15443. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  15444. }
  15445. //
  15446. // chat templates
  15447. //
  15448. // Simple version of "llama_apply_chat_template" that only works with strings
  15449. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  15450. static int32_t llama_chat_apply_template_internal(
  15451. const std::string & tmpl,
  15452. const std::vector<const llama_chat_message *> & chat,
  15453. std::string & dest, bool add_ass) {
  15454. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  15455. std::stringstream ss;
  15456. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  15457. return tmpl.find(haystack) != std::string::npos;
  15458. };
  15459. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  15460. // chatml template
  15461. for (auto message : chat) {
  15462. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  15463. }
  15464. if (add_ass) {
  15465. ss << "<|im_start|>assistant\n";
  15466. }
  15467. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  15468. // llama2 template and its variants
  15469. // [variant] support system message
  15470. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  15471. // [variant] space before + after response
  15472. bool space_around_response = tmpl_contains("' ' + eos_token");
  15473. // [variant] add BOS inside history
  15474. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  15475. // [variant] trim spaces from the input message
  15476. bool strip_message = tmpl_contains("content.strip()");
  15477. // construct the prompt
  15478. bool is_inside_turn = true; // skip BOS at the beginning
  15479. ss << "[INST] ";
  15480. for (auto message : chat) {
  15481. std::string content = strip_message ? trim(message->content) : message->content;
  15482. std::string role(message->role);
  15483. if (!is_inside_turn) {
  15484. is_inside_turn = true;
  15485. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  15486. }
  15487. if (role == "system") {
  15488. if (support_system_message) {
  15489. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  15490. } else {
  15491. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  15492. ss << content << "\n";
  15493. }
  15494. } else if (role == "user") {
  15495. ss << content << " [/INST]";
  15496. } else {
  15497. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  15498. is_inside_turn = false;
  15499. }
  15500. }
  15501. // llama2 templates seem to not care about "add_generation_prompt"
  15502. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  15503. // Phi 3
  15504. for (auto message : chat) {
  15505. std::string role(message->role);
  15506. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  15507. }
  15508. if (add_ass) {
  15509. ss << "<|assistant|>\n";
  15510. }
  15511. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  15512. // zephyr template
  15513. for (auto message : chat) {
  15514. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  15515. }
  15516. if (add_ass) {
  15517. ss << "<|assistant|>\n";
  15518. }
  15519. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  15520. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  15521. for (auto message : chat) {
  15522. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  15523. ss << bos << message->role << "\n" << message->content << "</s>\n";
  15524. }
  15525. if (add_ass) {
  15526. ss << "<s>assistant\n";
  15527. }
  15528. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  15529. // google/gemma-7b-it
  15530. std::string system_prompt = "";
  15531. for (auto message : chat) {
  15532. std::string role(message->role);
  15533. if (role == "system") {
  15534. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  15535. system_prompt = trim(message->content);
  15536. continue;
  15537. }
  15538. // in gemma, "assistant" is "model"
  15539. role = role == "assistant" ? "model" : message->role;
  15540. ss << "<start_of_turn>" << role << "\n";
  15541. if (!system_prompt.empty() && role != "model") {
  15542. ss << system_prompt << "\n\n";
  15543. system_prompt = "";
  15544. }
  15545. ss << trim(message->content) << "<end_of_turn>\n";
  15546. }
  15547. if (add_ass) {
  15548. ss << "<start_of_turn>model\n";
  15549. }
  15550. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  15551. // OrionStarAI/Orion-14B-Chat
  15552. std::string system_prompt = "";
  15553. for (auto message : chat) {
  15554. std::string role(message->role);
  15555. if (role == "system") {
  15556. // there is no system message support, we will merge it with user prompt
  15557. system_prompt = message->content;
  15558. continue;
  15559. } else if (role == "user") {
  15560. ss << "Human: ";
  15561. if (!system_prompt.empty()) {
  15562. ss << system_prompt << "\n\n";
  15563. system_prompt = "";
  15564. }
  15565. ss << message->content << "\n\nAssistant: </s>";
  15566. } else {
  15567. ss << message->content << "</s>";
  15568. }
  15569. }
  15570. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  15571. // openchat/openchat-3.5-0106,
  15572. for (auto message : chat) {
  15573. std::string role(message->role);
  15574. if (role == "system") {
  15575. ss << message->content << "<|end_of_turn|>";
  15576. } else {
  15577. role[0] = toupper(role[0]);
  15578. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  15579. }
  15580. }
  15581. if (add_ass) {
  15582. ss << "GPT4 Correct Assistant:";
  15583. }
  15584. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  15585. // eachadea/vicuna-13b-1.1 (and Orca variant)
  15586. for (auto message : chat) {
  15587. std::string role(message->role);
  15588. if (role == "system") {
  15589. // Orca-Vicuna variant uses a system prefix
  15590. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  15591. ss << "SYSTEM: " << message->content << "\n";
  15592. } else {
  15593. ss << message->content << "\n\n";
  15594. }
  15595. } else if (role == "user") {
  15596. ss << "USER: " << message->content << "\n";
  15597. } else if (role == "assistant") {
  15598. ss << "ASSISTANT: " << message->content << "</s>\n";
  15599. }
  15600. }
  15601. if (add_ass) {
  15602. ss << "ASSISTANT:";
  15603. }
  15604. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  15605. // deepseek-ai/deepseek-coder-33b-instruct
  15606. for (auto message : chat) {
  15607. std::string role(message->role);
  15608. if (role == "system") {
  15609. ss << message->content;
  15610. } else if (role == "user") {
  15611. ss << "### Instruction:\n" << message->content << "\n";
  15612. } else if (role == "assistant") {
  15613. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  15614. }
  15615. }
  15616. if (add_ass) {
  15617. ss << "### Response:\n";
  15618. }
  15619. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  15620. // CohereForAI/c4ai-command-r-plus
  15621. for (auto message : chat) {
  15622. std::string role(message->role);
  15623. if (role == "system") {
  15624. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15625. } else if (role == "user") {
  15626. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15627. } else if (role == "assistant") {
  15628. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15629. }
  15630. }
  15631. if (add_ass) {
  15632. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  15633. }
  15634. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  15635. // Llama 3
  15636. for (auto message : chat) {
  15637. std::string role(message->role);
  15638. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  15639. }
  15640. if (add_ass) {
  15641. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  15642. }
  15643. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  15644. // chatglm3-6b
  15645. ss << "[gMASK]" << "sop";
  15646. for (auto message : chat) {
  15647. std::string role(message->role);
  15648. ss << "<|" << role << "|>" << "\n " << message->content;
  15649. }
  15650. if (add_ass) {
  15651. ss << "<|assistant|>";
  15652. }
  15653. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  15654. ss << "[gMASK]" << "<sop>";
  15655. for (auto message : chat) {
  15656. std::string role(message->role);
  15657. ss << "<|" << role << "|>" << "\n" << message->content;
  15658. }
  15659. if (add_ass) {
  15660. ss << "<|assistant|>";
  15661. }
  15662. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  15663. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  15664. for (auto message : chat) {
  15665. std::string role(message->role);
  15666. if (role == "user") {
  15667. ss << LU8("<用户>");
  15668. ss << trim(message->content);
  15669. ss << "<AI>";
  15670. } else {
  15671. ss << trim(message->content);
  15672. }
  15673. }
  15674. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  15675. // DeepSeek-V2
  15676. for (auto message : chat) {
  15677. std::string role(message->role);
  15678. if (role == "system") {
  15679. ss << message->content << "\n\n";
  15680. } else if (role == "user") {
  15681. ss << "User: " << message->content << "\n\n";
  15682. } else if (role == "assistant") {
  15683. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  15684. }
  15685. }
  15686. if (add_ass) {
  15687. ss << "Assistant:";
  15688. }
  15689. } else {
  15690. // template not supported
  15691. return -1;
  15692. }
  15693. dest = ss.str();
  15694. return dest.size();
  15695. }
  15696. int32_t llama_chat_apply_template(
  15697. const struct llama_model * model,
  15698. const char * tmpl,
  15699. const struct llama_chat_message * chat,
  15700. size_t n_msg,
  15701. bool add_ass,
  15702. char * buf,
  15703. int32_t length) {
  15704. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  15705. if (tmpl == nullptr) {
  15706. GGML_ASSERT(model != nullptr);
  15707. // load template from model
  15708. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  15709. std::string template_key = "tokenizer.chat_template";
  15710. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  15711. if (res < 0) {
  15712. // worst case: there is no information about template, we will use chatml by default
  15713. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  15714. } else {
  15715. curr_tmpl = std::string(model_template.data(), model_template.size());
  15716. }
  15717. }
  15718. // format the chat to string
  15719. std::vector<const llama_chat_message *> chat_vec;
  15720. chat_vec.resize(n_msg);
  15721. for (size_t i = 0; i < n_msg; i++) {
  15722. chat_vec[i] = &chat[i];
  15723. }
  15724. std::string formatted_chat;
  15725. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  15726. if (res < 0) {
  15727. return res;
  15728. }
  15729. if (buf && length > 0) {
  15730. strncpy(buf, formatted_chat.c_str(), length);
  15731. }
  15732. return res;
  15733. }
  15734. //
  15735. // grammar
  15736. //
  15737. struct llama_grammar * llama_grammar_init(
  15738. const llama_grammar_element ** rules,
  15739. size_t n_rules,
  15740. size_t start_rule_index) {
  15741. return llama_grammar_init_impl(rules, n_rules, start_rule_index);
  15742. }
  15743. void llama_grammar_free(struct llama_grammar * grammar) {
  15744. llama_grammar_free_impl(grammar);
  15745. }
  15746. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  15747. return llama_grammar_copy_impl(grammar);
  15748. }
  15749. void llama_grammar_sample(
  15750. const struct llama_grammar * grammar,
  15751. const struct llama_context * ctx,
  15752. llama_token_data_array * candidates) {
  15753. llama_grammar_sample_impl(grammar, &ctx->model.vocab, &ctx->sampling, candidates);
  15754. }
  15755. void llama_sample_grammar(
  15756. struct llama_context * ctx,
  15757. llama_token_data_array * candidates,
  15758. const struct llama_grammar * grammar) {
  15759. llama_grammar_sample(grammar, ctx, candidates);
  15760. }
  15761. void llama_grammar_accept_token(
  15762. struct llama_grammar * grammar,
  15763. struct llama_context * ctx,
  15764. llama_token token) {
  15765. llama_grammar_accept_token_impl(grammar, &ctx->model.vocab, &ctx->sampling, token);
  15766. }
  15767. //
  15768. // sampling
  15769. //
  15770. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  15771. llama_set_rng_seed_impl(&ctx->sampling, seed);
  15772. }
  15773. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  15774. llama_sample_softmax_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15775. }
  15776. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  15777. llama_sample_top_k_impl(ctx ? &ctx->sampling : nullptr, candidates, k, min_keep);
  15778. }
  15779. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15780. llama_sample_top_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15781. }
  15782. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15783. llama_sample_min_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15784. }
  15785. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  15786. llama_sample_tail_free_impl(ctx ? &ctx->sampling : nullptr, candidates, z, min_keep);
  15787. }
  15788. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15789. llama_sample_typical_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15790. }
  15791. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  15792. llama_sample_entropy_impl(ctx ? &ctx->sampling : nullptr, candidates_p, min_temp, max_temp, exponent_val);
  15793. }
  15794. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  15795. llama_sample_temp_impl(ctx ? &ctx->sampling : nullptr, candidates_p, temp);
  15796. }
  15797. void llama_sample_repetition_penalties(
  15798. struct llama_context * ctx,
  15799. llama_token_data_array * candidates,
  15800. const llama_token * last_tokens,
  15801. size_t penalty_last_n,
  15802. float penalty_repeat,
  15803. float penalty_freq,
  15804. float penalty_present) {
  15805. llama_sample_repetition_penalties_impl(ctx ? &ctx->sampling : nullptr, candidates, last_tokens, penalty_last_n, penalty_repeat, penalty_freq, penalty_present);
  15806. }
  15807. void llama_sample_apply_guidance(
  15808. struct llama_context * ctx,
  15809. float * logits,
  15810. float * logits_guidance,
  15811. float scale) {
  15812. llama_sample_apply_guidance_impl(&ctx->sampling, logits, logits_guidance, scale);
  15813. }
  15814. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  15815. return llama_sample_token_mirostat_impl(&ctx->sampling, candidates, tau, eta, m, mu);
  15816. }
  15817. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  15818. return llama_sample_token_mirostat_v2_impl(ctx ? &ctx->sampling : nullptr, candidates, tau, eta, mu);
  15819. }
  15820. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  15821. return llama_sample_token_greedy_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15822. }
  15823. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  15824. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, rng);
  15825. }
  15826. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  15827. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, ctx->sampling.rng);
  15828. }
  15829. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  15830. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  15831. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  15832. return strlen(split_path);
  15833. }
  15834. return 0;
  15835. }
  15836. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  15837. std::string str_split_path(split_path);
  15838. char postfix[32];
  15839. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  15840. std::string str_postfix(postfix);
  15841. // check if dest ends with postfix
  15842. int size_prefix = str_split_path.size() - str_postfix.size();
  15843. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  15844. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  15845. return size_prefix;
  15846. }
  15847. return 0;
  15848. }
  15849. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  15850. struct llama_timings result = {
  15851. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  15852. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  15853. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  15854. /*.t_sample_ms =*/ 1e-3 * ctx->sampling.t_sample_us,
  15855. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  15856. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  15857. /*.n_sample =*/ std::max(1, ctx->sampling.n_sample),
  15858. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  15859. /*.n_eval =*/ std::max(1, ctx->n_eval),
  15860. };
  15861. return result;
  15862. }
  15863. void llama_print_timings(struct llama_context * ctx) {
  15864. const llama_timings timings = llama_get_timings(ctx);
  15865. LLAMA_LOG_INFO("\n");
  15866. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  15867. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15868. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  15869. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  15870. __func__, timings.t_p_eval_ms, timings.n_p_eval, timings.t_p_eval_ms / timings.n_p_eval, 1e3 / timings.t_p_eval_ms * timings.n_p_eval);
  15871. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15872. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  15873. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  15874. }
  15875. void llama_reset_timings(struct llama_context * ctx) {
  15876. ctx->t_start_us = ggml_time_us();
  15877. ctx->t_eval_us = ctx->n_eval = 0;
  15878. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  15879. ctx->sampling.reset_timings();
  15880. }
  15881. const char * llama_print_system_info(void) {
  15882. static std::string s;
  15883. s = "";
  15884. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  15885. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  15886. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  15887. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  15888. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  15889. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  15890. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  15891. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  15892. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  15893. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  15894. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  15895. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  15896. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  15897. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  15898. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  15899. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  15900. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  15901. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  15902. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  15903. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  15904. return s.c_str();
  15905. }
  15906. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  15907. fprintf(stream, "\n");
  15908. fprintf(stream, "###########\n");
  15909. fprintf(stream, "# Timings #\n");
  15910. fprintf(stream, "###########\n");
  15911. fprintf(stream, "\n");
  15912. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  15913. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  15914. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  15915. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  15916. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  15917. 1.0e-3 * ctx->sampling.t_sample_us / ctx->sampling.n_sample);
  15918. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  15919. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  15920. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->sampling.n_sample);
  15921. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  15922. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  15923. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  15924. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->sampling.t_sample_us);
  15925. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  15926. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  15927. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  15928. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  15929. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  15930. 1.0e6 * ctx->sampling.n_sample / ctx->sampling.t_sample_us);
  15931. }
  15932. // For internal test use
  15933. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  15934. struct llama_context * ctx
  15935. ) {
  15936. return ctx->model.tensors_by_name;
  15937. }
  15938. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  15939. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  15940. g_state.log_callback_user_data = user_data;
  15941. #ifdef GGML_USE_METAL
  15942. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15943. #elif defined(GGML_USE_CUDA)
  15944. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15945. #elif defined(GGML_USE_CANN)
  15946. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15947. #endif
  15948. }
  15949. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  15950. va_list args_copy;
  15951. va_copy(args_copy, args);
  15952. char buffer[128];
  15953. int len = vsnprintf(buffer, 128, format, args);
  15954. if (len < 128) {
  15955. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  15956. } else {
  15957. char* buffer2 = new char[len+1];
  15958. vsnprintf(buffer2, len+1, format, args_copy);
  15959. buffer2[len] = 0;
  15960. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  15961. delete[] buffer2;
  15962. }
  15963. va_end(args_copy);
  15964. }
  15965. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  15966. va_list args;
  15967. va_start(args, format);
  15968. llama_log_internal_v(level, format, args);
  15969. va_end(args);
  15970. }
  15971. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  15972. (void) level;
  15973. (void) user_data;
  15974. fputs(text, stderr);
  15975. fflush(stderr);
  15976. }