llama.cpp 790 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199
  1. /**
  2. * llama.cpp - commit 1e6f6554aa11fa10160a5fda689e736c3c34169f - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-impl.h"
  27. #include "llama-vocab.h"
  28. #include "llama-grammar.h"
  29. #include "llama-sampling.h"
  30. #include "unicode.h"
  31. #include "ggml.h"
  32. #include "ggml-alloc.h"
  33. #include "ggml-backend.h"
  34. #ifdef GGML_USE_RPC
  35. # include "ggml-rpc.h"
  36. #endif
  37. #ifdef GGML_USE_CUDA
  38. # include "ggml-cuda.h"
  39. #elif defined(GGML_USE_VULKAN)
  40. # include "ggml-vulkan.h"
  41. #elif defined(GGML_USE_SYCL)
  42. # include "ggml-sycl.h"
  43. #elif defined(GGML_USE_KOMPUTE)
  44. # include "ggml-kompute.h"
  45. #elif defined(GGML_USE_CANN)
  46. # include "ggml-cann.h"
  47. #endif
  48. #ifdef GGML_USE_BLAS
  49. # include "ggml-blas.h"
  50. #endif
  51. #ifdef GGML_USE_METAL
  52. # include "ggml-metal.h"
  53. #endif
  54. // TODO: replace with ggml API call
  55. #define QK_K 256
  56. #ifdef __has_include
  57. #if __has_include(<unistd.h>)
  58. #include <unistd.h>
  59. #if defined(_POSIX_MAPPED_FILES)
  60. #include <sys/mman.h>
  61. #include <fcntl.h>
  62. #endif
  63. #if defined(_POSIX_MEMLOCK_RANGE)
  64. #include <sys/resource.h>
  65. #endif
  66. #endif
  67. #endif
  68. #if defined(_WIN32)
  69. #define WIN32_LEAN_AND_MEAN
  70. #ifndef NOMINMAX
  71. #define NOMINMAX
  72. #endif
  73. #include <windows.h>
  74. #ifndef PATH_MAX
  75. #define PATH_MAX MAX_PATH
  76. #endif
  77. #include <io.h>
  78. #endif
  79. #if __cplusplus >= 202000L
  80. #define LU8(x) (const char*)(u8##x)
  81. #else
  82. #define LU8(x) u8##x
  83. #endif
  84. #include <algorithm>
  85. #include <array>
  86. #include <cassert>
  87. #include <cctype>
  88. #include <cfloat>
  89. #include <cinttypes>
  90. #include <climits>
  91. #include <cmath>
  92. #include <cstdarg>
  93. #include <cstddef>
  94. #include <cstdint>
  95. #include <cstdio>
  96. #include <cstring>
  97. #include <ctime>
  98. #include <fstream>
  99. #include <functional>
  100. #include <future>
  101. #include <initializer_list>
  102. #include <locale>
  103. #include <map>
  104. #include <memory>
  105. #include <mutex>
  106. #include <numeric>
  107. #include <set>
  108. #include <sstream>
  109. #include <thread>
  110. #include <type_traits>
  111. #include <unordered_map>
  112. #if defined(_MSC_VER)
  113. #pragma warning(disable: 4244 4267) // possible loss of data
  114. #endif
  115. // bump if necessary
  116. #define LLAMA_MAX_LAYERS 512
  117. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  118. //
  119. // helpers
  120. //
  121. // trim whitespace from the beginning and end of a string
  122. static std::string trim(const std::string & str) {
  123. size_t start = 0;
  124. size_t end = str.size();
  125. while (start < end && isspace(str[start])) {
  126. start += 1;
  127. }
  128. while (end > start && isspace(str[end - 1])) {
  129. end -= 1;
  130. }
  131. return str.substr(start, end - start);
  132. }
  133. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  134. if (search.empty()) {
  135. return; // Avoid infinite loop if 'search' is an empty string
  136. }
  137. size_t pos = 0;
  138. while ((pos = s.find(search, pos)) != std::string::npos) {
  139. s.replace(pos, search.length(), replace);
  140. pos += replace.length();
  141. }
  142. }
  143. static bool is_float_close(float a, float b, float abs_tol) {
  144. // Check for non-negative tolerance
  145. if (abs_tol < 0.0) {
  146. throw std::invalid_argument("Tolerance must be non-negative");
  147. }
  148. // Exact equality check
  149. if (a == b) {
  150. return true;
  151. }
  152. // Check for infinities
  153. if (std::isinf(a) || std::isinf(b)) {
  154. return false;
  155. }
  156. // Regular comparison using the provided absolute tolerance
  157. return std::fabs(b - a) <= abs_tol;
  158. }
  159. static void zeros(std::ofstream & file, size_t n) {
  160. char zero = 0;
  161. for (size_t i = 0; i < n; ++i) {
  162. file.write(&zero, 1);
  163. }
  164. }
  165. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  166. static std::string format(const char * fmt, ...) {
  167. va_list ap;
  168. va_list ap2;
  169. va_start(ap, fmt);
  170. va_copy(ap2, ap);
  171. int size = vsnprintf(NULL, 0, fmt, ap);
  172. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  173. std::vector<char> buf(size + 1);
  174. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  175. GGML_ASSERT(size2 == size);
  176. va_end(ap2);
  177. va_end(ap);
  178. return std::string(buf.data(), size);
  179. }
  180. //
  181. // gguf constants (sync with gguf.py)
  182. //
  183. enum llm_arch {
  184. LLM_ARCH_LLAMA,
  185. LLM_ARCH_FALCON,
  186. LLM_ARCH_BAICHUAN,
  187. LLM_ARCH_GROK,
  188. LLM_ARCH_GPT2,
  189. LLM_ARCH_GPTJ,
  190. LLM_ARCH_GPTNEOX,
  191. LLM_ARCH_MPT,
  192. LLM_ARCH_STARCODER,
  193. LLM_ARCH_REFACT,
  194. LLM_ARCH_BERT,
  195. LLM_ARCH_NOMIC_BERT,
  196. LLM_ARCH_JINA_BERT_V2,
  197. LLM_ARCH_BLOOM,
  198. LLM_ARCH_STABLELM,
  199. LLM_ARCH_QWEN,
  200. LLM_ARCH_QWEN2,
  201. LLM_ARCH_QWEN2MOE,
  202. LLM_ARCH_PHI2,
  203. LLM_ARCH_PHI3,
  204. LLM_ARCH_PLAMO,
  205. LLM_ARCH_CODESHELL,
  206. LLM_ARCH_ORION,
  207. LLM_ARCH_INTERNLM2,
  208. LLM_ARCH_MINICPM,
  209. LLM_ARCH_GEMMA,
  210. LLM_ARCH_GEMMA2,
  211. LLM_ARCH_STARCODER2,
  212. LLM_ARCH_MAMBA,
  213. LLM_ARCH_XVERSE,
  214. LLM_ARCH_COMMAND_R,
  215. LLM_ARCH_DBRX,
  216. LLM_ARCH_OLMO,
  217. LLM_ARCH_OPENELM,
  218. LLM_ARCH_ARCTIC,
  219. LLM_ARCH_DEEPSEEK2,
  220. LLM_ARCH_CHATGLM,
  221. LLM_ARCH_BITNET,
  222. LLM_ARCH_T5,
  223. LLM_ARCH_JAIS,
  224. LLM_ARCH_UNKNOWN,
  225. };
  226. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  227. { LLM_ARCH_LLAMA, "llama" },
  228. { LLM_ARCH_FALCON, "falcon" },
  229. { LLM_ARCH_GROK, "grok" },
  230. { LLM_ARCH_GPT2, "gpt2" },
  231. { LLM_ARCH_GPTJ, "gptj" },
  232. { LLM_ARCH_GPTNEOX, "gptneox" },
  233. { LLM_ARCH_MPT, "mpt" },
  234. { LLM_ARCH_BAICHUAN, "baichuan" },
  235. { LLM_ARCH_STARCODER, "starcoder" },
  236. { LLM_ARCH_REFACT, "refact" },
  237. { LLM_ARCH_BERT, "bert" },
  238. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  239. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  240. { LLM_ARCH_BLOOM, "bloom" },
  241. { LLM_ARCH_STABLELM, "stablelm" },
  242. { LLM_ARCH_QWEN, "qwen" },
  243. { LLM_ARCH_QWEN2, "qwen2" },
  244. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  245. { LLM_ARCH_PHI2, "phi2" },
  246. { LLM_ARCH_PHI3, "phi3" },
  247. { LLM_ARCH_PLAMO, "plamo" },
  248. { LLM_ARCH_CODESHELL, "codeshell" },
  249. { LLM_ARCH_ORION, "orion" },
  250. { LLM_ARCH_INTERNLM2, "internlm2" },
  251. { LLM_ARCH_MINICPM, "minicpm" },
  252. { LLM_ARCH_GEMMA, "gemma" },
  253. { LLM_ARCH_GEMMA2, "gemma2" },
  254. { LLM_ARCH_STARCODER2, "starcoder2" },
  255. { LLM_ARCH_MAMBA, "mamba" },
  256. { LLM_ARCH_XVERSE, "xverse" },
  257. { LLM_ARCH_COMMAND_R, "command-r" },
  258. { LLM_ARCH_DBRX, "dbrx" },
  259. { LLM_ARCH_OLMO, "olmo" },
  260. { LLM_ARCH_OPENELM, "openelm" },
  261. { LLM_ARCH_ARCTIC, "arctic" },
  262. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  263. { LLM_ARCH_CHATGLM, "chatglm" },
  264. { LLM_ARCH_BITNET, "bitnet" },
  265. { LLM_ARCH_T5, "t5" },
  266. { LLM_ARCH_JAIS, "jais" },
  267. { LLM_ARCH_UNKNOWN, "(unknown)" },
  268. };
  269. enum llm_kv {
  270. LLM_KV_GENERAL_TYPE,
  271. LLM_KV_GENERAL_ARCHITECTURE,
  272. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  273. LLM_KV_GENERAL_ALIGNMENT,
  274. LLM_KV_GENERAL_NAME,
  275. LLM_KV_GENERAL_AUTHOR,
  276. LLM_KV_GENERAL_VERSION,
  277. LLM_KV_GENERAL_URL,
  278. LLM_KV_GENERAL_DESCRIPTION,
  279. LLM_KV_GENERAL_LICENSE,
  280. LLM_KV_GENERAL_SOURCE_URL,
  281. LLM_KV_GENERAL_SOURCE_HF_REPO,
  282. LLM_KV_VOCAB_SIZE,
  283. LLM_KV_CONTEXT_LENGTH,
  284. LLM_KV_EMBEDDING_LENGTH,
  285. LLM_KV_BLOCK_COUNT,
  286. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  287. LLM_KV_FEED_FORWARD_LENGTH,
  288. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  289. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  290. LLM_KV_USE_PARALLEL_RESIDUAL,
  291. LLM_KV_TENSOR_DATA_LAYOUT,
  292. LLM_KV_EXPERT_COUNT,
  293. LLM_KV_EXPERT_USED_COUNT,
  294. LLM_KV_EXPERT_SHARED_COUNT,
  295. LLM_KV_EXPERT_WEIGHTS_SCALE,
  296. LLM_KV_POOLING_TYPE,
  297. LLM_KV_LOGIT_SCALE,
  298. LLM_KV_DECODER_START_TOKEN_ID,
  299. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  300. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  301. LLM_KV_ATTENTION_HEAD_COUNT,
  302. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  303. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  304. LLM_KV_ATTENTION_CLAMP_KQV,
  305. LLM_KV_ATTENTION_KEY_LENGTH,
  306. LLM_KV_ATTENTION_VALUE_LENGTH,
  307. LLM_KV_ATTENTION_LAYERNORM_EPS,
  308. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  309. LLM_KV_ATTENTION_CAUSAL,
  310. LLM_KV_ATTENTION_Q_LORA_RANK,
  311. LLM_KV_ATTENTION_KV_LORA_RANK,
  312. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  313. LLM_KV_ATTENTION_SLIDING_WINDOW,
  314. LLM_KV_ROPE_DIMENSION_COUNT,
  315. LLM_KV_ROPE_FREQ_BASE,
  316. LLM_KV_ROPE_SCALE_LINEAR,
  317. LLM_KV_ROPE_SCALING_TYPE,
  318. LLM_KV_ROPE_SCALING_FACTOR,
  319. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  320. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  321. LLM_KV_ROPE_SCALING_FINETUNED,
  322. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  323. LLM_KV_SPLIT_NO,
  324. LLM_KV_SPLIT_COUNT,
  325. LLM_KV_SPLIT_TENSORS_COUNT,
  326. LLM_KV_SSM_INNER_SIZE,
  327. LLM_KV_SSM_CONV_KERNEL,
  328. LLM_KV_SSM_STATE_SIZE,
  329. LLM_KV_SSM_TIME_STEP_RANK,
  330. LLM_KV_TOKENIZER_MODEL,
  331. LLM_KV_TOKENIZER_PRE,
  332. LLM_KV_TOKENIZER_LIST,
  333. LLM_KV_TOKENIZER_TOKEN_TYPE,
  334. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  335. LLM_KV_TOKENIZER_SCORES,
  336. LLM_KV_TOKENIZER_MERGES,
  337. LLM_KV_TOKENIZER_BOS_ID,
  338. LLM_KV_TOKENIZER_EOS_ID,
  339. LLM_KV_TOKENIZER_UNK_ID,
  340. LLM_KV_TOKENIZER_SEP_ID,
  341. LLM_KV_TOKENIZER_PAD_ID,
  342. LLM_KV_TOKENIZER_CLS_ID,
  343. LLM_KV_TOKENIZER_MASK_ID,
  344. LLM_KV_TOKENIZER_ADD_BOS,
  345. LLM_KV_TOKENIZER_ADD_EOS,
  346. LLM_KV_TOKENIZER_ADD_PREFIX,
  347. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  348. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  349. LLM_KV_TOKENIZER_HF_JSON,
  350. LLM_KV_TOKENIZER_RWKV,
  351. LLM_KV_TOKENIZER_PREFIX_ID,
  352. LLM_KV_TOKENIZER_SUFFIX_ID,
  353. LLM_KV_TOKENIZER_MIDDLE_ID,
  354. LLM_KV_TOKENIZER_EOT_ID,
  355. LLM_KV_TOKENIZER_EOM_ID,
  356. LLM_KV_ADAPTER_TYPE,
  357. LLM_KV_ADAPTER_LORA_ALPHA,
  358. };
  359. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  360. { LLM_KV_GENERAL_TYPE, "general.type" },
  361. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  362. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  363. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  364. { LLM_KV_GENERAL_NAME, "general.name" },
  365. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  366. { LLM_KV_GENERAL_VERSION, "general.version" },
  367. { LLM_KV_GENERAL_URL, "general.url" },
  368. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  369. { LLM_KV_GENERAL_LICENSE, "general.license" },
  370. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  371. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  372. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  373. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  374. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  375. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  376. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  377. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  378. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  379. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  380. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  381. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  382. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  383. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  384. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  385. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  386. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  387. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  388. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  389. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  390. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  391. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  392. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  393. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  394. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  395. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  396. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  397. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  398. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  399. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  400. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  401. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  402. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  403. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  404. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  405. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  406. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  407. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  408. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  409. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  410. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  411. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  412. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  413. { LLM_KV_SPLIT_NO, "split.no" },
  414. { LLM_KV_SPLIT_COUNT, "split.count" },
  415. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  416. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  417. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  418. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  419. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  420. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  421. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  422. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  423. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  424. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  425. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  426. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  427. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  428. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  429. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  430. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  431. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  432. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  433. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  434. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  435. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  436. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  437. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  438. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  439. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  440. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  441. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  442. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  443. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  444. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  445. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  446. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  447. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  448. };
  449. struct LLM_KV {
  450. LLM_KV(llm_arch arch) : arch(arch) {}
  451. llm_arch arch;
  452. std::string operator()(llm_kv kv) const {
  453. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  454. }
  455. };
  456. enum llm_tensor {
  457. LLM_TENSOR_TOKEN_EMBD,
  458. LLM_TENSOR_TOKEN_EMBD_NORM,
  459. LLM_TENSOR_TOKEN_TYPES,
  460. LLM_TENSOR_POS_EMBD,
  461. LLM_TENSOR_OUTPUT,
  462. LLM_TENSOR_OUTPUT_NORM,
  463. LLM_TENSOR_ROPE_FREQS,
  464. LLM_TENSOR_ROPE_FACTORS_LONG,
  465. LLM_TENSOR_ROPE_FACTORS_SHORT,
  466. LLM_TENSOR_ATTN_Q,
  467. LLM_TENSOR_ATTN_K,
  468. LLM_TENSOR_ATTN_V,
  469. LLM_TENSOR_ATTN_QKV,
  470. LLM_TENSOR_ATTN_OUT,
  471. LLM_TENSOR_ATTN_NORM,
  472. LLM_TENSOR_ATTN_NORM_2,
  473. LLM_TENSOR_ATTN_OUT_NORM,
  474. LLM_TENSOR_ATTN_POST_NORM,
  475. LLM_TENSOR_ATTN_ROT_EMBD,
  476. LLM_TENSOR_FFN_GATE_INP,
  477. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  478. LLM_TENSOR_FFN_NORM,
  479. LLM_TENSOR_FFN_POST_NORM,
  480. LLM_TENSOR_FFN_GATE,
  481. LLM_TENSOR_FFN_DOWN,
  482. LLM_TENSOR_FFN_UP,
  483. LLM_TENSOR_FFN_ACT,
  484. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  485. LLM_TENSOR_FFN_GATE_EXP,
  486. LLM_TENSOR_FFN_UP_EXP,
  487. LLM_TENSOR_FFN_NORM_EXPS,
  488. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  489. LLM_TENSOR_FFN_GATE_EXPS,
  490. LLM_TENSOR_FFN_UP_EXPS,
  491. LLM_TENSOR_FFN_DOWN_SHEXP,
  492. LLM_TENSOR_FFN_GATE_SHEXP,
  493. LLM_TENSOR_FFN_UP_SHEXP,
  494. LLM_TENSOR_ATTN_Q_NORM,
  495. LLM_TENSOR_ATTN_K_NORM,
  496. LLM_TENSOR_LAYER_OUT_NORM,
  497. LLM_TENSOR_SSM_IN,
  498. LLM_TENSOR_SSM_CONV1D,
  499. LLM_TENSOR_SSM_X,
  500. LLM_TENSOR_SSM_DT,
  501. LLM_TENSOR_SSM_A,
  502. LLM_TENSOR_SSM_D,
  503. LLM_TENSOR_SSM_OUT,
  504. LLM_TENSOR_ATTN_Q_A,
  505. LLM_TENSOR_ATTN_Q_B,
  506. LLM_TENSOR_ATTN_KV_A_MQA,
  507. LLM_TENSOR_ATTN_KV_B,
  508. LLM_TENSOR_ATTN_Q_A_NORM,
  509. LLM_TENSOR_ATTN_KV_A_NORM,
  510. LLM_TENSOR_ATTN_SUB_NORM,
  511. LLM_TENSOR_FFN_SUB_NORM,
  512. LLM_TENSOR_DEC_ATTN_NORM,
  513. LLM_TENSOR_DEC_ATTN_Q,
  514. LLM_TENSOR_DEC_ATTN_K,
  515. LLM_TENSOR_DEC_ATTN_V,
  516. LLM_TENSOR_DEC_ATTN_OUT,
  517. LLM_TENSOR_DEC_ATTN_REL_B,
  518. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  519. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  520. LLM_TENSOR_DEC_CROSS_ATTN_K,
  521. LLM_TENSOR_DEC_CROSS_ATTN_V,
  522. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  523. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  524. LLM_TENSOR_DEC_FFN_NORM,
  525. LLM_TENSOR_DEC_FFN_GATE,
  526. LLM_TENSOR_DEC_FFN_DOWN,
  527. LLM_TENSOR_DEC_FFN_UP,
  528. LLM_TENSOR_DEC_OUTPUT_NORM,
  529. LLM_TENSOR_ENC_ATTN_NORM,
  530. LLM_TENSOR_ENC_ATTN_Q,
  531. LLM_TENSOR_ENC_ATTN_K,
  532. LLM_TENSOR_ENC_ATTN_V,
  533. LLM_TENSOR_ENC_ATTN_OUT,
  534. LLM_TENSOR_ENC_ATTN_REL_B,
  535. LLM_TENSOR_ENC_FFN_NORM,
  536. LLM_TENSOR_ENC_FFN_GATE,
  537. LLM_TENSOR_ENC_FFN_DOWN,
  538. LLM_TENSOR_ENC_FFN_UP,
  539. LLM_TENSOR_ENC_OUTPUT_NORM,
  540. };
  541. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  542. {
  543. LLM_ARCH_LLAMA,
  544. {
  545. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  546. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  547. { LLM_TENSOR_OUTPUT, "output" },
  548. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  549. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  550. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  551. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  552. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  553. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  554. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  555. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  556. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  557. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  558. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  559. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  560. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  561. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  562. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  563. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  564. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  565. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  566. },
  567. },
  568. {
  569. LLM_ARCH_BAICHUAN,
  570. {
  571. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  572. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  573. { LLM_TENSOR_OUTPUT, "output" },
  574. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  575. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  576. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  577. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  578. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  579. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  580. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  581. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  582. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  583. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  584. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  585. },
  586. },
  587. {
  588. LLM_ARCH_FALCON,
  589. {
  590. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  591. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  592. { LLM_TENSOR_OUTPUT, "output" },
  593. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  594. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  595. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  596. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  597. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  598. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  599. },
  600. },
  601. {
  602. LLM_ARCH_GROK,
  603. {
  604. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  605. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  606. { LLM_TENSOR_OUTPUT, "output" },
  607. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  608. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  609. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  610. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  611. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  612. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  613. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  614. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  615. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  616. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  617. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  618. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  619. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  620. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  621. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  622. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  623. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  624. },
  625. },
  626. {
  627. LLM_ARCH_GPT2,
  628. {
  629. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  630. { LLM_TENSOR_POS_EMBD, "position_embd" },
  631. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  632. { LLM_TENSOR_OUTPUT, "output" },
  633. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  634. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  635. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  636. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  637. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  638. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  639. },
  640. },
  641. {
  642. LLM_ARCH_GPTJ,
  643. {
  644. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  645. },
  646. },
  647. {
  648. LLM_ARCH_GPTNEOX,
  649. {
  650. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  651. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  652. { LLM_TENSOR_OUTPUT, "output" },
  653. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  654. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  655. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  656. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  657. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  658. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  659. },
  660. },
  661. {
  662. LLM_ARCH_MPT,
  663. {
  664. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  665. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  666. { LLM_TENSOR_OUTPUT, "output"},
  667. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  668. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  669. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  670. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  671. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  672. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  673. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  674. { LLM_TENSOR_POS_EMBD, "position_embd" },
  675. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  676. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  677. },
  678. },
  679. {
  680. LLM_ARCH_STARCODER,
  681. {
  682. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  683. { LLM_TENSOR_POS_EMBD, "position_embd" },
  684. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  685. { LLM_TENSOR_OUTPUT, "output" },
  686. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  687. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  688. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  689. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  690. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  691. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  692. },
  693. },
  694. {
  695. LLM_ARCH_REFACT,
  696. {
  697. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  698. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  699. { LLM_TENSOR_OUTPUT, "output" },
  700. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  701. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  702. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  703. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  704. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  705. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  706. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  707. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  708. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  709. },
  710. },
  711. {
  712. LLM_ARCH_BERT,
  713. {
  714. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  715. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  716. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  717. { LLM_TENSOR_POS_EMBD, "position_embd" },
  718. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  719. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  720. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  721. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  722. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  723. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  724. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  725. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  726. },
  727. },
  728. {
  729. LLM_ARCH_NOMIC_BERT,
  730. {
  731. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  732. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  733. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  734. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  735. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  736. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  737. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  738. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  739. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  740. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  741. },
  742. },
  743. {
  744. LLM_ARCH_JINA_BERT_V2,
  745. {
  746. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  747. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  748. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  749. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  750. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  751. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  752. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  753. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  754. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  755. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  758. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  759. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_BLOOM,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  768. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  769. { LLM_TENSOR_OUTPUT, "output" },
  770. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  771. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  772. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  773. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  774. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  775. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  776. },
  777. },
  778. {
  779. LLM_ARCH_STABLELM,
  780. {
  781. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  782. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  783. { LLM_TENSOR_OUTPUT, "output" },
  784. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  785. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  786. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  787. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  788. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  789. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  790. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  791. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  792. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  793. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  794. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  795. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  796. },
  797. },
  798. {
  799. LLM_ARCH_QWEN,
  800. {
  801. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  802. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  803. { LLM_TENSOR_OUTPUT, "output" },
  804. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  805. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  806. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  807. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  808. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  809. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  810. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  811. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  812. },
  813. },
  814. {
  815. LLM_ARCH_QWEN2,
  816. {
  817. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  818. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  819. { LLM_TENSOR_OUTPUT, "output" },
  820. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  821. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  822. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  823. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  824. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  825. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  826. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  827. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  828. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  829. },
  830. },
  831. {
  832. LLM_ARCH_QWEN2MOE,
  833. {
  834. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  835. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  836. { LLM_TENSOR_OUTPUT, "output" },
  837. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  838. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  839. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  840. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  841. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  842. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  843. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  844. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  845. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  846. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  847. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  848. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  849. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  850. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  851. },
  852. },
  853. {
  854. LLM_ARCH_PHI2,
  855. {
  856. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  857. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  858. { LLM_TENSOR_OUTPUT, "output" },
  859. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  860. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  861. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  862. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  863. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  864. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  865. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  866. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  867. },
  868. },
  869. {
  870. LLM_ARCH_PHI3,
  871. {
  872. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  873. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  874. { LLM_TENSOR_OUTPUT, "output" },
  875. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  876. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  877. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  878. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  879. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  880. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  881. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  882. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  883. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  884. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  885. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  886. },
  887. },
  888. {
  889. LLM_ARCH_PLAMO,
  890. {
  891. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  892. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  893. { LLM_TENSOR_OUTPUT, "output" },
  894. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  895. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  896. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  897. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  898. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  899. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  900. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  901. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  902. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  903. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  904. },
  905. },
  906. {
  907. LLM_ARCH_CODESHELL,
  908. {
  909. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  910. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  911. { LLM_TENSOR_OUTPUT, "output" },
  912. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  913. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  914. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  915. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  916. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  917. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  918. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  919. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  920. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  921. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  922. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  923. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  924. },
  925. },
  926. {
  927. LLM_ARCH_ORION,
  928. {
  929. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  930. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  931. { LLM_TENSOR_OUTPUT, "output" },
  932. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  933. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  934. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  935. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  936. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  937. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  938. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  939. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  940. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  941. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  942. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  943. },
  944. },
  945. {
  946. LLM_ARCH_INTERNLM2,
  947. {
  948. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  949. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  950. { LLM_TENSOR_OUTPUT, "output" },
  951. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  952. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  953. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  954. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  955. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  956. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  957. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  958. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  959. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  960. },
  961. },
  962. {
  963. LLM_ARCH_MINICPM,
  964. {
  965. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  966. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  967. { LLM_TENSOR_OUTPUT, "output" },
  968. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  969. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  970. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  971. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  972. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  973. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  974. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  975. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  976. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  977. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  978. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  979. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  980. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  981. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  982. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  983. },
  984. },
  985. {
  986. LLM_ARCH_GEMMA,
  987. {
  988. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  989. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  990. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  991. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  992. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  993. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  994. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  995. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  996. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  997. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  998. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  999. },
  1000. },
  1001. {
  1002. LLM_ARCH_GEMMA2,
  1003. {
  1004. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1005. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1006. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1007. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1008. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1009. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1010. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1011. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1012. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1013. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1014. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1015. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1016. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1017. },
  1018. },
  1019. {
  1020. LLM_ARCH_STARCODER2,
  1021. {
  1022. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1023. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1024. { LLM_TENSOR_OUTPUT, "output" },
  1025. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1026. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1027. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1028. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1029. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1030. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1031. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1032. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1033. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1034. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1035. },
  1036. },
  1037. {
  1038. LLM_ARCH_MAMBA,
  1039. {
  1040. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1041. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1042. { LLM_TENSOR_OUTPUT, "output" },
  1043. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1044. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1045. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1046. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1047. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1048. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1049. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1050. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1051. },
  1052. },
  1053. {
  1054. LLM_ARCH_XVERSE,
  1055. {
  1056. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1057. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1058. { LLM_TENSOR_OUTPUT, "output" },
  1059. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1060. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1061. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1062. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1063. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1064. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1065. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1066. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1067. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1068. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1069. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1070. },
  1071. },
  1072. {
  1073. LLM_ARCH_COMMAND_R,
  1074. {
  1075. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1076. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1077. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1078. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1079. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1080. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1081. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1082. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1083. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1084. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1085. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1086. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1087. },
  1088. },
  1089. {
  1090. LLM_ARCH_DBRX,
  1091. {
  1092. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1093. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1094. { LLM_TENSOR_OUTPUT, "output" },
  1095. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1096. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1097. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1098. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1099. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1100. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1101. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1102. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1103. },
  1104. },
  1105. {
  1106. LLM_ARCH_OLMO,
  1107. {
  1108. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1109. { LLM_TENSOR_OUTPUT, "output" },
  1110. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1111. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1112. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1113. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1114. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1115. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1116. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1117. },
  1118. },
  1119. {
  1120. LLM_ARCH_OPENELM,
  1121. {
  1122. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1123. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1124. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1125. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1126. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1127. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1128. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1129. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1130. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1131. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1132. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1133. },
  1134. },
  1135. {
  1136. LLM_ARCH_ARCTIC,
  1137. {
  1138. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1139. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1140. { LLM_TENSOR_OUTPUT, "output" },
  1141. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1142. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1143. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1144. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1145. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1146. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1147. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1148. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1149. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1150. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1151. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1152. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1153. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1154. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1155. },
  1156. },
  1157. {
  1158. LLM_ARCH_DEEPSEEK2,
  1159. {
  1160. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1161. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1162. { LLM_TENSOR_OUTPUT, "output" },
  1163. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1164. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1165. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1166. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1167. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1168. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1169. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1170. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1171. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1172. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1173. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1174. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1175. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1176. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1177. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1178. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1179. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1180. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1181. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1182. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1183. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1184. },
  1185. },
  1186. {
  1187. LLM_ARCH_CHATGLM,
  1188. {
  1189. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1190. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1191. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1192. { LLM_TENSOR_OUTPUT, "output" },
  1193. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1194. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1195. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1196. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1197. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1198. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1199. },
  1200. },
  1201. {
  1202. LLM_ARCH_BITNET,
  1203. {
  1204. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1205. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1206. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1207. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1208. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1209. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1210. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1211. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1212. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1213. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1214. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1215. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1216. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1217. },
  1218. },
  1219. {
  1220. LLM_ARCH_T5,
  1221. {
  1222. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1223. { LLM_TENSOR_OUTPUT, "output" },
  1224. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1225. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1226. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1227. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1228. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1229. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1230. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1231. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1232. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1233. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1234. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1235. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1236. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1237. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1238. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1239. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1240. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1241. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1242. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1243. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1244. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1245. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1246. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1247. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1248. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1249. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1250. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1251. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1252. },
  1253. },
  1254. {
  1255. LLM_ARCH_JAIS,
  1256. {
  1257. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1258. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1259. { LLM_TENSOR_OUTPUT, "output" },
  1260. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1261. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1262. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1263. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1264. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1265. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1266. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1267. },
  1268. },
  1269. {
  1270. LLM_ARCH_UNKNOWN,
  1271. {
  1272. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1273. },
  1274. },
  1275. };
  1276. static llm_arch llm_arch_from_string(const std::string & name) {
  1277. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1278. if (kv.second == name) {
  1279. return kv.first;
  1280. }
  1281. }
  1282. return LLM_ARCH_UNKNOWN;
  1283. }
  1284. // helper to handle gguf constants
  1285. // usage:
  1286. //
  1287. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1288. //
  1289. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1290. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1291. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1292. //
  1293. struct LLM_TN {
  1294. LLM_TN(llm_arch arch) : arch(arch) {}
  1295. llm_arch arch;
  1296. std::string operator()(llm_tensor tensor) const {
  1297. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1298. return "__missing__";
  1299. }
  1300. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1301. }
  1302. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1303. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1304. return "__missing__";
  1305. }
  1306. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1307. }
  1308. std::string operator()(llm_tensor tensor, int bid) const {
  1309. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1310. return "__missing__";
  1311. }
  1312. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1313. }
  1314. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1315. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1316. return "__missing__";
  1317. }
  1318. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1319. }
  1320. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1321. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1322. return "__missing__";
  1323. }
  1324. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1325. }
  1326. };
  1327. //
  1328. // gguf helpers
  1329. //
  1330. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1331. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1332. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1333. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1334. };
  1335. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1336. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1337. if (kv.second == name) {
  1338. return (llama_rope_scaling_type) kv.first;
  1339. }
  1340. }
  1341. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1342. }
  1343. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1344. switch (type) {
  1345. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1346. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1347. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1348. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1349. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1350. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1351. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1352. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1353. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1354. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1355. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1356. default: return format("unknown type %d", type);
  1357. }
  1358. }
  1359. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1360. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1361. switch (type) {
  1362. case GGUF_TYPE_STRING:
  1363. return gguf_get_val_str(ctx_gguf, i);
  1364. case GGUF_TYPE_ARRAY:
  1365. {
  1366. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1367. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1368. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1369. std::stringstream ss;
  1370. ss << "[";
  1371. for (int j = 0; j < arr_n; j++) {
  1372. if (arr_type == GGUF_TYPE_STRING) {
  1373. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1374. // escape quotes
  1375. replace_all(val, "\\", "\\\\");
  1376. replace_all(val, "\"", "\\\"");
  1377. ss << '"' << val << '"';
  1378. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1379. ss << "???";
  1380. } else {
  1381. ss << gguf_data_to_str(arr_type, data, j);
  1382. }
  1383. if (j < arr_n - 1) {
  1384. ss << ", ";
  1385. }
  1386. }
  1387. ss << "]";
  1388. return ss.str();
  1389. }
  1390. default:
  1391. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1392. }
  1393. }
  1394. //
  1395. // llama helpers
  1396. //
  1397. #if defined(_WIN32)
  1398. static std::string llama_format_win_err(DWORD err) {
  1399. LPSTR buf;
  1400. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1401. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1402. if (!size) {
  1403. return "FormatMessageA failed";
  1404. }
  1405. std::string ret(buf, size);
  1406. LocalFree(buf);
  1407. return ret;
  1408. }
  1409. #endif
  1410. template <typename T>
  1411. struct no_init {
  1412. T value;
  1413. no_init() { /* do nothing */ }
  1414. };
  1415. struct llama_file {
  1416. #if defined(_WIN32)
  1417. // use FILE * so we don't have to re-open the file to mmap
  1418. FILE * fp;
  1419. HANDLE fp_win32;
  1420. size_t size;
  1421. private:
  1422. std::string GetErrorMessageWin32(DWORD error_code) const {
  1423. std::string ret;
  1424. LPSTR lpMsgBuf = NULL;
  1425. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1426. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1427. if (!bufLen) {
  1428. ret = format("Win32 error code: %s", error_code);
  1429. } else {
  1430. ret = lpMsgBuf;
  1431. LocalFree(lpMsgBuf);
  1432. }
  1433. return ret;
  1434. }
  1435. public:
  1436. llama_file(const char * fname, const char * mode) {
  1437. fp = ggml_fopen(fname, mode);
  1438. if (fp == NULL) {
  1439. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1440. }
  1441. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1442. seek(0, SEEK_END);
  1443. size = tell();
  1444. seek(0, SEEK_SET);
  1445. }
  1446. size_t tell() const {
  1447. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1448. LARGE_INTEGER li;
  1449. li.QuadPart = 0;
  1450. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1451. if (!ret) {
  1452. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1453. }
  1454. return li.QuadPart;
  1455. }
  1456. void seek(size_t offset, int whence) const {
  1457. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1458. // Still, keep static asserts to avoid failures in the future.
  1459. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1460. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1461. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1462. LARGE_INTEGER li;
  1463. li.QuadPart = offset;
  1464. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1465. if (!ret) {
  1466. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1467. }
  1468. }
  1469. void read_raw(void * ptr, size_t len) const {
  1470. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1471. // use the Win32 API to do file io instead of the C/C++ library functions.
  1472. // There are conditions under which ReadFile cannot read chunks >64MB.
  1473. // Thus split the operation into smaller chunks if len exceeds this limit.
  1474. size_t bytes_read = 0;
  1475. while (bytes_read < len) {
  1476. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1477. DWORD chunk_read = 0;
  1478. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1479. if (!result) {
  1480. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1481. }
  1482. if (chunk_read < chunk_size || chunk_read == 0) {
  1483. throw std::runtime_error("unexpectedly reached end of file");
  1484. }
  1485. bytes_read += chunk_read;
  1486. } ;
  1487. }
  1488. uint32_t read_u32() const {
  1489. uint32_t val;
  1490. read_raw(&val, sizeof(val));
  1491. return val;
  1492. }
  1493. void write_raw(const void * ptr, size_t len) const {
  1494. // There are conditions under which WriteFile cannot write chunks >64MB.
  1495. // Thus split the operation into smaller chunks if len exceeds this limit.
  1496. size_t bytes_written = 0;
  1497. while (bytes_written < len) {
  1498. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1499. DWORD chunk_written = 0;
  1500. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1501. if (!result) {
  1502. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1503. }
  1504. if (chunk_written < chunk_size || chunk_written == 0) {
  1505. throw std::runtime_error("unexpectedly failed to write bytes");
  1506. }
  1507. bytes_written += chunk_written;
  1508. }
  1509. }
  1510. void write_u32(std::uint32_t val) const {
  1511. write_raw(&val, sizeof(val));
  1512. }
  1513. ~llama_file() {
  1514. if (fp) {
  1515. std::fclose(fp);
  1516. }
  1517. }
  1518. #else
  1519. // use FILE * so we don't have to re-open the file to mmap
  1520. FILE * fp;
  1521. size_t size;
  1522. llama_file(const char * fname, const char * mode) {
  1523. fp = ggml_fopen(fname, mode);
  1524. if (fp == NULL) {
  1525. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1526. }
  1527. seek(0, SEEK_END);
  1528. size = tell();
  1529. seek(0, SEEK_SET);
  1530. }
  1531. size_t tell() const {
  1532. #ifdef _WIN32
  1533. __int64 ret = _ftelli64(fp);
  1534. #else
  1535. long ret = std::ftell(fp);
  1536. #endif
  1537. if (ret == -1) {
  1538. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1539. }
  1540. return (size_t) ret;
  1541. }
  1542. void seek(size_t offset, int whence) const {
  1543. #ifdef _WIN32
  1544. int ret = _fseeki64(fp, (__int64) offset, whence);
  1545. #else
  1546. int ret = std::fseek(fp, (long) offset, whence);
  1547. #endif
  1548. if (ret != 0) {
  1549. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1550. }
  1551. }
  1552. void read_raw(void * ptr, size_t len) const {
  1553. if (len == 0) {
  1554. return;
  1555. }
  1556. errno = 0;
  1557. std::size_t ret = std::fread(ptr, len, 1, fp);
  1558. if (ferror(fp)) {
  1559. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1560. }
  1561. if (ret != 1) {
  1562. throw std::runtime_error("unexpectedly reached end of file");
  1563. }
  1564. }
  1565. uint32_t read_u32() const {
  1566. uint32_t ret;
  1567. read_raw(&ret, sizeof(ret));
  1568. return ret;
  1569. }
  1570. void write_raw(const void * ptr, size_t len) const {
  1571. if (len == 0) {
  1572. return;
  1573. }
  1574. errno = 0;
  1575. size_t ret = std::fwrite(ptr, len, 1, fp);
  1576. if (ret != 1) {
  1577. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1578. }
  1579. }
  1580. void write_u32(std::uint32_t val) const {
  1581. write_raw(&val, sizeof(val));
  1582. }
  1583. ~llama_file() {
  1584. if (fp) {
  1585. std::fclose(fp);
  1586. }
  1587. }
  1588. #endif
  1589. };
  1590. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1591. struct llama_mmap {
  1592. void * addr;
  1593. size_t size;
  1594. llama_mmap(const llama_mmap &) = delete;
  1595. #ifdef _POSIX_MAPPED_FILES
  1596. static constexpr bool SUPPORTED = true;
  1597. // list of mapped fragments (first_offset, last_offset)
  1598. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1599. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1600. size = file->size;
  1601. int fd = fileno(file->fp);
  1602. int flags = MAP_SHARED;
  1603. // prefetch/readahead impairs performance on NUMA systems
  1604. if (numa) { prefetch = 0; }
  1605. #ifdef __linux__
  1606. // advise the kernel to read the file sequentially (increases readahead)
  1607. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1608. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1609. strerror(errno));
  1610. }
  1611. if (prefetch) { flags |= MAP_POPULATE; }
  1612. #endif
  1613. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1614. if (addr == MAP_FAILED) { // NOLINT
  1615. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1616. }
  1617. if (prefetch > 0) {
  1618. // advise the kernel to preload the mapped memory
  1619. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1620. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1621. strerror(errno));
  1622. }
  1623. }
  1624. if (numa) {
  1625. // advise the kernel not to use readahead
  1626. // (because the next page might not belong on the same node)
  1627. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1628. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1629. strerror(errno));
  1630. }
  1631. }
  1632. // initialize list of mapped_fragments
  1633. mapped_fragments.emplace_back(0, file->size);
  1634. }
  1635. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1636. // align first to the next page
  1637. size_t offset_in_page = *first & (page_size - 1);
  1638. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1639. *first += offset_to_page;
  1640. // align last to the previous page
  1641. *last = *last & ~(page_size - 1);
  1642. if (*last <= *first) {
  1643. *last = *first;
  1644. }
  1645. }
  1646. // partially unmap the file in the range [first, last)
  1647. void unmap_fragment(size_t first, size_t last) {
  1648. // note: this function must not be called multiple times with overlapping ranges
  1649. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1650. int page_size = sysconf(_SC_PAGESIZE);
  1651. align_range(&first, &last, page_size);
  1652. size_t len = last - first;
  1653. if (len == 0) {
  1654. return;
  1655. }
  1656. GGML_ASSERT(first % page_size == 0);
  1657. GGML_ASSERT(last % page_size == 0);
  1658. GGML_ASSERT(last > first);
  1659. void * next_page_start = (uint8_t *) addr + first;
  1660. // unmap the range
  1661. if (munmap(next_page_start, len)) {
  1662. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1663. }
  1664. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1665. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1666. for (const auto & frag : mapped_fragments) {
  1667. if (frag.first < first && frag.second > last) {
  1668. // the range is in the middle of the fragment, split it
  1669. new_mapped_fragments.emplace_back(frag.first, first);
  1670. new_mapped_fragments.emplace_back(last, frag.second);
  1671. } else if (frag.first < first && frag.second > first) {
  1672. // the range starts in the middle of the fragment
  1673. new_mapped_fragments.emplace_back(frag.first, first);
  1674. } else if (frag.first < last && frag.second > last) {
  1675. // the range ends in the middle of the fragment
  1676. new_mapped_fragments.emplace_back(last, frag.second);
  1677. } else if (frag.first >= first && frag.second <= last) {
  1678. // the range covers the entire fragment
  1679. } else {
  1680. // the range is outside the fragment
  1681. new_mapped_fragments.push_back(frag);
  1682. }
  1683. }
  1684. mapped_fragments = std::move(new_mapped_fragments);
  1685. }
  1686. ~llama_mmap() {
  1687. for (const auto & frag : mapped_fragments) {
  1688. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1689. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1690. }
  1691. }
  1692. }
  1693. #elif defined(_WIN32)
  1694. static constexpr bool SUPPORTED = true;
  1695. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1696. GGML_UNUSED(numa);
  1697. size = file->size;
  1698. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1699. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1700. if (hMapping == NULL) {
  1701. DWORD error = GetLastError();
  1702. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1703. }
  1704. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1705. DWORD error = GetLastError();
  1706. CloseHandle(hMapping);
  1707. if (addr == NULL) {
  1708. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1709. }
  1710. if (prefetch > 0) {
  1711. #if _WIN32_WINNT >= 0x602
  1712. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1713. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1714. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1715. // may fail on pre-Windows 8 systems
  1716. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1717. if (pPrefetchVirtualMemory) {
  1718. // advise the kernel to preload the mapped memory
  1719. WIN32_MEMORY_RANGE_ENTRY range;
  1720. range.VirtualAddress = addr;
  1721. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1722. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1723. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1724. llama_format_win_err(GetLastError()).c_str());
  1725. }
  1726. }
  1727. #else
  1728. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1729. #endif
  1730. }
  1731. }
  1732. void unmap_fragment(size_t first, size_t last) {
  1733. // not supported
  1734. GGML_UNUSED(first);
  1735. GGML_UNUSED(last);
  1736. }
  1737. ~llama_mmap() {
  1738. if (!UnmapViewOfFile(addr)) {
  1739. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1740. llama_format_win_err(GetLastError()).c_str());
  1741. }
  1742. }
  1743. #else
  1744. static constexpr bool SUPPORTED = false;
  1745. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1746. GGML_UNUSED(file);
  1747. GGML_UNUSED(prefetch);
  1748. GGML_UNUSED(numa);
  1749. throw std::runtime_error("mmap not supported");
  1750. }
  1751. void unmap_fragment(size_t first, size_t last) {
  1752. GGML_UNUSED(first);
  1753. GGML_UNUSED(last);
  1754. throw std::runtime_error("mmap not supported");
  1755. }
  1756. #endif
  1757. };
  1758. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1759. // Represents some region of memory being locked using mlock or VirtualLock;
  1760. // will automatically unlock on destruction.
  1761. struct llama_mlock {
  1762. void * addr = NULL;
  1763. size_t size = 0;
  1764. bool failed_already = false;
  1765. llama_mlock() {}
  1766. llama_mlock(const llama_mlock &) = delete;
  1767. ~llama_mlock() {
  1768. if (size) {
  1769. raw_unlock(addr, size);
  1770. }
  1771. }
  1772. void init(void * ptr) {
  1773. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1774. addr = ptr;
  1775. }
  1776. void grow_to(size_t target_size) {
  1777. GGML_ASSERT(addr);
  1778. if (failed_already) {
  1779. return;
  1780. }
  1781. size_t granularity = lock_granularity();
  1782. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1783. if (target_size > size) {
  1784. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1785. size = target_size;
  1786. } else {
  1787. failed_already = true;
  1788. }
  1789. }
  1790. }
  1791. #ifdef _POSIX_MEMLOCK_RANGE
  1792. static constexpr bool SUPPORTED = true;
  1793. static size_t lock_granularity() {
  1794. return (size_t) sysconf(_SC_PAGESIZE);
  1795. }
  1796. #ifdef __APPLE__
  1797. #define MLOCK_SUGGESTION \
  1798. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1799. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1800. #else
  1801. #define MLOCK_SUGGESTION \
  1802. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1803. #endif
  1804. bool raw_lock(const void * addr, size_t size) const {
  1805. if (!mlock(addr, size)) {
  1806. return true;
  1807. }
  1808. char* errmsg = std::strerror(errno);
  1809. bool suggest = (errno == ENOMEM);
  1810. // Check if the resource limit is fine after all
  1811. struct rlimit lock_limit;
  1812. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1813. suggest = false;
  1814. }
  1815. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1816. suggest = false;
  1817. }
  1818. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1819. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1820. return false;
  1821. }
  1822. #undef MLOCK_SUGGESTION
  1823. static void raw_unlock(void * addr, size_t size) {
  1824. if (munlock(addr, size)) {
  1825. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1826. }
  1827. }
  1828. #elif defined(_WIN32)
  1829. static constexpr bool SUPPORTED = true;
  1830. static size_t lock_granularity() {
  1831. SYSTEM_INFO si;
  1832. GetSystemInfo(&si);
  1833. return (size_t) si.dwPageSize;
  1834. }
  1835. bool raw_lock(void * ptr, size_t len) const {
  1836. for (int tries = 1; ; tries++) {
  1837. if (VirtualLock(ptr, len)) {
  1838. return true;
  1839. }
  1840. if (tries == 2) {
  1841. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1842. len, size, llama_format_win_err(GetLastError()).c_str());
  1843. return false;
  1844. }
  1845. // It failed but this was only the first try; increase the working
  1846. // set size and try again.
  1847. SIZE_T min_ws_size, max_ws_size;
  1848. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1849. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1850. llama_format_win_err(GetLastError()).c_str());
  1851. return false;
  1852. }
  1853. // Per MSDN: "The maximum number of pages that a process can lock
  1854. // is equal to the number of pages in its minimum working set minus
  1855. // a small overhead."
  1856. // Hopefully a megabyte is enough overhead:
  1857. size_t increment = len + 1048576;
  1858. // The minimum must be <= the maximum, so we need to increase both:
  1859. min_ws_size += increment;
  1860. max_ws_size += increment;
  1861. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1862. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1863. llama_format_win_err(GetLastError()).c_str());
  1864. return false;
  1865. }
  1866. }
  1867. }
  1868. static void raw_unlock(void * ptr, size_t len) {
  1869. if (!VirtualUnlock(ptr, len)) {
  1870. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1871. llama_format_win_err(GetLastError()).c_str());
  1872. }
  1873. }
  1874. #else
  1875. static constexpr bool SUPPORTED = false;
  1876. static size_t lock_granularity() {
  1877. return (size_t) 65536;
  1878. }
  1879. bool raw_lock(const void * addr, size_t len) const {
  1880. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1881. return false;
  1882. }
  1883. static void raw_unlock(const void * addr, size_t len) {}
  1884. #endif
  1885. };
  1886. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1887. // NOTE: avoid ever using this except for building the token_to_piece caches
  1888. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  1889. std::string piece;
  1890. piece.resize(piece.capacity()); // using string internal cache
  1891. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1892. if (n_chars < 0) {
  1893. piece.resize(-n_chars);
  1894. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1895. GGML_ASSERT(check == -n_chars);
  1896. }
  1897. else {
  1898. piece.resize(n_chars);
  1899. }
  1900. return piece;
  1901. }
  1902. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1903. ggml_backend_buffer_type_t buft = nullptr;
  1904. #if defined(GGML_USE_CUDA)
  1905. // host buffers should only be used when data is expected to be copied to/from the GPU
  1906. if (host_buffer) {
  1907. buft = ggml_backend_cuda_host_buffer_type();
  1908. }
  1909. #elif defined(GGML_USE_SYCL)
  1910. if (host_buffer) {
  1911. buft = ggml_backend_sycl_host_buffer_type();
  1912. }
  1913. #elif defined(GGML_USE_CPU_HBM)
  1914. buft = ggml_backend_cpu_hbm_buffer_type();
  1915. #elif defined(GGML_USE_VULKAN)
  1916. if (host_buffer) {
  1917. buft = ggml_backend_vk_host_buffer_type();
  1918. }
  1919. #endif
  1920. if (buft == nullptr) {
  1921. buft = ggml_backend_cpu_buffer_type();
  1922. }
  1923. return buft;
  1924. GGML_UNUSED(host_buffer);
  1925. }
  1926. //
  1927. // globals
  1928. //
  1929. struct llama_state {
  1930. llama_state() {
  1931. #ifdef GGML_USE_METAL
  1932. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1933. #elif defined(GGML_USE_CUDA)
  1934. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1935. #elif defined(GGML_USE_CANN)
  1936. ggml_backend_cann_log_set_callback(log_callback, log_callback_user_data);
  1937. #endif
  1938. }
  1939. // We save the log callback globally
  1940. ggml_log_callback log_callback = llama_log_callback_default;
  1941. void * log_callback_user_data = nullptr;
  1942. };
  1943. static llama_state g_state;
  1944. // available llama models
  1945. enum e_model {
  1946. MODEL_UNKNOWN,
  1947. MODEL_14M,
  1948. MODEL_17M,
  1949. MODEL_22M,
  1950. MODEL_33M,
  1951. MODEL_60M,
  1952. MODEL_70M,
  1953. MODEL_80M,
  1954. MODEL_109M,
  1955. MODEL_137M,
  1956. MODEL_160M,
  1957. MODEL_220M,
  1958. MODEL_250M,
  1959. MODEL_270M,
  1960. MODEL_335M,
  1961. MODEL_410M,
  1962. MODEL_450M,
  1963. MODEL_770M,
  1964. MODEL_780M,
  1965. MODEL_0_5B,
  1966. MODEL_1B,
  1967. MODEL_1_3B,
  1968. MODEL_1_4B,
  1969. MODEL_2B,
  1970. MODEL_2_8B,
  1971. MODEL_3B,
  1972. MODEL_4B,
  1973. MODEL_6B,
  1974. MODEL_6_9B,
  1975. MODEL_7B,
  1976. MODEL_8B,
  1977. MODEL_9B,
  1978. MODEL_11B,
  1979. MODEL_12B,
  1980. MODEL_13B,
  1981. MODEL_14B,
  1982. MODEL_15B,
  1983. MODEL_16B,
  1984. MODEL_20B,
  1985. MODEL_30B,
  1986. MODEL_34B,
  1987. MODEL_35B,
  1988. MODEL_40B,
  1989. MODEL_65B,
  1990. MODEL_70B,
  1991. MODEL_236B,
  1992. MODEL_314B,
  1993. MODEL_SMALL,
  1994. MODEL_MEDIUM,
  1995. MODEL_LARGE,
  1996. MODEL_XL,
  1997. MODEL_A2_7B,
  1998. MODEL_8x7B,
  1999. MODEL_8x22B,
  2000. MODEL_16x12B,
  2001. MODEL_10B_128x3_66B,
  2002. MODEL_57B_A14B,
  2003. MODEL_27B,
  2004. };
  2005. static const size_t kiB = 1024;
  2006. static const size_t MiB = 1024*kiB;
  2007. static const size_t GiB = 1024*MiB;
  2008. struct llama_hparams {
  2009. bool vocab_only;
  2010. bool rope_finetuned;
  2011. bool use_par_res;
  2012. uint32_t n_vocab;
  2013. uint32_t n_ctx_train; // context size the model was trained on
  2014. uint32_t n_embd;
  2015. uint32_t n_layer;
  2016. uint32_t n_rot;
  2017. uint32_t n_swa = 0; // sliding window attention (SWA)
  2018. 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
  2019. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2020. uint32_t n_expert = 0;
  2021. uint32_t n_expert_used = 0;
  2022. uint32_t n_vocab_type = 0; // for BERT-style token types
  2023. uint32_t n_rel_attn_bkts = 0;
  2024. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2025. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2026. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2027. uint32_t n_layer_dense_lead = 0;
  2028. uint32_t n_lora_q = 0;
  2029. uint32_t n_lora_kv = 0;
  2030. uint32_t n_ff_exp = 0;
  2031. uint32_t n_ff_shexp = 0;
  2032. uint32_t n_expert_shared = 0;
  2033. float expert_weights_scale = 0.0;
  2034. float f_norm_eps;
  2035. float f_norm_rms_eps;
  2036. float f_attn_logit_softcapping = 50.0f;
  2037. float f_final_logit_softcapping = 30.0f;
  2038. float rope_attn_factor = 1.0f;
  2039. float rope_freq_base_train;
  2040. float rope_freq_scale_train;
  2041. uint32_t n_ctx_orig_yarn;
  2042. float rope_yarn_log_mul;
  2043. // for State Space Models
  2044. uint32_t ssm_d_conv = 0;
  2045. uint32_t ssm_d_inner = 0;
  2046. uint32_t ssm_d_state = 0;
  2047. uint32_t ssm_dt_rank = 0;
  2048. float f_clamp_kqv = 0.0f;
  2049. float f_max_alibi_bias = 0.0f;
  2050. float f_logit_scale = 0.0f;
  2051. bool causal_attn = true;
  2052. bool use_alibi = false;
  2053. bool attn_soft_cap = false;
  2054. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2055. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2056. llama_token dec_start_token_id = -1;
  2057. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2058. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2059. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2060. bool operator!=(const llama_hparams & other) const {
  2061. if (this->vocab_only != other.vocab_only) return true;
  2062. if (this->n_vocab != other.n_vocab) return true;
  2063. if (this->n_ctx_train != other.n_ctx_train) return true;
  2064. if (this->n_embd != other.n_embd) return true;
  2065. if (this->n_layer != other.n_layer) return true;
  2066. if (this->n_rot != other.n_rot) return true;
  2067. if (this->n_swa != other.n_swa) return true;
  2068. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2069. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2070. if (this->n_expert != other.n_expert) return true;
  2071. if (this->n_expert_used != other.n_expert_used) return true;
  2072. if (this->n_head_arr != other.n_head_arr) return true;
  2073. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2074. if (this->n_ff_arr != other.n_ff_arr) return true;
  2075. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2076. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2077. if (this->n_lora_q != other.n_lora_q) return true;
  2078. if (this->n_lora_kv != other.n_lora_kv) return true;
  2079. if (this->n_ff_exp != other.n_ff_exp) return true;
  2080. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2081. if (this->n_expert_shared != other.n_expert_shared) return true;
  2082. if (this->rope_finetuned != other.rope_finetuned) return true;
  2083. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2084. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2085. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2086. if (this->ssm_d_state != other.ssm_d_state) return true;
  2087. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2088. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2089. const float EPSILON = 1e-9f;
  2090. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2091. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2092. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2093. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2094. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2095. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2096. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2097. return false;
  2098. }
  2099. uint32_t n_head(uint32_t il = 0) const {
  2100. if (il < n_layer) {
  2101. return n_head_arr[il];
  2102. }
  2103. GGML_ABORT("fatal error");
  2104. }
  2105. uint32_t n_head_kv(uint32_t il = 0) const {
  2106. if (il < n_layer) {
  2107. return n_head_kv_arr[il];
  2108. }
  2109. GGML_ABORT("fatal error");
  2110. }
  2111. uint32_t n_ff(uint32_t il = 0) const {
  2112. if (il < n_layer) {
  2113. return n_ff_arr[il];
  2114. }
  2115. GGML_ABORT("fatal error");
  2116. }
  2117. uint32_t n_gqa(uint32_t il = 0) const {
  2118. const uint32_t n_head = this->n_head(il);
  2119. const uint32_t n_head_kv = this->n_head_kv(il);
  2120. if (n_head_kv == 0) {
  2121. return 0;
  2122. }
  2123. return n_head/n_head_kv;
  2124. }
  2125. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2126. const uint32_t n_head_kv = this->n_head_kv(il);
  2127. return n_embd_head_k * n_head_kv;
  2128. }
  2129. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2130. const uint32_t n_head_kv = this->n_head_kv(il);
  2131. return n_embd_head_v * n_head_kv;
  2132. }
  2133. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2134. // corresponds to Mamba's conv_states size
  2135. // TODO: maybe support other convolution strides than 1
  2136. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2137. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2138. }
  2139. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2140. // corresponds to Mamba's ssm_states size
  2141. return ssm_d_state * ssm_d_inner;
  2142. }
  2143. };
  2144. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2145. struct llama_cparams {
  2146. uint32_t n_ctx; // context size used during inference
  2147. uint32_t n_batch;
  2148. uint32_t n_ubatch;
  2149. uint32_t n_seq_max;
  2150. uint32_t n_threads; // number of threads to use for generation
  2151. uint32_t n_threads_batch; // number of threads to use for batch processing
  2152. float rope_freq_base;
  2153. float rope_freq_scale;
  2154. uint32_t n_ctx_orig_yarn;
  2155. // These hyperparameters are not exposed in GGUF, because all
  2156. // existing YaRN models use the same values for them.
  2157. float yarn_ext_factor;
  2158. float yarn_attn_factor;
  2159. float yarn_beta_fast;
  2160. float yarn_beta_slow;
  2161. float defrag_thold;
  2162. bool embeddings;
  2163. bool causal_attn;
  2164. bool offload_kqv;
  2165. bool flash_attn;
  2166. enum llama_pooling_type pooling_type;
  2167. ggml_backend_sched_eval_callback cb_eval;
  2168. void * cb_eval_user_data;
  2169. };
  2170. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2171. struct llama_layer {
  2172. // normalization
  2173. struct ggml_tensor * attn_norm;
  2174. struct ggml_tensor * attn_norm_b;
  2175. struct ggml_tensor * attn_norm_2;
  2176. struct ggml_tensor * attn_norm_2_b;
  2177. struct ggml_tensor * attn_q_norm;
  2178. struct ggml_tensor * attn_q_norm_b;
  2179. struct ggml_tensor * attn_k_norm;
  2180. struct ggml_tensor * attn_k_norm_b;
  2181. struct ggml_tensor * attn_out_norm;
  2182. struct ggml_tensor * attn_out_norm_b;
  2183. struct ggml_tensor * attn_q_a_norm;
  2184. struct ggml_tensor * attn_kv_a_norm;
  2185. struct ggml_tensor * attn_sub_norm;
  2186. struct ggml_tensor * attn_post_norm;
  2187. struct ggml_tensor * ffn_sub_norm;
  2188. struct ggml_tensor * attn_norm_cross;
  2189. struct ggml_tensor * attn_norm_enc;
  2190. // attention
  2191. struct ggml_tensor * wq;
  2192. struct ggml_tensor * wk;
  2193. struct ggml_tensor * wv;
  2194. struct ggml_tensor * wo;
  2195. struct ggml_tensor * wqkv;
  2196. struct ggml_tensor * wq_a;
  2197. struct ggml_tensor * wq_b;
  2198. struct ggml_tensor * wkv_a_mqa;
  2199. struct ggml_tensor * wkv_b;
  2200. struct ggml_tensor * wq_cross;
  2201. struct ggml_tensor * wk_cross;
  2202. struct ggml_tensor * wv_cross;
  2203. struct ggml_tensor * wo_cross;
  2204. struct ggml_tensor * wq_enc;
  2205. struct ggml_tensor * wk_enc;
  2206. struct ggml_tensor * wv_enc;
  2207. struct ggml_tensor * wo_enc;
  2208. // attention bias
  2209. struct ggml_tensor * bq;
  2210. struct ggml_tensor * bk;
  2211. struct ggml_tensor * bv;
  2212. struct ggml_tensor * bo;
  2213. struct ggml_tensor * bqkv;
  2214. // relative position bias
  2215. struct ggml_tensor * attn_rel_b;
  2216. struct ggml_tensor * attn_rel_b_enc;
  2217. struct ggml_tensor * attn_rel_b_cross;
  2218. // normalization
  2219. struct ggml_tensor * ffn_norm;
  2220. struct ggml_tensor * ffn_norm_b;
  2221. struct ggml_tensor * ffn_post_norm;
  2222. struct ggml_tensor * layer_out_norm;
  2223. struct ggml_tensor * layer_out_norm_b;
  2224. struct ggml_tensor * ffn_norm_exps;
  2225. struct ggml_tensor * ffn_norm_enc;
  2226. // ff
  2227. struct ggml_tensor * ffn_gate; // w1
  2228. struct ggml_tensor * ffn_down; // w2
  2229. struct ggml_tensor * ffn_up; // w3
  2230. struct ggml_tensor * ffn_gate_enc;
  2231. struct ggml_tensor * ffn_down_enc;
  2232. struct ggml_tensor * ffn_up_enc;
  2233. // ff MoE
  2234. struct ggml_tensor * ffn_gate_inp;
  2235. struct ggml_tensor * ffn_gate_exps;
  2236. struct ggml_tensor * ffn_down_exps;
  2237. struct ggml_tensor * ffn_up_exps ;
  2238. // ff shared expert (shexp)
  2239. struct ggml_tensor * ffn_gate_inp_shexp;
  2240. struct ggml_tensor * ffn_gate_shexp;
  2241. struct ggml_tensor * ffn_down_shexp;
  2242. struct ggml_tensor * ffn_up_shexp;
  2243. // ff bias
  2244. struct ggml_tensor * ffn_gate_b = nullptr;
  2245. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2246. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2247. struct ggml_tensor * ffn_act;
  2248. // mamba proj
  2249. struct ggml_tensor * ssm_in;
  2250. struct ggml_tensor * ssm_x;
  2251. struct ggml_tensor * ssm_dt;
  2252. struct ggml_tensor * ssm_out;
  2253. // mamba
  2254. struct ggml_tensor * ssm_conv1d;
  2255. struct ggml_tensor * ssm_a;
  2256. struct ggml_tensor * ssm_d;
  2257. // mamba bias
  2258. struct ggml_tensor * ssm_conv1d_b;
  2259. struct ggml_tensor * ssm_dt_b;
  2260. // long rope factors
  2261. struct ggml_tensor * rope_long = nullptr;
  2262. struct ggml_tensor * rope_short = nullptr;
  2263. struct ggml_tensor * rope_freqs = nullptr;
  2264. // bitnet scale
  2265. struct ggml_tensor * wq_scale;
  2266. struct ggml_tensor * wk_scale;
  2267. struct ggml_tensor * wv_scale;
  2268. struct ggml_tensor * wo_scale;
  2269. struct ggml_tensor * ffn_gate_scale;
  2270. struct ggml_tensor * ffn_up_scale;
  2271. struct ggml_tensor * ffn_down_scale;
  2272. };
  2273. struct llama_kv_cell {
  2274. llama_pos pos = -1;
  2275. llama_pos delta = 0;
  2276. int32_t src = 0; // used by recurrent state models to copy states
  2277. std::set<llama_seq_id> seq_id;
  2278. bool has_seq_id(const llama_seq_id & id) const {
  2279. return seq_id.find(id) != seq_id.end();
  2280. }
  2281. bool is_empty() const {
  2282. return seq_id.empty();
  2283. }
  2284. bool is_same_seq(const llama_kv_cell & other) const {
  2285. return seq_id == other.seq_id;
  2286. }
  2287. };
  2288. // ring-buffer of cached KV data
  2289. struct llama_kv_cache {
  2290. bool has_shift = false;
  2291. bool do_defrag = false;
  2292. bool do_copy = false;
  2293. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2294. bool v_trans = true; // the value tensor is transposed
  2295. // Note: The value of head isn't only used to optimize searching
  2296. // for a free KV slot. llama_decode_internal also uses it, so it
  2297. // cannot be freely changed after a slot has been allocated.
  2298. uint32_t head = 0;
  2299. uint32_t size = 0;
  2300. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2301. // computed before each graph build
  2302. uint32_t n = 0;
  2303. ggml_type type_k = GGML_TYPE_F16;
  2304. ggml_type type_v = GGML_TYPE_F16;
  2305. std::vector<llama_kv_cell> cells;
  2306. std::vector<struct ggml_tensor *> k_l; // per layer
  2307. std::vector<struct ggml_tensor *> v_l;
  2308. std::vector<struct ggml_context *> ctxs;
  2309. std::vector<ggml_backend_buffer_t> bufs;
  2310. size_t total_size() const {
  2311. size_t size = 0;
  2312. for (ggml_backend_buffer_t buf : bufs) {
  2313. size += ggml_backend_buffer_get_size(buf);
  2314. }
  2315. return size;
  2316. }
  2317. ~llama_kv_cache() {
  2318. for (struct ggml_context * ctx : ctxs) {
  2319. ggml_free(ctx);
  2320. }
  2321. for (ggml_backend_buffer_t buf : bufs) {
  2322. ggml_backend_buffer_free(buf);
  2323. }
  2324. }
  2325. };
  2326. struct llama_control_vector {
  2327. std::vector<struct ggml_tensor *> tensors; // per layer
  2328. std::vector<struct ggml_context *> ctxs;
  2329. std::vector<ggml_backend_buffer_t> bufs;
  2330. int32_t layer_start = -1;
  2331. int32_t layer_end = -1;
  2332. struct ggml_tensor * tensor_for(int il) const {
  2333. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2334. return nullptr;
  2335. }
  2336. return tensors[il];
  2337. }
  2338. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2339. ggml_tensor * layer_dir = tensor_for(il);
  2340. if (layer_dir != nullptr) {
  2341. cur = ggml_add(ctx, cur, layer_dir);
  2342. }
  2343. return cur;
  2344. }
  2345. ~llama_control_vector() {
  2346. for (struct ggml_context * ctx : ctxs) {
  2347. ggml_free(ctx);
  2348. }
  2349. for (ggml_backend_buffer_t buf : bufs) {
  2350. ggml_backend_buffer_free(buf);
  2351. }
  2352. }
  2353. };
  2354. struct llama_model {
  2355. e_model type = MODEL_UNKNOWN;
  2356. llm_arch arch = LLM_ARCH_UNKNOWN;
  2357. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2358. std::string name = "n/a";
  2359. llama_hparams hparams = {};
  2360. llama_vocab vocab;
  2361. struct ggml_tensor * tok_embd;
  2362. struct ggml_tensor * type_embd;
  2363. struct ggml_tensor * pos_embd;
  2364. struct ggml_tensor * tok_norm;
  2365. struct ggml_tensor * tok_norm_b;
  2366. struct ggml_tensor * output_norm;
  2367. struct ggml_tensor * output_norm_b;
  2368. struct ggml_tensor * output;
  2369. struct ggml_tensor * output_b;
  2370. struct ggml_tensor * output_norm_enc;
  2371. std::vector<llama_layer> layers;
  2372. llama_split_mode split_mode;
  2373. int main_gpu;
  2374. int n_gpu_layers;
  2375. std::vector<std::string> rpc_servers;
  2376. // gguf metadata
  2377. std::unordered_map<std::string, std::string> gguf_kv;
  2378. // layer -> buffer type mapping
  2379. struct layer_buft {
  2380. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2381. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2382. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2383. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2384. ggml_backend_buffer_type_t buft; // everything else
  2385. };
  2386. layer_buft buft_input;
  2387. layer_buft buft_output;
  2388. std::vector<layer_buft> buft_layer;
  2389. // contexts where the model tensors metadata is stored
  2390. std::vector<struct ggml_context *> ctxs;
  2391. // the model memory buffers for the tensor data
  2392. std::vector<ggml_backend_buffer_t> bufs;
  2393. // model memory mapped files
  2394. llama_mmaps mappings;
  2395. // objects representing data potentially being locked in memory
  2396. llama_mlocks mlock_bufs;
  2397. llama_mlocks mlock_mmaps;
  2398. // for quantize-stats only
  2399. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2400. int64_t t_load_us = 0;
  2401. int64_t t_start_us = 0;
  2402. // keep track of loaded lora adapters
  2403. std::set<struct llama_lora_adapter *> lora_adapters;
  2404. ~llama_model() {
  2405. for (struct ggml_context * ctx : ctxs) {
  2406. ggml_free(ctx);
  2407. }
  2408. for (ggml_backend_buffer_t buf : bufs) {
  2409. #ifdef GGML_USE_CUDA
  2410. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2411. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2412. }
  2413. #endif
  2414. ggml_backend_buffer_free(buf);
  2415. }
  2416. while (!lora_adapters.empty()) {
  2417. llama_lora_adapter_free(*lora_adapters.begin());
  2418. }
  2419. }
  2420. };
  2421. struct llama_context {
  2422. llama_context(const llama_model & model)
  2423. : model(model)
  2424. , sampling(llama_n_vocab(&model))
  2425. , t_start_us(model.t_start_us)
  2426. , t_load_us(model.t_load_us) {}
  2427. ~llama_context() {
  2428. ggml_backend_sched_free(sched);
  2429. for (ggml_backend_t backend : backends) {
  2430. ggml_backend_free(backend);
  2431. }
  2432. ggml_backend_buffer_free(buf_output);
  2433. }
  2434. const struct llama_model & model;
  2435. struct llama_cparams cparams;
  2436. struct llama_sampling sampling;
  2437. struct llama_kv_cache kv_self;
  2438. struct llama_control_vector cvec;
  2439. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  2440. std::vector<ggml_backend_t> backends;
  2441. #ifdef GGML_USE_METAL
  2442. ggml_backend_t backend_metal = nullptr;
  2443. #endif
  2444. #ifdef GGML_USE_BLAS
  2445. ggml_backend_t backend_blas = nullptr;
  2446. #endif
  2447. ggml_backend_t backend_cpu = nullptr;
  2448. bool has_evaluated_once = false;
  2449. int64_t t_start_us;
  2450. int64_t t_load_us;
  2451. int64_t t_p_eval_us = 0;
  2452. int64_t t_eval_us = 0;
  2453. int64_t t_compute_start_us = 0;
  2454. int64_t n_queued_tokens = 0;
  2455. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  2456. int32_t n_eval = 0; // number of eval calls
  2457. // host buffer for the model output (logits and embeddings)
  2458. ggml_backend_buffer_t buf_output = nullptr;
  2459. // decode output (2-dimensional array: [n_outputs][n_vocab])
  2460. size_t logits_size = 0; // capacity (of floats) for logits
  2461. float * logits = nullptr;
  2462. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  2463. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  2464. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  2465. bool logits_all = false;
  2466. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  2467. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  2468. size_t embd_size = 0; // capacity (of floats) for embeddings
  2469. float * embd = nullptr;
  2470. // sequence embeddings output (map of [n_embd] vectors)
  2471. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2472. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2473. // whether we are computing encoder output or decoder output
  2474. bool is_encoding = false;
  2475. // output of the encoder part of the encoder-decoder models
  2476. std::vector<float> embd_enc;
  2477. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  2478. // memory buffers used to evaluate the model
  2479. std::vector<uint8_t> buf_compute_meta;
  2480. ggml_backend_sched_t sched = nullptr;
  2481. ggml_abort_callback abort_callback = nullptr;
  2482. void * abort_callback_data = nullptr;
  2483. // input tensors
  2484. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2485. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2486. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2487. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2488. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2489. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  2490. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2491. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2492. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2493. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2494. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2495. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2496. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  2497. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  2498. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  2499. };
  2500. struct llama_lora_weight {
  2501. struct ggml_tensor * a = nullptr;
  2502. struct ggml_tensor * b = nullptr;
  2503. llama_lora_weight() = default;
  2504. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  2505. };
  2506. struct llama_lora_adapter {
  2507. struct llama_model * base_model;
  2508. // map tensor name to lora_a_b
  2509. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  2510. std::vector<struct ggml_context *> ctxs;
  2511. std::vector<ggml_backend_buffer_t> bufs;
  2512. float alpha;
  2513. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  2514. base_model->lora_adapters.insert(this);
  2515. }
  2516. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  2517. std::string name(w->name);
  2518. auto pos = ab_map.find(name);
  2519. if (ab_map.find(name) != ab_map.end()) {
  2520. return &pos->second;
  2521. }
  2522. return nullptr;
  2523. }
  2524. ~llama_lora_adapter() {
  2525. for (struct ggml_context * ctx : ctxs) {
  2526. ggml_free(ctx);
  2527. }
  2528. for (ggml_backend_buffer_t buf : bufs) {
  2529. ggml_backend_buffer_free(buf);
  2530. }
  2531. auto pos = base_model->lora_adapters.find(this);
  2532. if (pos != base_model->lora_adapters.end()) {
  2533. base_model->lora_adapters.erase(pos);
  2534. }
  2535. }
  2536. };
  2537. static size_t llama_get_device_count(const llama_model & model) {
  2538. size_t count = 1;
  2539. #if defined(GGML_USE_CUDA)
  2540. count = ggml_backend_cuda_get_device_count();
  2541. #elif defined(GGML_USE_SYCL)
  2542. count = ggml_backend_sycl_get_device_count();
  2543. #elif defined(GGML_USE_VULKAN)
  2544. count = ggml_backend_vk_get_device_count();
  2545. #elif defined(GGML_USE_CANN)
  2546. return ggml_backend_cann_get_device_count();
  2547. #endif
  2548. #if defined(GGML_USE_RPC)
  2549. count += model.rpc_servers.size();
  2550. #endif
  2551. return count;
  2552. GGML_UNUSED(model);
  2553. }
  2554. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2555. ggml_backend_buffer_type_t buft = nullptr;
  2556. #if defined(GGML_USE_RPC)
  2557. int dev_count = (int)llama_get_device_count(model);
  2558. int rpc_count = (int)model.rpc_servers.size();
  2559. if (gpu >= dev_count - rpc_count) {
  2560. const char * endpoint = model.rpc_servers[gpu - dev_count + rpc_count].c_str();
  2561. return ggml_backend_rpc_buffer_type(endpoint);
  2562. }
  2563. #endif
  2564. #if defined(GGML_USE_METAL)
  2565. buft = ggml_backend_metal_buffer_type();
  2566. #elif defined(GGML_USE_CUDA)
  2567. buft = ggml_backend_cuda_buffer_type(gpu);
  2568. #elif defined(GGML_USE_VULKAN)
  2569. buft = ggml_backend_vk_buffer_type(gpu);
  2570. #elif defined(GGML_USE_SYCL)
  2571. buft = ggml_backend_sycl_buffer_type(gpu);
  2572. #elif defined(GGML_USE_KOMPUTE)
  2573. buft = ggml_backend_kompute_buffer_type(gpu);
  2574. if (buft == nullptr) {
  2575. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2576. }
  2577. #elif defined(GGML_USE_CANN)
  2578. buft = ggml_backend_cann_buffer_type(gpu);
  2579. #endif
  2580. if (buft == nullptr) {
  2581. buft = llama_default_buffer_type_cpu(true);
  2582. }
  2583. return buft;
  2584. GGML_UNUSED(model);
  2585. GGML_UNUSED(gpu);
  2586. }
  2587. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2588. ggml_backend_buffer_type_t buft = nullptr;
  2589. #ifdef GGML_USE_CUDA
  2590. if (ggml_backend_cuda_get_device_count() > 1) {
  2591. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2592. }
  2593. #endif
  2594. #ifdef GGML_USE_SYCL
  2595. if (ggml_backend_sycl_get_device_count() > 1) {
  2596. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2597. }
  2598. #endif
  2599. if (buft == nullptr) {
  2600. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2601. }
  2602. return buft;
  2603. GGML_UNUSED(tensor_split);
  2604. }
  2605. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2606. #if defined(GGML_USE_RPC)
  2607. int dev_count = (int)llama_get_device_count(model);
  2608. int rpc_count = (int)model.rpc_servers.size();
  2609. if (device >= dev_count - rpc_count) {
  2610. size_t total;
  2611. size_t free;
  2612. const char * endpoint = model.rpc_servers[device - dev_count + rpc_count].c_str();
  2613. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  2614. return free;
  2615. }
  2616. #endif
  2617. #if defined(GGML_USE_CUDA)
  2618. size_t total;
  2619. size_t free;
  2620. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2621. return free;
  2622. #elif defined(GGML_USE_SYCL)
  2623. size_t total;
  2624. size_t free;
  2625. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2626. return free;
  2627. #elif defined(GGML_USE_VULKAN)
  2628. size_t total;
  2629. size_t free;
  2630. ggml_backend_vk_get_device_memory(device, &free, &total);
  2631. return free;
  2632. #elif defined(GGML_USE_CANN)
  2633. size_t total;
  2634. size_t free;
  2635. ggml_backend_cann_get_device_memory(device, &free, &total);
  2636. return free;
  2637. #else
  2638. return 1;
  2639. #endif
  2640. GGML_UNUSED(model);
  2641. GGML_UNUSED(device);
  2642. }
  2643. //
  2644. // kv cache helpers
  2645. //
  2646. static bool llama_kv_cache_init(
  2647. struct llama_kv_cache & cache,
  2648. const llama_context * ctx,
  2649. ggml_type type_k,
  2650. ggml_type type_v,
  2651. uint32_t kv_size,
  2652. bool offload) {
  2653. const llama_model & model = ctx->model;
  2654. const llama_cparams & cparams = ctx->cparams;
  2655. const struct llama_hparams & hparams = model.hparams;
  2656. const int64_t n_layer = hparams.n_layer;
  2657. cache.has_shift = false;
  2658. // TODO: find a nicer way to add other recurrent model architectures
  2659. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2660. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  2661. cache.head = 0;
  2662. cache.size = kv_size;
  2663. cache.used = 0;
  2664. cache.type_k = type_k;
  2665. cache.type_v = type_v;
  2666. cache.cells.clear();
  2667. cache.cells.resize(kv_size);
  2668. if (cache.recurrent) {
  2669. // init state copy sources
  2670. for (uint32_t i = 0; i < cache.size; ++i) {
  2671. cache.cells[i].src = i;
  2672. }
  2673. }
  2674. // count used buffer types
  2675. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2676. if (offload) {
  2677. for (int64_t i = 0; i < n_layer; ++i) {
  2678. buft_layer_count[model.buft_layer[i].buft]++;
  2679. }
  2680. } else {
  2681. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2682. }
  2683. // create a context for each buffer type
  2684. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2685. for (auto & it : buft_layer_count) {
  2686. int n_layers = it.second;
  2687. struct ggml_init_params params = {
  2688. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2689. /*.mem_buffer =*/ NULL,
  2690. /*.no_alloc =*/ true,
  2691. };
  2692. ggml_context * ctx = ggml_init(params);
  2693. if (!ctx) {
  2694. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2695. return false;
  2696. }
  2697. ctx_map[it.first] = ctx;
  2698. cache.ctxs.push_back(ctx);
  2699. }
  2700. cache.k_l.reserve(n_layer);
  2701. cache.v_l.reserve(n_layer);
  2702. for (int i = 0; i < (int) n_layer; i++) {
  2703. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  2704. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  2705. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2706. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2707. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2708. ggml_format_name(k, "cache_k_l%d", i);
  2709. ggml_format_name(v, "cache_v_l%d", i);
  2710. cache.k_l.push_back(k);
  2711. cache.v_l.push_back(v);
  2712. }
  2713. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2714. for (auto it : ctx_map) {
  2715. ggml_backend_buffer_type_t buft = it.first;
  2716. ggml_context * ctx = it.second;
  2717. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2718. if (!buf) {
  2719. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2720. return false;
  2721. }
  2722. ggml_backend_buffer_clear(buf, 0);
  2723. 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);
  2724. cache.bufs.push_back(buf);
  2725. }
  2726. return true;
  2727. }
  2728. // find an empty slot of size "n_tokens" in the cache
  2729. // updates the cache head
  2730. // Note: On success, it's important that cache.head points
  2731. // to the first cell of the slot.
  2732. static bool llama_kv_cache_find_slot(
  2733. struct llama_kv_cache & cache,
  2734. const struct llama_batch & batch) {
  2735. const uint32_t n_tokens = batch.n_tokens;
  2736. if (cache.recurrent) {
  2737. // For recurrent state architectures (like Mamba),
  2738. // each KV cache cell can store the state for a whole sequence.
  2739. llama_seq_id min = cache.size - 1;
  2740. llama_seq_id max = 0;
  2741. for (uint32_t i = 0; i < n_tokens; ++i) {
  2742. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2743. llama_seq_id seq_id = batch.seq_id[i][j];
  2744. // make sure it's a valid seq_id
  2745. if ((uint32_t) seq_id < cache.size) {
  2746. if (seq_id > max) {
  2747. max = seq_id;
  2748. }
  2749. if (seq_id < min) {
  2750. min = seq_id;
  2751. }
  2752. // Assuming the tokens are in-order
  2753. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2754. // What should happen when the pos backtracks or skips a value?
  2755. // Clearing the state mid-batch would require special-casing which isn't done.
  2756. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2757. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2758. }
  2759. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2760. cache.used += 1;
  2761. }
  2762. cache.cells[seq_id].pos = batch.pos[i];
  2763. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2764. } else {
  2765. // too big seq_id
  2766. // TODO: would it be possible to resize the KV cache size instead?
  2767. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2768. return false;
  2769. }
  2770. }
  2771. }
  2772. // allow getting the range of used cells, from head to head + n
  2773. cache.head = min;
  2774. cache.n = max - min + 1;
  2775. // sanity check
  2776. return max >= min;
  2777. }
  2778. // otherwise, one cell per token.
  2779. if (n_tokens > cache.size) {
  2780. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  2781. return false;
  2782. }
  2783. uint32_t n_tested = 0;
  2784. while (true) {
  2785. if (cache.head + n_tokens > cache.size) {
  2786. n_tested += cache.size - cache.head;
  2787. cache.head = 0;
  2788. continue;
  2789. }
  2790. bool found = true;
  2791. for (uint32_t i = 0; i < n_tokens; i++) {
  2792. if (cache.cells[cache.head + i].pos >= 0) {
  2793. found = false;
  2794. cache.head += i + 1;
  2795. n_tested += i + 1;
  2796. break;
  2797. }
  2798. }
  2799. if (found) {
  2800. break;
  2801. }
  2802. if (n_tested >= cache.size) {
  2803. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2804. return false;
  2805. }
  2806. }
  2807. for (uint32_t i = 0; i < n_tokens; i++) {
  2808. cache.cells[cache.head + i].pos = batch.pos[i];
  2809. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2810. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2811. }
  2812. }
  2813. cache.used += n_tokens;
  2814. return true;
  2815. }
  2816. // find how many cells are currently in use
  2817. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2818. for (uint32_t i = cache.size; i > 0; --i) {
  2819. const llama_kv_cell & cell = cache.cells[i - 1];
  2820. if (cell.pos >= 0 && !cell.is_empty()) {
  2821. return i;
  2822. }
  2823. }
  2824. return 0;
  2825. }
  2826. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2827. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2828. cache.cells[i].pos = -1;
  2829. cache.cells[i].seq_id.clear();
  2830. }
  2831. cache.head = 0;
  2832. cache.used = 0;
  2833. for (auto & buf : cache.bufs) {
  2834. ggml_backend_buffer_clear(buf, 0);
  2835. }
  2836. }
  2837. static bool llama_kv_cache_seq_rm(
  2838. struct llama_kv_cache & cache,
  2839. llama_seq_id seq_id,
  2840. llama_pos p0,
  2841. llama_pos p1) {
  2842. uint32_t new_head = cache.size;
  2843. if (p0 < 0) p0 = 0;
  2844. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2845. // models like Mamba can't have a state partially erased
  2846. if (cache.recurrent) {
  2847. if (seq_id >= (int64_t) cache.size) {
  2848. // could be fatal
  2849. return false;
  2850. }
  2851. if (0 <= seq_id) {
  2852. // partial intersection is invalid
  2853. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2854. return false;
  2855. }
  2856. } else {
  2857. // seq_id is negative, then the range should include everything or nothing
  2858. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2859. return false;
  2860. }
  2861. }
  2862. }
  2863. for (uint32_t i = 0; i < cache.size; ++i) {
  2864. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2865. if (seq_id < 0) {
  2866. cache.cells[i].seq_id.clear();
  2867. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2868. cache.cells[i].seq_id.erase(seq_id);
  2869. } else {
  2870. continue;
  2871. }
  2872. if (cache.cells[i].is_empty()) {
  2873. // keep count of the number of used cells
  2874. if (cache.cells[i].pos >= 0) cache.used--;
  2875. cache.cells[i].pos = -1;
  2876. if (new_head == cache.size) new_head = i;
  2877. }
  2878. }
  2879. }
  2880. // If we freed up a slot, set head to it so searching can start there.
  2881. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2882. return true;
  2883. }
  2884. static void llama_kv_cache_seq_cp(
  2885. struct llama_kv_cache & cache,
  2886. llama_seq_id seq_id_src,
  2887. llama_seq_id seq_id_dst,
  2888. llama_pos p0,
  2889. llama_pos p1) {
  2890. if (p0 < 0) p0 = 0;
  2891. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2892. if (cache.recurrent) {
  2893. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2894. seq_id_src = cache.cells[seq_id_src].src;
  2895. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2896. // intent to "copy from"
  2897. // supports copy chains thanks to taking the source of the source
  2898. cache.cells[seq_id_dst].src = seq_id_src;
  2899. // preserve the "keep or clear" status of the copied sequence
  2900. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2901. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2902. } else {
  2903. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2904. }
  2905. cache.do_copy = true;
  2906. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2907. }
  2908. return;
  2909. }
  2910. // otherwise, this is the KV cache of a Transformer-like model
  2911. cache.head = 0;
  2912. for (uint32_t i = 0; i < cache.size; ++i) {
  2913. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2914. cache.cells[i].seq_id.insert(seq_id_dst);
  2915. }
  2916. }
  2917. }
  2918. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2919. uint32_t new_head = cache.size;
  2920. for (uint32_t i = 0; i < cache.size; ++i) {
  2921. if (!cache.cells[i].has_seq_id(seq_id)) {
  2922. if (cache.cells[i].pos >= 0) cache.used--;
  2923. cache.cells[i].pos = -1;
  2924. cache.cells[i].seq_id.clear();
  2925. if (new_head == cache.size) new_head = i;
  2926. } else {
  2927. cache.cells[i].seq_id.clear();
  2928. cache.cells[i].seq_id.insert(seq_id);
  2929. }
  2930. }
  2931. // If we freed up a slot, set head to it so searching can start there.
  2932. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2933. }
  2934. static void llama_kv_cache_seq_add(
  2935. struct llama_kv_cache & cache,
  2936. llama_seq_id seq_id,
  2937. llama_pos p0,
  2938. llama_pos p1,
  2939. llama_pos delta) {
  2940. uint32_t new_head = cache.size;
  2941. if (p0 < 0) p0 = 0;
  2942. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2943. // If there is no range then return early to avoid looping over the cache.
  2944. if (p0 == p1) return;
  2945. if (cache.recurrent) {
  2946. // for Mamba-like models, only the pos needs to be shifted
  2947. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2948. llama_kv_cell & cell = cache.cells[seq_id];
  2949. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2950. cell.pos += delta;
  2951. }
  2952. }
  2953. return;
  2954. }
  2955. for (uint32_t i = 0; i < cache.size; ++i) {
  2956. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2957. cache.has_shift = true;
  2958. cache.cells[i].pos += delta;
  2959. cache.cells[i].delta += delta;
  2960. if (cache.cells[i].pos < 0) {
  2961. if (!cache.cells[i].is_empty()) {
  2962. cache.used--;
  2963. }
  2964. cache.cells[i].pos = -1;
  2965. cache.cells[i].seq_id.clear();
  2966. if (new_head == cache.size) {
  2967. new_head = i;
  2968. }
  2969. }
  2970. }
  2971. }
  2972. // If we freed up a slot, set head to it so searching can start there.
  2973. // Otherwise we just start the next search from the beginning.
  2974. cache.head = new_head != cache.size ? new_head : 0;
  2975. }
  2976. static void llama_kv_cache_seq_div(
  2977. struct llama_kv_cache & cache,
  2978. llama_seq_id seq_id,
  2979. llama_pos p0,
  2980. llama_pos p1,
  2981. int d) {
  2982. if (p0 < 0) p0 = 0;
  2983. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2984. // If there is no range then return early to avoid looping over the cache.
  2985. if (p0 == p1) return;
  2986. if (cache.recurrent) {
  2987. // for Mamba-like models, only the pos needs to be changed
  2988. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2989. llama_kv_cell & cell = cache.cells[seq_id];
  2990. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2991. cell.pos /= d;
  2992. }
  2993. }
  2994. return;
  2995. }
  2996. for (uint32_t i = 0; i < cache.size; ++i) {
  2997. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2998. cache.has_shift = true;
  2999. {
  3000. llama_pos p_old = cache.cells[i].pos;
  3001. cache.cells[i].pos /= d;
  3002. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3003. }
  3004. }
  3005. }
  3006. }
  3007. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3008. llama_pos result = 0;
  3009. for (uint32_t i = 0; i < cache.size; ++i) {
  3010. if (cache.cells[i].has_seq_id(seq_id)) {
  3011. result = std::max(result, cache.cells[i].pos);
  3012. }
  3013. }
  3014. return result;
  3015. }
  3016. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3017. cache.do_defrag = true;
  3018. }
  3019. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3020. // the FA kernels require padding to avoid extra runtime boundary checks
  3021. return cparams.flash_attn ? 256u : 32u;
  3022. }
  3023. //
  3024. // model loading and saving
  3025. //
  3026. enum llama_fver {
  3027. GGUF_FILE_VERSION_V1 = 1,
  3028. GGUF_FILE_VERSION_V2 = 2,
  3029. GGUF_FILE_VERSION_V3 = 3,
  3030. };
  3031. static const char * llama_file_version_name(llama_fver version) {
  3032. switch (version) {
  3033. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3034. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3035. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3036. }
  3037. return "unknown";
  3038. }
  3039. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3040. char buf[256];
  3041. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3042. for (size_t i = 1; i < ne.size(); i++) {
  3043. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3044. }
  3045. return buf;
  3046. }
  3047. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3048. char buf[256];
  3049. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3050. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3051. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3052. }
  3053. return buf;
  3054. }
  3055. namespace GGUFMeta {
  3056. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3057. struct GKV_Base_Type {
  3058. static constexpr gguf_type gt = gt_;
  3059. static T getter(const gguf_context * ctx, const int kid) {
  3060. return gfun(ctx, kid);
  3061. }
  3062. };
  3063. template<typename T> struct GKV_Base;
  3064. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3065. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3066. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3067. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3068. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3069. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3070. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3071. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3072. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3073. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3074. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3075. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3076. template<> struct GKV_Base<std::string> {
  3077. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3078. static std::string getter(const gguf_context * ctx, const int kid) {
  3079. return gguf_get_val_str(ctx, kid);
  3080. }
  3081. };
  3082. struct ArrayInfo {
  3083. const gguf_type gt;
  3084. const size_t length;
  3085. const void * data;
  3086. };
  3087. template<> struct GKV_Base<ArrayInfo> {
  3088. public:
  3089. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3090. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3091. return ArrayInfo {
  3092. gguf_get_arr_type(ctx, k),
  3093. size_t(gguf_get_arr_n(ctx, k)),
  3094. gguf_get_arr_data(ctx, k),
  3095. };
  3096. }
  3097. };
  3098. template<typename T>
  3099. class GKV : public GKV_Base<T> {
  3100. GKV() = delete;
  3101. public:
  3102. static T get_kv(const gguf_context * ctx, const int k) {
  3103. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3104. if (kt != GKV::gt) {
  3105. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3106. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3107. }
  3108. return GKV::getter(ctx, k);
  3109. }
  3110. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3111. switch (ty) {
  3112. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3113. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3114. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3115. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3116. }
  3117. return "unknown";
  3118. }
  3119. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3120. if (!ovrd) { return false; }
  3121. if (ovrd->tag == expected_type) {
  3122. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3123. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3124. switch (ovrd->tag) {
  3125. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3126. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3127. } break;
  3128. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3129. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3130. } break;
  3131. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3132. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3133. } break;
  3134. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3135. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  3136. } break;
  3137. default:
  3138. // Shouldn't be possible to end up here, but just in case...
  3139. throw std::runtime_error(
  3140. format("Unsupported attempt to override %s type for metadata key %s\n",
  3141. override_type_to_str(ovrd->tag), ovrd->key));
  3142. }
  3143. return true;
  3144. }
  3145. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  3146. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  3147. return false;
  3148. }
  3149. template<typename OT>
  3150. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  3151. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3152. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  3153. target = ovrd->val_bool;
  3154. return true;
  3155. }
  3156. return false;
  3157. }
  3158. template<typename OT>
  3159. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  3160. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3161. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  3162. target = ovrd->val_i64;
  3163. return true;
  3164. }
  3165. return false;
  3166. }
  3167. template<typename OT>
  3168. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  3169. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3170. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  3171. target = ovrd->val_f64;
  3172. return true;
  3173. }
  3174. return false;
  3175. }
  3176. template<typename OT>
  3177. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  3178. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3179. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  3180. target = ovrd->val_str;
  3181. return true;
  3182. }
  3183. return false;
  3184. }
  3185. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3186. if (try_override<T>(target, ovrd)) {
  3187. return true;
  3188. }
  3189. if (k < 0) { return false; }
  3190. target = get_kv(ctx, k);
  3191. return true;
  3192. }
  3193. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3194. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  3195. }
  3196. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3197. return set(ctx, key.c_str(), target, ovrd);
  3198. }
  3199. };
  3200. }
  3201. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  3202. // TODO: update when needed or think of some clever automatic way to do this
  3203. static size_t llama_model_max_nodes(const llama_model & /*model*/) {
  3204. //if (model.arch == LLM_ARCH_LLAMA && model.hparams.n_layer > ??) { // llama-3 405B
  3205. // return 32768;
  3206. //}
  3207. return 8192;
  3208. }
  3209. struct llama_model_loader {
  3210. int n_kv = 0;
  3211. int n_tensors = 0;
  3212. int n_created = 0;
  3213. int64_t n_elements = 0;
  3214. size_t n_bytes = 0;
  3215. bool use_mmap = false;
  3216. bool check_tensors;
  3217. llama_files files;
  3218. llama_ftype ftype;
  3219. llama_fver fver;
  3220. llama_mmaps mappings;
  3221. // Holds information on a model weight
  3222. struct llama_tensor_weight {
  3223. uint16_t idx; // source file index
  3224. size_t offs; // tensor data offset in the original file
  3225. ggml_tensor * tensor;
  3226. 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) {
  3227. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  3228. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  3229. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  3230. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  3231. }
  3232. }
  3233. };
  3234. std::vector<llama_tensor_weight> weights;
  3235. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  3236. struct gguf_context * meta = NULL;
  3237. std::vector<ggml_context *> contexts;
  3238. std::string arch_name;
  3239. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  3240. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  3241. int trace = 0;
  3242. if (getenv("LLAMA_TRACE")) {
  3243. trace = atoi(getenv("LLAMA_TRACE"));
  3244. }
  3245. if (param_overrides_p != nullptr) {
  3246. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  3247. kv_overrides.insert({std::string(p->key), *p});
  3248. }
  3249. }
  3250. struct ggml_context * ctx = NULL;
  3251. struct gguf_init_params params = {
  3252. /*.no_alloc = */ true,
  3253. /*.ctx = */ &ctx,
  3254. };
  3255. meta = gguf_init_from_file(fname.c_str(), params);
  3256. if (!meta) {
  3257. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  3258. }
  3259. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  3260. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  3261. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  3262. contexts.emplace_back(ctx);
  3263. // Save tensors data offset of the main file.
  3264. // For subsidiary files, `meta` tensor data offset must not be used,
  3265. // so we build a unified tensors index for weights.
  3266. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3267. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  3268. }
  3269. uint16_t n_split = 0;
  3270. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  3271. // Load additional GGML contexts
  3272. if (n_split > 1) {
  3273. uint16_t idx = 0;
  3274. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  3275. if (idx != 0) {
  3276. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  3277. }
  3278. char split_prefix[PATH_MAX] = {0};
  3279. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  3280. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  3281. }
  3282. if (trace > 0) {
  3283. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  3284. }
  3285. char split_path[PATH_MAX] = {0};
  3286. for (idx = 1; idx < n_split; idx++) {
  3287. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  3288. struct gguf_init_params split_params = {
  3289. /*.no_alloc = */ true,
  3290. /*.ctx = */ &ctx,
  3291. };
  3292. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  3293. if (!ctx_gguf) {
  3294. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  3295. }
  3296. files.emplace_back(new llama_file(split_path, "rb"));
  3297. contexts.emplace_back(ctx);
  3298. // Save tensors data offset info of the shard.
  3299. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3300. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  3301. }
  3302. gguf_free(ctx_gguf);
  3303. }
  3304. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  3305. // sanity check
  3306. {
  3307. const int n_tensors_loaded = (int) weights.size();
  3308. if (n_tensors != n_tensors_loaded) {
  3309. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  3310. }
  3311. }
  3312. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  3313. }
  3314. n_kv = gguf_get_n_kv(meta);
  3315. n_tensors = weights.size();
  3316. fver = (enum llama_fver) gguf_get_version(meta);
  3317. std::set<std::string> tensor_names;
  3318. for (auto & w : weights) {
  3319. n_elements += ggml_nelements(w.tensor);
  3320. n_bytes += ggml_nbytes(w.tensor);
  3321. // make sure there is no duplicated tensor names
  3322. const std::string name(w.tensor->name);
  3323. auto found = tensor_names.find(name);
  3324. if (found != tensor_names.end()) {
  3325. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  3326. }
  3327. tensor_names.insert(name);
  3328. }
  3329. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  3330. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  3331. // determine file type based on the number of tensors for each quantization and print meta data
  3332. // TODO: make optional
  3333. {
  3334. std::map<enum ggml_type, uint32_t> n_type;
  3335. uint32_t n_type_max = 0;
  3336. enum ggml_type type_max = GGML_TYPE_F32;
  3337. for (int i = 0; i < n_tensors; i++) {
  3338. const ggml_tensor * tensor = weights.at(i).tensor;
  3339. enum ggml_type type = tensor->type;
  3340. n_type[type]++;
  3341. if (n_type_max < n_type[type]) {
  3342. n_type_max = n_type[type];
  3343. type_max = type;
  3344. }
  3345. if (trace > 0) {
  3346. const uint16_t sid = weights.at(i).idx;
  3347. 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());
  3348. }
  3349. }
  3350. switch (type_max) {
  3351. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  3352. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  3353. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  3354. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  3355. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  3356. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  3357. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  3358. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  3359. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  3360. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  3361. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  3362. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  3363. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  3364. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  3365. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  3366. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  3367. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  3368. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  3369. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  3370. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  3371. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  3372. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  3373. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  3374. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  3375. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  3376. default:
  3377. {
  3378. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  3379. ftype = LLAMA_FTYPE_ALL_F32;
  3380. } break;
  3381. }
  3382. // this is a way to mark that we have "guessed" the file type
  3383. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  3384. {
  3385. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  3386. if (kid >= 0) {
  3387. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  3388. }
  3389. }
  3390. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  3391. for (int i = 0; i < n_kv; i++) {
  3392. const char * name = gguf_get_key(meta, i);
  3393. const enum gguf_type type = gguf_get_kv_type(meta, i);
  3394. const std::string type_name =
  3395. type == GGUF_TYPE_ARRAY
  3396. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  3397. : gguf_type_name(type);
  3398. std::string value = gguf_kv_to_str(meta, i);
  3399. const size_t MAX_VALUE_LEN = 40;
  3400. if (value.size() > MAX_VALUE_LEN) {
  3401. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  3402. }
  3403. replace_all(value, "\n", "\\n");
  3404. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  3405. }
  3406. // print type counts
  3407. for (auto & kv : n_type) {
  3408. if (kv.second == 0) {
  3409. continue;
  3410. }
  3411. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  3412. }
  3413. }
  3414. if (!llama_mmap::SUPPORTED) {
  3415. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  3416. use_mmap = false;
  3417. }
  3418. this->use_mmap = use_mmap;
  3419. this->check_tensors = check_tensors;
  3420. }
  3421. ~llama_model_loader() {
  3422. if (meta) {
  3423. gguf_free(meta);
  3424. }
  3425. for (auto * ctx : contexts) {
  3426. ggml_free(ctx);
  3427. }
  3428. }
  3429. template<typename T>
  3430. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3431. get_arr_n(const std::string & key, T & result, const bool required = true) {
  3432. const int kid = gguf_find_key(meta, key.c_str());
  3433. if (kid < 0) {
  3434. if (required) {
  3435. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3436. }
  3437. return false;
  3438. }
  3439. struct GGUFMeta::ArrayInfo arr_info =
  3440. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3441. result = arr_info.length;
  3442. return true;
  3443. }
  3444. template<typename T>
  3445. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3446. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  3447. return get_arr_n(llm_kv(kid), result, required);
  3448. }
  3449. template<typename T>
  3450. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  3451. const int kid = gguf_find_key(meta, key.c_str());
  3452. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3453. if (required) {
  3454. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3455. }
  3456. return false;
  3457. }
  3458. struct GGUFMeta::ArrayInfo arr_info =
  3459. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3460. switch (arr_info.gt) {
  3461. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3462. case GGUF_TYPE_INT32: GGML_ASSERT(
  3463. (std::is_same<T, int32_t>::value) ||
  3464. (std::is_same<T, uint32_t>::value)); break;
  3465. default:
  3466. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3467. }
  3468. result.resize(arr_info.length);
  3469. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  3470. return true;
  3471. }
  3472. template<typename T, size_t N_MAX>
  3473. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  3474. const int kid = gguf_find_key(meta, key.c_str());
  3475. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3476. if (required) {
  3477. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3478. }
  3479. return false;
  3480. }
  3481. struct GGUFMeta::ArrayInfo arr_info =
  3482. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3483. switch (arr_info.gt) {
  3484. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3485. case GGUF_TYPE_INT32: GGML_ASSERT(
  3486. (std::is_same<T, int32_t>::value) ||
  3487. (std::is_same<T, uint32_t>::value)); break;
  3488. default:
  3489. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3490. }
  3491. if (arr_info.length > N_MAX) {
  3492. 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));
  3493. }
  3494. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  3495. return true;
  3496. }
  3497. template<typename T>
  3498. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  3499. return get_arr(llm_kv(kid), result, required);
  3500. }
  3501. template<typename T>
  3502. bool get_key(const std::string & key, T & result, const bool required = true) {
  3503. auto it = kv_overrides.find(key);
  3504. const struct llama_model_kv_override * override =
  3505. it != kv_overrides.end() ? &it->second : nullptr;
  3506. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  3507. if (required && !found) {
  3508. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3509. }
  3510. return found;
  3511. }
  3512. template<typename T>
  3513. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  3514. return get_key(llm_kv(kid), result, required);
  3515. }
  3516. // get array of n <= N_MAX elements, or a single element repeated n times
  3517. template<typename T, size_t N_MAX>
  3518. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  3519. const int kid = gguf_find_key(meta, key.c_str());
  3520. if (kid < 0) {
  3521. if (required) {
  3522. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3523. }
  3524. return false;
  3525. }
  3526. if (n > N_MAX) {
  3527. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  3528. }
  3529. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  3530. struct GGUFMeta::ArrayInfo arr_info =
  3531. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3532. if (n != arr_info.length) {
  3533. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  3534. }
  3535. return get_arr(key, result, required);
  3536. } else {
  3537. T value;
  3538. bool ok = get_key(key, value, required);
  3539. if (!ok) {
  3540. return false;
  3541. }
  3542. for (uint32_t i = 0; i < n; i++) {
  3543. result[i] = value;
  3544. }
  3545. return true;
  3546. }
  3547. }
  3548. template<typename T>
  3549. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  3550. return get_key_or_arr(llm_kv(kid), result, n, required);
  3551. }
  3552. std::string get_arch_name() const {
  3553. return arch_name;
  3554. }
  3555. enum llm_arch get_arch() const {
  3556. return llm_kv.arch;
  3557. }
  3558. const char * get_tensor_name(int i) const {
  3559. return weights.at(i).tensor->name;
  3560. }
  3561. const llama_tensor_weight * get_weight(const char * name) const {
  3562. for (const auto & weight : weights) {
  3563. if (strcmp(name, weight.tensor->name) == 0) {
  3564. return &weight;
  3565. }
  3566. }
  3567. return nullptr;
  3568. }
  3569. const llama_tensor_weight * get_weight(int i) const {
  3570. return get_weight(get_tensor_name(i));
  3571. }
  3572. const llama_tensor_weight & require_weight(const char * name) const {
  3573. const llama_tensor_weight * weight = get_weight(name);
  3574. if (!weight) {
  3575. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3576. }
  3577. return *weight;
  3578. }
  3579. struct ggml_tensor * get_tensor_meta(const char * name) const {
  3580. const auto * weight = get_weight(name);
  3581. if (!weight) {
  3582. return nullptr;
  3583. }
  3584. return weight->tensor;
  3585. }
  3586. struct ggml_tensor * require_tensor_meta(const char * name) const {
  3587. struct ggml_tensor * tensor = get_tensor_meta(name);
  3588. if (!tensor) {
  3589. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3590. }
  3591. return tensor;
  3592. }
  3593. struct ggml_tensor * get_tensor_meta(int i) const {
  3594. return get_tensor_meta(get_tensor_name(i));
  3595. }
  3596. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  3597. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  3598. ggml_set_name(tensor, ggml_get_name(cur));
  3599. if (duplicated) {
  3600. size_data += ggml_nbytes(cur);
  3601. } else {
  3602. n_created++;
  3603. }
  3604. return tensor;
  3605. }
  3606. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  3607. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  3608. if (cur == NULL) {
  3609. if (!required) {
  3610. return NULL;
  3611. }
  3612. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  3613. }
  3614. {
  3615. bool is_ok = true;
  3616. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3617. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  3618. is_ok = false;
  3619. break;
  3620. }
  3621. }
  3622. if (!is_ok) {
  3623. throw std::runtime_error(
  3624. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  3625. __func__, name.c_str(),
  3626. llama_format_tensor_shape(ne).c_str(),
  3627. llama_format_tensor_shape(cur).c_str()));
  3628. }
  3629. }
  3630. return cur;
  3631. }
  3632. static const int TENSOR_NOT_REQUIRED = 1;
  3633. static const int TENSOR_DUPLICATED = 2;
  3634. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  3635. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  3636. if (cur == NULL) {
  3637. return NULL;
  3638. }
  3639. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  3640. }
  3641. 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) {
  3642. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3643. if (cur == NULL) {
  3644. return NULL;
  3645. }
  3646. if (cur->type != base->type) {
  3647. 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)));
  3648. }
  3649. std::array<int64_t, GGML_MAX_DIMS> dims;
  3650. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3651. dims[i] = i < ne.size() ? ne[i] : 1;
  3652. }
  3653. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  3654. dims[0], dims[1], dims[2], dims[3],
  3655. cur->nb[1], cur->nb[2], cur->nb[3],
  3656. offset);
  3657. ggml_set_name(tensor, name.c_str());
  3658. n_created++;
  3659. return tensor;
  3660. }
  3661. void done_getting_tensors() const {
  3662. if (n_created != n_tensors) {
  3663. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  3664. }
  3665. }
  3666. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  3667. if (use_mmap) {
  3668. mappings.reserve(files.size());
  3669. mmaps_used.reserve(files.size());
  3670. for (const auto & file : files) {
  3671. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  3672. mmaps_used.emplace_back(mapping->size, 0);
  3673. if (mlock_mmaps) {
  3674. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  3675. mlock_mmap->init(mapping->addr);
  3676. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  3677. }
  3678. mappings.emplace_back(std::move(mapping));
  3679. }
  3680. }
  3681. // compute the total size of all tensors for progress reporting
  3682. for (auto & w : weights) {
  3683. size_data += ggml_nbytes(w.tensor);
  3684. }
  3685. }
  3686. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  3687. GGML_ASSERT(!mappings.empty());
  3688. const auto & mapping = mappings.at(idx);
  3689. *first = mapping->size;
  3690. *last = 0;
  3691. *addr = mapping->addr;
  3692. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3693. try {
  3694. const auto * weight = get_weight(ggml_get_name(tensor));
  3695. if (!weight) {
  3696. continue;
  3697. }
  3698. if (weight->idx != idx) {
  3699. continue;
  3700. }
  3701. *first = std::min(*first, weight->offs);
  3702. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  3703. } catch(...) {
  3704. // the tensor is not in the model
  3705. }
  3706. }
  3707. }
  3708. // for backwards compatibility, does not support ggml-backend
  3709. void load_data_for(struct ggml_tensor * cur) const {
  3710. const auto & w = require_weight(ggml_get_name(cur));
  3711. if (use_mmap) {
  3712. const auto & mapping = mappings.at(w.idx);
  3713. if (cur->data == nullptr) {
  3714. cur->data = (uint8_t *)mapping->addr + w.offs;
  3715. } else {
  3716. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  3717. }
  3718. } else {
  3719. GGML_ASSERT(cur->data != nullptr);
  3720. GGML_ASSERT(w.idx < files.size());
  3721. const auto & file = files.at(w.idx);
  3722. file->seek(w.offs, SEEK_SET);
  3723. file->read_raw(cur->data, ggml_nbytes(cur));
  3724. }
  3725. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  3726. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3727. }
  3728. }
  3729. size_t size_done = 0;
  3730. size_t size_data = 0;
  3731. std::vector<std::pair<size_t, size_t>> mmaps_used;
  3732. // Returns false if cancelled by progress_callback
  3733. bool load_all_data(
  3734. struct ggml_context * ctx,
  3735. llama_buf_map & bufs_mmap,
  3736. llama_mlocks * lmlocks,
  3737. llama_progress_callback progress_callback,
  3738. void * progress_callback_user_data) {
  3739. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  3740. std::vector<no_init<uint8_t>> read_buf;
  3741. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  3742. #if defined(GGML_USE_CUDA)
  3743. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  3744. // NVMe raid configurations might require more / larger buffers.
  3745. constexpr size_t n_buffers = 4;
  3746. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  3747. std::vector<ggml_backend_buffer_t> host_buffers;
  3748. std::vector<void*> host_ptrs;
  3749. std::vector<ggml_backend_event_t> events;
  3750. size_t buffer_idx = 0; // buffer to use for async loads
  3751. ggml_backend_t cuda_backend = nullptr;
  3752. if (!use_mmap && !check_tensors) {
  3753. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  3754. // First determine if the CUDA backend is active, and if so, determine the device ID.
  3755. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  3756. if (buf) {
  3757. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  3758. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  3759. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  3760. if (buffer_type == cuda_buffer_type) {
  3761. cuda_backend = ggml_backend_cuda_init(i);
  3762. break;
  3763. }
  3764. }
  3765. }
  3766. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  3767. if (cuda_backend) {
  3768. for (size_t idx = 0; idx < n_buffers; ++idx) {
  3769. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  3770. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  3771. events.emplace_back(ggml_backend_event_new(cuda_backend));
  3772. }
  3773. }
  3774. }
  3775. #endif
  3776. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3777. const auto * weight = get_weight(ggml_get_name(cur));
  3778. if (weight == nullptr) {
  3779. // this can happen with split experts models
  3780. continue;
  3781. }
  3782. if (progress_callback) {
  3783. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  3784. return false;
  3785. }
  3786. }
  3787. size_t n_size = ggml_nbytes(cur);
  3788. if (use_mmap) {
  3789. const auto & mapping = mappings.at(weight->idx);
  3790. ggml_backend_buffer_t buf_mmap = nullptr;
  3791. if (bufs_mmap.count(weight->idx)) {
  3792. buf_mmap = bufs_mmap.at(weight->idx);
  3793. }
  3794. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  3795. if (check_tensors) {
  3796. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  3797. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  3798. }));
  3799. }
  3800. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  3801. if (buf_mmap && cur->data == nullptr) {
  3802. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  3803. if (lmlocks) {
  3804. const auto & lmlock = lmlocks->at(weight->idx);
  3805. lmlock->grow_to(weight->offs + n_size);
  3806. }
  3807. auto & mmap_used = mmaps_used[weight->idx];
  3808. mmap_used.first = std::min(mmap_used.first, weight->offs);
  3809. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  3810. } else {
  3811. ggml_backend_tensor_set(cur, data, 0, n_size);
  3812. }
  3813. } else {
  3814. GGML_ASSERT(weight->idx < files.size());
  3815. const auto & file = files.at(weight->idx);
  3816. if (ggml_backend_buffer_is_host(cur->buffer)) {
  3817. file->seek(weight->offs, SEEK_SET);
  3818. file->read_raw(cur->data, n_size);
  3819. if (check_tensors) {
  3820. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  3821. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  3822. }));
  3823. }
  3824. } else {
  3825. #if defined(GGML_USE_CUDA)
  3826. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  3827. if (cuda_backend) {
  3828. file->seek(weight->offs, SEEK_SET);
  3829. size_t bytes_read = 0;
  3830. while (bytes_read < n_size) {
  3831. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  3832. ggml_backend_event_synchronize(events[buffer_idx]);
  3833. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  3834. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  3835. ggml_backend_event_record(events[buffer_idx]);
  3836. bytes_read += read_iteration;
  3837. ++buffer_idx;
  3838. buffer_idx %= n_buffers;
  3839. }
  3840. }
  3841. else
  3842. #endif
  3843. {
  3844. read_buf.resize(n_size);
  3845. file->seek(weight->offs, SEEK_SET);
  3846. file->read_raw(read_buf.data(), n_size);
  3847. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3848. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  3849. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3850. }
  3851. }
  3852. }
  3853. }
  3854. size_done += n_size;
  3855. }
  3856. #if defined(GGML_USE_CUDA)
  3857. // free temporary resources used for async cuda uploads
  3858. if (cuda_backend) {
  3859. for (size_t idx = 0; idx < n_buffers;++idx) {
  3860. ggml_backend_event_synchronize(events[idx]);
  3861. ggml_backend_event_free(events[idx]);
  3862. ggml_backend_buffer_free(host_buffers[idx]);
  3863. }
  3864. ggml_backend_free(cuda_backend);
  3865. }
  3866. #endif
  3867. // check validation results
  3868. bool validation_failed = false;
  3869. for (auto & future : validation_result) {
  3870. auto result = future.get();
  3871. if (!result.second) {
  3872. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  3873. validation_failed = true;
  3874. }
  3875. }
  3876. if (validation_failed) {
  3877. throw std::runtime_error("found tensors with invalid data");
  3878. }
  3879. // check if this is the last call and do final cleanup
  3880. if (size_done >= size_data) {
  3881. // unmap offloaded tensors and metadata
  3882. if (use_mmap) {
  3883. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3884. const auto & mmap_used = mmaps_used.at(idx);
  3885. auto & mapping = mappings.at(idx);
  3886. mapping->unmap_fragment(0, mmap_used.first);
  3887. if (mmap_used.second != 0) {
  3888. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3889. }
  3890. }
  3891. }
  3892. if (progress_callback) {
  3893. // Even though the model is done loading, we still honor
  3894. // cancellation since we need to free allocations.
  3895. return progress_callback(1.0f, progress_callback_user_data);
  3896. }
  3897. }
  3898. return true;
  3899. }
  3900. };
  3901. template<>
  3902. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3903. uint32_t tmp;
  3904. const bool found = get_key(kid, tmp, required);
  3905. if (found) {
  3906. result = (enum llama_pooling_type) tmp;
  3907. } else {
  3908. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3909. }
  3910. return found;
  3911. }
  3912. //
  3913. // load LLaMA models
  3914. //
  3915. static const char * llama_model_arch_name(llm_arch arch) {
  3916. auto it = LLM_ARCH_NAMES.find(arch);
  3917. if (it == LLM_ARCH_NAMES.end()) {
  3918. return "unknown";
  3919. }
  3920. return it->second;
  3921. }
  3922. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3923. if (ftype & LLAMA_FTYPE_GUESSED) {
  3924. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3925. }
  3926. switch (ftype) {
  3927. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3928. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3929. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  3930. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3931. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3932. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3933. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3934. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3935. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3936. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3937. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3938. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3939. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3940. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3941. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3942. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3943. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3944. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3945. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  3946. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3947. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3948. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3949. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3950. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  3951. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  3952. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  3953. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3954. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3955. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3956. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3957. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  3958. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  3959. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  3960. default: return "unknown, may not work";
  3961. }
  3962. }
  3963. static const char * llama_model_type_name(e_model type) {
  3964. switch (type) {
  3965. case MODEL_14M: return "14M";
  3966. case MODEL_17M: return "17M";
  3967. case MODEL_22M: return "22M";
  3968. case MODEL_33M: return "33M";
  3969. case MODEL_60M: return "60M";
  3970. case MODEL_70M: return "70M";
  3971. case MODEL_80M: return "80M";
  3972. case MODEL_109M: return "109M";
  3973. case MODEL_137M: return "137M";
  3974. case MODEL_160M: return "160M";
  3975. case MODEL_220M: return "220M";
  3976. case MODEL_250M: return "250M";
  3977. case MODEL_270M: return "270M";
  3978. case MODEL_335M: return "335M";
  3979. case MODEL_410M: return "410M";
  3980. case MODEL_450M: return "450M";
  3981. case MODEL_770M: return "770M";
  3982. case MODEL_780M: return "780M";
  3983. case MODEL_0_5B: return "0.5B";
  3984. case MODEL_1B: return "1B";
  3985. case MODEL_1_3B: return "1.3B";
  3986. case MODEL_1_4B: return "1.4B";
  3987. case MODEL_2B: return "2B";
  3988. case MODEL_2_8B: return "2.8B";
  3989. case MODEL_3B: return "3B";
  3990. case MODEL_4B: return "4B";
  3991. case MODEL_6B: return "6B";
  3992. case MODEL_6_9B: return "6.9B";
  3993. case MODEL_7B: return "7B";
  3994. case MODEL_8B: return "8B";
  3995. case MODEL_9B: return "9B";
  3996. case MODEL_11B: return "11B";
  3997. case MODEL_12B: return "12B";
  3998. case MODEL_13B: return "13B";
  3999. case MODEL_14B: return "14B";
  4000. case MODEL_15B: return "15B";
  4001. case MODEL_16B: return "16B";
  4002. case MODEL_20B: return "20B";
  4003. case MODEL_30B: return "30B";
  4004. case MODEL_34B: return "34B";
  4005. case MODEL_35B: return "35B";
  4006. case MODEL_40B: return "40B";
  4007. case MODEL_65B: return "65B";
  4008. case MODEL_70B: return "70B";
  4009. case MODEL_236B: return "236B";
  4010. case MODEL_314B: return "314B";
  4011. case MODEL_SMALL: return "0.1B";
  4012. case MODEL_MEDIUM: return "0.4B";
  4013. case MODEL_LARGE: return "0.8B";
  4014. case MODEL_XL: return "1.5B";
  4015. case MODEL_A2_7B: return "A2.7B";
  4016. case MODEL_8x7B: return "8x7B";
  4017. case MODEL_8x22B: return "8x22B";
  4018. case MODEL_16x12B: return "16x12B";
  4019. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4020. case MODEL_57B_A14B: return "57B.A14B";
  4021. case MODEL_27B: return "27B";
  4022. default: return "?B";
  4023. }
  4024. }
  4025. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4026. switch (type) {
  4027. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4028. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4029. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4030. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4031. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4032. default: return "unknown";
  4033. }
  4034. }
  4035. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4036. model.arch = ml.get_arch();
  4037. if (model.arch == LLM_ARCH_UNKNOWN) {
  4038. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4039. }
  4040. }
  4041. static void llm_load_hparams(
  4042. llama_model_loader & ml,
  4043. llama_model & model) {
  4044. auto & hparams = model.hparams;
  4045. const gguf_context * ctx = ml.meta;
  4046. // get metadata as string
  4047. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4048. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4049. if (type == GGUF_TYPE_ARRAY) {
  4050. continue;
  4051. }
  4052. const char * name = gguf_get_key(ctx, i);
  4053. const std::string value = gguf_kv_to_str(ctx, i);
  4054. model.gguf_kv.emplace(name, value);
  4055. }
  4056. // get general kv
  4057. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4058. // get hparams kv
  4059. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4060. // everything past this point is not vocab-related
  4061. if (hparams.vocab_only) {
  4062. return;
  4063. }
  4064. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4065. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4066. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4067. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4068. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4069. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4070. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4071. if (hparams.n_expert > 0) {
  4072. GGML_ASSERT(hparams.n_expert_used > 0);
  4073. } else {
  4074. GGML_ASSERT(hparams.n_expert_used == 0);
  4075. }
  4076. // zero-out the per-layer hparams
  4077. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4078. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4079. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4080. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4081. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4082. // n_head_kv is optional, default to n_head
  4083. hparams.n_head_kv_arr = hparams.n_head_arr;
  4084. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4085. bool rope_finetuned = false;
  4086. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4087. hparams.rope_finetuned = rope_finetuned;
  4088. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4089. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4090. // rope_freq_base (optional)
  4091. hparams.rope_freq_base_train = 10000.0f;
  4092. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4093. std::string rope_scaling("linear");
  4094. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4095. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4096. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4097. // rope_freq_scale (inverse of the kv) is optional
  4098. float ropescale = 0.0f;
  4099. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4100. // try the old key name
  4101. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4102. }
  4103. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4104. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4105. // non-transformer models do not have attention heads
  4106. if (hparams.n_head() > 0) {
  4107. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4108. // gpt-j n_rot = rotary_dim
  4109. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4110. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4111. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  4112. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  4113. // sanity check for n_rot (optional)
  4114. hparams.n_rot = hparams.n_embd_head_k;
  4115. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  4116. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  4117. if (hparams.n_rot != hparams.n_embd_head_k) {
  4118. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  4119. }
  4120. }
  4121. } else {
  4122. hparams.n_rot = 0;
  4123. hparams.n_embd_head_k = 0;
  4124. hparams.n_embd_head_v = 0;
  4125. }
  4126. // arch-specific KVs
  4127. switch (model.arch) {
  4128. case LLM_ARCH_LLAMA:
  4129. {
  4130. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4131. if (hparams.n_expert == 8) {
  4132. switch (hparams.n_layer) {
  4133. case 32: model.type = e_model::MODEL_8x7B; break;
  4134. case 56: model.type = e_model::MODEL_8x22B; break;
  4135. default: model.type = e_model::MODEL_UNKNOWN;
  4136. }
  4137. } else {
  4138. switch (hparams.n_layer) {
  4139. case 22: model.type = e_model::MODEL_1B; break;
  4140. case 26: model.type = e_model::MODEL_3B; break;
  4141. // granite uses a vocab with len 49152
  4142. 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;
  4143. case 36: model.type = e_model::MODEL_8B; break; // granite
  4144. case 40: model.type = e_model::MODEL_13B; break;
  4145. case 48: model.type = e_model::MODEL_34B; break;
  4146. case 60: model.type = e_model::MODEL_30B; break;
  4147. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  4148. default: model.type = e_model::MODEL_UNKNOWN;
  4149. }
  4150. }
  4151. } break;
  4152. case LLM_ARCH_MINICPM:
  4153. {
  4154. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4155. switch (hparams.n_layer) {
  4156. case 40: model.type = e_model::MODEL_2B; break;
  4157. default: model.type = e_model::MODEL_UNKNOWN;
  4158. }
  4159. } break;
  4160. case LLM_ARCH_GROK:
  4161. {
  4162. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4163. switch (hparams.n_layer) {
  4164. case 64: model.type = e_model::MODEL_314B; break;
  4165. default: model.type = e_model::MODEL_UNKNOWN;
  4166. }
  4167. } break;
  4168. case LLM_ARCH_FALCON:
  4169. {
  4170. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4171. switch (hparams.n_layer) {
  4172. case 32: model.type = e_model::MODEL_7B; break;
  4173. case 60: model.type = e_model::MODEL_40B; break;
  4174. default: model.type = e_model::MODEL_UNKNOWN;
  4175. }
  4176. } break;
  4177. case LLM_ARCH_BAICHUAN:
  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_7B; break;
  4182. case 40: model.type = e_model::MODEL_13B; break;
  4183. default: model.type = e_model::MODEL_UNKNOWN;
  4184. }
  4185. if (model.type == e_model::MODEL_13B) {
  4186. // TODO: become GGUF KV parameter
  4187. hparams.f_max_alibi_bias = 8.0f;
  4188. }
  4189. } break;
  4190. case LLM_ARCH_STARCODER:
  4191. {
  4192. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4193. switch (hparams.n_layer) {
  4194. case 24: model.type = e_model::MODEL_1B; break;
  4195. case 36: model.type = e_model::MODEL_3B; break;
  4196. case 42: model.type = e_model::MODEL_7B; break;
  4197. case 40: model.type = e_model::MODEL_15B; break;
  4198. default: model.type = e_model::MODEL_UNKNOWN;
  4199. }
  4200. } break;
  4201. case LLM_ARCH_REFACT:
  4202. {
  4203. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4204. switch (hparams.n_layer) {
  4205. case 32: model.type = e_model::MODEL_1B; break;
  4206. default: model.type = e_model::MODEL_UNKNOWN;
  4207. }
  4208. // TODO: become GGUF KV parameter
  4209. hparams.f_max_alibi_bias = 8.0f;
  4210. } break;
  4211. case LLM_ARCH_BERT:
  4212. {
  4213. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4214. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4215. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4216. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4217. switch (hparams.n_layer) {
  4218. case 3:
  4219. model.type = e_model::MODEL_17M; break; // bge-micro
  4220. case 6:
  4221. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  4222. case 12:
  4223. switch (hparams.n_embd) {
  4224. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  4225. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  4226. } break;
  4227. case 24:
  4228. model.type = e_model::MODEL_335M; break; // bge-large
  4229. }
  4230. } break;
  4231. case LLM_ARCH_JINA_BERT_V2:
  4232. {
  4233. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4234. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4235. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4236. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4237. hparams.f_max_alibi_bias = 8.0f;
  4238. switch (hparams.n_layer) {
  4239. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  4240. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  4241. }
  4242. } break;
  4243. case LLM_ARCH_NOMIC_BERT:
  4244. {
  4245. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4246. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4247. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4248. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4249. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  4250. model.type = e_model::MODEL_137M;
  4251. }
  4252. } break;
  4253. case LLM_ARCH_BLOOM:
  4254. {
  4255. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4256. switch (hparams.n_layer) {
  4257. case 24: model.type = e_model::MODEL_1B; break;
  4258. case 30:
  4259. switch (hparams.n_embd) {
  4260. case 2560: model.type = e_model::MODEL_3B; break;
  4261. case 4096: model.type = e_model::MODEL_7B; break;
  4262. } break;
  4263. }
  4264. // TODO: become GGUF KV parameter
  4265. hparams.f_max_alibi_bias = 8.0f;
  4266. } break;
  4267. case LLM_ARCH_MPT:
  4268. {
  4269. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4270. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4271. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4272. switch (hparams.n_layer) {
  4273. case 32: model.type = e_model::MODEL_7B; break;
  4274. case 48: model.type = e_model::MODEL_30B; break;
  4275. default: model.type = e_model::MODEL_UNKNOWN;
  4276. }
  4277. } break;
  4278. case LLM_ARCH_STABLELM:
  4279. {
  4280. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4281. switch (hparams.n_layer) {
  4282. case 24: model.type = e_model::MODEL_1B; break;
  4283. case 32: model.type = e_model::MODEL_3B; break;
  4284. case 40: model.type = e_model::MODEL_12B; break;
  4285. default: model.type = e_model::MODEL_UNKNOWN;
  4286. }
  4287. } break;
  4288. case LLM_ARCH_QWEN:
  4289. {
  4290. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4291. switch (hparams.n_layer) {
  4292. case 32: model.type = e_model::MODEL_7B; break;
  4293. case 40: model.type = e_model::MODEL_13B; break;
  4294. default: model.type = e_model::MODEL_UNKNOWN;
  4295. }
  4296. } break;
  4297. case LLM_ARCH_QWEN2:
  4298. {
  4299. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4300. switch (hparams.n_layer) {
  4301. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  4302. case 32: model.type = e_model::MODEL_7B; break;
  4303. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  4304. case 80: model.type = e_model::MODEL_70B; break;
  4305. default: model.type = e_model::MODEL_UNKNOWN;
  4306. }
  4307. } break;
  4308. case LLM_ARCH_QWEN2MOE:
  4309. {
  4310. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  4311. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  4312. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4313. switch (hparams.n_layer) {
  4314. case 24: model.type = e_model::MODEL_A2_7B; break;
  4315. case 28: model.type = e_model::MODEL_57B_A14B; break;
  4316. default: model.type = e_model::MODEL_UNKNOWN;
  4317. }
  4318. } break;
  4319. case LLM_ARCH_PHI2:
  4320. {
  4321. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4322. switch (hparams.n_layer) {
  4323. case 24: model.type = e_model::MODEL_1B; break;
  4324. case 32: model.type = e_model::MODEL_3B; break;
  4325. default: model.type = e_model::MODEL_UNKNOWN;
  4326. }
  4327. } break;
  4328. case LLM_ARCH_PHI3:
  4329. {
  4330. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);
  4331. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4332. switch (hparams.n_layer) {
  4333. case 24: model.type = e_model::MODEL_1B; break;
  4334. case 32: model.type = e_model::MODEL_3B; break;
  4335. case 40: model.type = e_model::MODEL_14B; break;
  4336. default: model.type = e_model::MODEL_UNKNOWN;
  4337. }
  4338. } break;
  4339. case LLM_ARCH_PLAMO:
  4340. {
  4341. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4342. switch (hparams.n_layer) {
  4343. case 40: model.type = e_model::MODEL_13B; break;
  4344. default: model.type = e_model::MODEL_UNKNOWN;
  4345. }
  4346. } break;
  4347. case LLM_ARCH_GPT2:
  4348. {
  4349. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4350. switch (hparams.n_layer) {
  4351. case 12: model.type = e_model::MODEL_SMALL; break;
  4352. case 24: model.type = e_model::MODEL_MEDIUM; break;
  4353. case 36: model.type = e_model::MODEL_LARGE; break;
  4354. case 48: model.type = e_model::MODEL_XL; break;
  4355. default: model.type = e_model::MODEL_UNKNOWN;
  4356. }
  4357. } break;
  4358. case LLM_ARCH_CODESHELL:
  4359. {
  4360. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4361. switch (hparams.n_layer) {
  4362. case 42: model.type = e_model::MODEL_7B; break;
  4363. default: model.type = e_model::MODEL_UNKNOWN;
  4364. }
  4365. } break;
  4366. case LLM_ARCH_ORION:
  4367. {
  4368. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4369. switch (hparams.n_layer) {
  4370. case 40: model.type = e_model::MODEL_14B; break;
  4371. default: model.type = e_model::MODEL_UNKNOWN;
  4372. }
  4373. } break;
  4374. case LLM_ARCH_INTERNLM2:
  4375. {
  4376. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4377. switch (hparams.n_layer) {
  4378. case 32: model.type = e_model::MODEL_7B; break;
  4379. case 48: model.type = e_model::MODEL_20B; break;
  4380. default: model.type = e_model::MODEL_UNKNOWN;
  4381. }
  4382. } break;
  4383. case LLM_ARCH_GEMMA:
  4384. {
  4385. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4386. switch (hparams.n_layer) {
  4387. case 18: model.type = e_model::MODEL_2B; break;
  4388. case 28: model.type = e_model::MODEL_7B; break;
  4389. default: model.type = e_model::MODEL_UNKNOWN;
  4390. }
  4391. } break;
  4392. case LLM_ARCH_GEMMA2:
  4393. {
  4394. hparams.n_swa = 4096; // default value of gemma 2
  4395. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  4396. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4397. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  4398. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  4399. hparams.attn_soft_cap = true;
  4400. switch (hparams.n_layer) {
  4401. case 26: model.type = e_model::MODEL_2B; break;
  4402. case 42: model.type = e_model::MODEL_9B; break;
  4403. case 46: model.type = e_model::MODEL_27B; break;
  4404. default: model.type = e_model::MODEL_UNKNOWN;
  4405. }
  4406. } break;
  4407. case LLM_ARCH_STARCODER2:
  4408. {
  4409. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4410. switch (hparams.n_layer) {
  4411. case 30: model.type = e_model::MODEL_3B; break;
  4412. case 32: model.type = e_model::MODEL_7B; break;
  4413. case 40: model.type = e_model::MODEL_15B; break;
  4414. case 52: model.type = e_model::MODEL_20B; break; // granite
  4415. case 88: model.type = e_model::MODEL_34B; break; // granite
  4416. default: model.type = e_model::MODEL_UNKNOWN;
  4417. }
  4418. } break;
  4419. case LLM_ARCH_MAMBA:
  4420. {
  4421. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  4422. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  4423. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  4424. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  4425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4426. switch (hparams.n_layer) {
  4427. case 24:
  4428. switch (hparams.n_embd) {
  4429. case 768: model.type = e_model::MODEL_SMALL; break;
  4430. default: model.type = e_model::MODEL_UNKNOWN;
  4431. } break;
  4432. case 48:
  4433. switch (hparams.n_embd) {
  4434. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  4435. case 1536: model.type = e_model::MODEL_LARGE; break;
  4436. case 2048: model.type = e_model::MODEL_XL; break;
  4437. default: model.type = e_model::MODEL_UNKNOWN;
  4438. } break;
  4439. case 64:
  4440. switch (hparams.n_embd) {
  4441. case 2560: model.type = e_model::MODEL_3B; break;
  4442. default: model.type = e_model::MODEL_UNKNOWN;
  4443. } break;
  4444. default: model.type = e_model::MODEL_UNKNOWN;
  4445. }
  4446. } break;
  4447. case LLM_ARCH_XVERSE:
  4448. {
  4449. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4450. switch (hparams.n_layer) {
  4451. case 32: model.type = e_model::MODEL_7B; break;
  4452. case 40: model.type = e_model::MODEL_13B; break;
  4453. case 80: model.type = e_model::MODEL_65B; break;
  4454. default: model.type = e_model::MODEL_UNKNOWN;
  4455. }
  4456. } break;
  4457. case LLM_ARCH_COMMAND_R:
  4458. {
  4459. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  4460. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4461. switch (hparams.n_layer) {
  4462. case 40: model.type = e_model::MODEL_35B; break;
  4463. default: model.type = e_model::MODEL_UNKNOWN;
  4464. }
  4465. } break;
  4466. case LLM_ARCH_DBRX:
  4467. {
  4468. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4469. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  4470. switch (hparams.n_layer) {
  4471. case 40: model.type = e_model::MODEL_16x12B; break;
  4472. default: model.type = e_model::MODEL_UNKNOWN;
  4473. }
  4474. } break;
  4475. case LLM_ARCH_OLMO:
  4476. {
  4477. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4478. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4479. switch (hparams.n_layer) {
  4480. case 22: model.type = e_model::MODEL_1B; break;
  4481. case 32: model.type = e_model::MODEL_7B; break;
  4482. case 80: model.type = e_model::MODEL_70B; break;
  4483. default: model.type = e_model::MODEL_UNKNOWN;
  4484. }
  4485. } break;
  4486. case LLM_ARCH_OPENELM:
  4487. {
  4488. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4489. switch (hparams.n_layer) {
  4490. case 16: model.type = e_model::MODEL_270M; break;
  4491. case 20: model.type = e_model::MODEL_450M; break;
  4492. case 28: model.type = e_model::MODEL_1B; break;
  4493. case 36: model.type = e_model::MODEL_3B; break;
  4494. default: model.type = e_model::MODEL_UNKNOWN;
  4495. }
  4496. } break;
  4497. case LLM_ARCH_GPTNEOX:
  4498. {
  4499. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4500. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  4501. switch (hparams.n_layer) {
  4502. case 6:
  4503. switch (hparams.n_ff()) {
  4504. case 512: model.type = e_model::MODEL_14M; break;
  4505. case 2048: model.type = e_model::MODEL_70M; break;
  4506. default: model.type = e_model::MODEL_UNKNOWN;
  4507. } break;
  4508. case 12:
  4509. switch (hparams.n_ff()) {
  4510. case 3072: model.type = e_model::MODEL_160M; break;
  4511. default: model.type = e_model::MODEL_UNKNOWN;
  4512. } break;
  4513. case 16:
  4514. switch (hparams.n_ff()) {
  4515. case 8192: model.type = e_model::MODEL_1B; break;
  4516. default: model.type = e_model::MODEL_UNKNOWN;
  4517. } break;
  4518. case 24:
  4519. switch (hparams.n_ff()) {
  4520. case 4096: model.type = e_model::MODEL_410M; break;
  4521. case 8192: model.type = e_model::MODEL_1_4B; break;
  4522. default: model.type = e_model::MODEL_UNKNOWN;
  4523. } break;
  4524. case 32:
  4525. switch (hparams.n_ff()) {
  4526. case 10240: model.type = e_model::MODEL_2_8B; break;
  4527. case 16384: model.type = e_model::MODEL_6_9B; break;
  4528. default: model.type = e_model::MODEL_UNKNOWN;
  4529. } break;
  4530. case 36:
  4531. switch (hparams.n_ff()) {
  4532. case 20480: model.type = e_model::MODEL_12B; break;
  4533. default: model.type = e_model::MODEL_UNKNOWN;
  4534. } break;
  4535. case 44:
  4536. switch (hparams.n_ff()) {
  4537. case 24576: model.type = e_model::MODEL_20B; break;
  4538. default: model.type = e_model::MODEL_UNKNOWN;
  4539. } break;
  4540. default: model.type = e_model::MODEL_UNKNOWN;
  4541. }
  4542. } break;
  4543. case LLM_ARCH_ARCTIC:
  4544. {
  4545. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4546. if (hparams.n_expert == 128) {
  4547. switch (hparams.n_layer) {
  4548. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  4549. default: model.type = e_model::MODEL_UNKNOWN;
  4550. }
  4551. } else {
  4552. model.type = e_model::MODEL_UNKNOWN;
  4553. }
  4554. } break;
  4555. case LLM_ARCH_DEEPSEEK2:
  4556. {
  4557. bool is_lite = (hparams.n_layer == 27);
  4558. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4559. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  4560. if (!is_lite) {
  4561. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  4562. }
  4563. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  4564. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  4565. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  4566. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  4567. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  4568. switch (hparams.n_layer) {
  4569. case 27: model.type = e_model::MODEL_16B; break;
  4570. case 60: model.type = e_model::MODEL_236B; break;
  4571. default: model.type = e_model::MODEL_UNKNOWN;
  4572. }
  4573. } break;
  4574. case LLM_ARCH_CHATGLM:
  4575. {
  4576. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4577. switch (hparams.n_layer) {
  4578. case 28: model.type = e_model::MODEL_6B; break;
  4579. case 40: model.type = e_model::MODEL_9B; break;
  4580. default: model.type = e_model::MODEL_UNKNOWN;
  4581. }
  4582. } break;
  4583. case LLM_ARCH_BITNET:
  4584. {
  4585. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4586. switch (hparams.n_layer) {
  4587. case 26: model.type = e_model::MODEL_3B; break;
  4588. default: model.type = e_model::MODEL_UNKNOWN;
  4589. }
  4590. } break;
  4591. case LLM_ARCH_T5:
  4592. {
  4593. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4594. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  4595. uint32_t dec_start_token_id;
  4596. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  4597. hparams.dec_start_token_id = dec_start_token_id;
  4598. }
  4599. switch (hparams.n_layer) {
  4600. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  4601. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  4602. case 12:
  4603. switch (hparams.n_ff()) {
  4604. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  4605. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  4606. default: model.type = e_model::MODEL_UNKNOWN;
  4607. } break;
  4608. case 24:
  4609. switch (hparams.n_ff()) {
  4610. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  4611. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  4612. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  4613. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  4614. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  4615. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  4616. default: model.type = e_model::MODEL_UNKNOWN;
  4617. } break;
  4618. default: model.type = e_model::MODEL_UNKNOWN;
  4619. }
  4620. } break;
  4621. case LLM_ARCH_JAIS:
  4622. {
  4623. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4624. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4625. switch (hparams.n_layer) {
  4626. case 24: model.type = e_model::MODEL_1_3B; break;
  4627. case 40: model.type = e_model::MODEL_13B; break;
  4628. /* TODO: add variants */
  4629. default: model.type = e_model::MODEL_UNKNOWN;
  4630. }
  4631. } break;
  4632. default: (void)0;
  4633. }
  4634. model.ftype = ml.ftype;
  4635. if (hparams.f_max_alibi_bias > 0.0f) {
  4636. hparams.use_alibi = true;
  4637. }
  4638. hparams.rope_type = llama_rope_type(&model);
  4639. }
  4640. static void llm_load_vocab(
  4641. llama_model_loader & ml,
  4642. llama_model & model) {
  4643. auto & vocab = model.vocab;
  4644. struct gguf_context * ctx = ml.meta;
  4645. const auto kv = LLM_KV(model.arch);
  4646. // determine vocab type
  4647. {
  4648. std::string tokenizer_model;
  4649. std::string tokenizer_pre;
  4650. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  4651. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  4652. if (tokenizer_model == "no_vocab") {
  4653. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  4654. // default special tokens
  4655. vocab.special_bos_id = -1;
  4656. vocab.special_eos_id = -1;
  4657. vocab.special_unk_id = -1;
  4658. vocab.special_sep_id = -1;
  4659. vocab.special_pad_id = -1;
  4660. vocab.special_cls_id = -1;
  4661. vocab.special_mask_id = -1;
  4662. vocab.linefeed_id = -1;
  4663. return;
  4664. } else if (tokenizer_model == "llama") {
  4665. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  4666. // default special tokens
  4667. vocab.special_bos_id = 1;
  4668. vocab.special_eos_id = 2;
  4669. vocab.special_unk_id = 0;
  4670. vocab.special_sep_id = -1;
  4671. vocab.special_pad_id = -1;
  4672. vocab.special_cls_id = -1;
  4673. vocab.special_mask_id = -1;
  4674. } else if (tokenizer_model == "bert") {
  4675. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  4676. // default special tokens
  4677. vocab.special_bos_id = -1;
  4678. vocab.special_eos_id = -1;
  4679. vocab.special_unk_id = 100;
  4680. vocab.special_sep_id = 102;
  4681. vocab.special_pad_id = 0;
  4682. vocab.special_cls_id = 101;
  4683. vocab.special_mask_id = 103;
  4684. } else if (tokenizer_model == "gpt2") {
  4685. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  4686. // read bpe merges and populate bpe ranks
  4687. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  4688. if (merges_keyidx == -1) {
  4689. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  4690. }
  4691. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  4692. for (int i = 0; i < n_merges; i++) {
  4693. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  4694. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4695. std::string first;
  4696. std::string second;
  4697. const size_t pos = word.find(' ', 1);
  4698. if (pos != std::string::npos) {
  4699. first = word.substr(0, pos);
  4700. second = word.substr(pos + 1);
  4701. }
  4702. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  4703. }
  4704. // default special tokens
  4705. vocab.special_bos_id = 11;
  4706. vocab.special_eos_id = 11;
  4707. vocab.special_unk_id = -1;
  4708. vocab.special_sep_id = -1;
  4709. vocab.special_pad_id = -1;
  4710. vocab.special_cls_id = -1;
  4711. vocab.special_mask_id = -1;
  4712. } else if (tokenizer_model == "t5") {
  4713. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  4714. // default special tokens
  4715. vocab.special_bos_id = -1;
  4716. vocab.special_eos_id = 1;
  4717. vocab.special_unk_id = 2;
  4718. vocab.special_sep_id = -1;
  4719. vocab.special_pad_id = 0;
  4720. vocab.special_cls_id = -1;
  4721. vocab.special_mask_id = -1;
  4722. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  4723. if (precompiled_charsmap_keyidx != -1) {
  4724. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  4725. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  4726. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  4727. #ifdef IS_BIG_ENDIAN
  4728. // correct endiannes of data in precompiled_charsmap binary blob
  4729. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  4730. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  4731. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  4732. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  4733. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  4734. for (size_t i = 0; i < xcda_array_size; ++i) {
  4735. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  4736. }
  4737. #endif
  4738. }
  4739. } else {
  4740. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  4741. }
  4742. // for now, only BPE models have pre-tokenizers
  4743. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  4744. vocab.tokenizer_add_space_prefix = false;
  4745. vocab.tokenizer_clean_spaces = true;
  4746. if (tokenizer_pre == "default") {
  4747. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4748. } else if (
  4749. tokenizer_pre == "llama3" ||
  4750. tokenizer_pre == "llama-v3" ||
  4751. tokenizer_pre == "llama-bpe") {
  4752. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  4753. vocab.tokenizer_ignore_merges = true;
  4754. vocab.tokenizer_add_bos = true;
  4755. } else if (
  4756. tokenizer_pre == "deepseek-llm") {
  4757. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  4758. vocab.tokenizer_clean_spaces = false;
  4759. } else if (
  4760. tokenizer_pre == "deepseek-coder") {
  4761. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  4762. vocab.tokenizer_clean_spaces = false;
  4763. } else if (
  4764. tokenizer_pre == "falcon") {
  4765. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  4766. } else if (
  4767. tokenizer_pre == "mpt") {
  4768. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  4769. } else if (
  4770. tokenizer_pre == "starcoder") {
  4771. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  4772. } else if (
  4773. tokenizer_pre == "gpt-2" ||
  4774. tokenizer_pre == "phi-2" ||
  4775. tokenizer_pre == "jina-es" ||
  4776. tokenizer_pre == "jina-de" ||
  4777. tokenizer_pre == "jina-v2-es" ||
  4778. tokenizer_pre == "jina-v2-de" ||
  4779. tokenizer_pre == "jina-v2-code") {
  4780. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  4781. } else if (
  4782. tokenizer_pre == "refact") {
  4783. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  4784. } else if (
  4785. tokenizer_pre == "command-r") {
  4786. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  4787. vocab.tokenizer_clean_spaces = false;
  4788. } else if (
  4789. tokenizer_pre == "qwen2") {
  4790. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  4791. vocab.tokenizer_clean_spaces = false;
  4792. } else if (
  4793. tokenizer_pre == "stablelm2") {
  4794. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  4795. } else if (
  4796. tokenizer_pre == "olmo") {
  4797. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  4798. } else if (
  4799. tokenizer_pre == "dbrx") {
  4800. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  4801. } else if (
  4802. tokenizer_pre == "smaug-bpe") {
  4803. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  4804. } else if (
  4805. tokenizer_pre == "poro-chat") {
  4806. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  4807. vocab.tokenizer_clean_spaces = false;
  4808. } else if (
  4809. tokenizer_pre == "chatglm-bpe") {
  4810. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  4811. vocab.special_bos_id = -1;
  4812. } else if (
  4813. tokenizer_pre == "viking") {
  4814. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  4815. vocab.tokenizer_clean_spaces = false;
  4816. } else if (
  4817. tokenizer_pre == "jais") {
  4818. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  4819. } else if (
  4820. tokenizer_pre == "tekken") {
  4821. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  4822. vocab.tokenizer_clean_spaces = false;
  4823. vocab.tokenizer_ignore_merges = true;
  4824. vocab.tokenizer_add_bos = true;
  4825. } else if (
  4826. tokenizer_pre == "smollm") {
  4827. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  4828. vocab.tokenizer_clean_spaces = false;
  4829. } else if (
  4830. tokenizer_pre == "codeshell") {
  4831. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  4832. } else {
  4833. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  4834. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4835. }
  4836. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4837. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4838. vocab.tokenizer_add_space_prefix = true;
  4839. vocab.tokenizer_clean_spaces = false;
  4840. vocab.tokenizer_add_bos = true;
  4841. vocab.tokenizer_add_eos = false;
  4842. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4843. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4844. vocab.tokenizer_add_space_prefix = false;
  4845. vocab.tokenizer_clean_spaces = true;
  4846. vocab.tokenizer_add_bos = true;
  4847. vocab.tokenizer_add_eos = false;
  4848. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  4849. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4850. vocab.tokenizer_add_bos = false;
  4851. vocab.tokenizer_add_eos = true;
  4852. } else {
  4853. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4854. }
  4855. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  4856. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  4857. }
  4858. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  4859. if (token_idx == -1) {
  4860. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  4861. }
  4862. const float * scores = nullptr;
  4863. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  4864. if (score_idx != -1) {
  4865. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  4866. }
  4867. const int * toktypes = nullptr;
  4868. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  4869. if (toktype_idx != -1) {
  4870. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  4871. }
  4872. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  4873. vocab.id_to_token.resize(n_vocab);
  4874. for (uint32_t i = 0; i < n_vocab; i++) {
  4875. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  4876. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4877. vocab.token_to_id[word] = i;
  4878. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  4879. auto & token_data = vocab.id_to_token[i];
  4880. token_data.text = std::move(word);
  4881. token_data.score = scores ? scores[i] : 0.0f;
  4882. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  4883. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  4884. switch(toktypes[i]) {
  4885. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  4886. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  4887. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  4888. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  4889. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  4890. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  4891. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4892. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4893. }
  4894. }
  4895. }
  4896. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  4897. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  4898. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4899. // For Fill-In-the-Middle (FIM)/infill models which where converted
  4900. // prior to support of FIM special tokens in GGUF, the following
  4901. // will allow those models to continue to work. The general names
  4902. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  4903. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  4904. // new versions of these models have been published.
  4905. std::string gen_name;
  4906. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  4907. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  4908. [](unsigned char c){ return std::tolower(c); });
  4909. if (gen_name.find("code") != std::string::npos) {
  4910. if (model.arch == LLM_ARCH_LLAMA
  4911. && 32010 < vocab.id_to_token.size()
  4912. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  4913. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  4914. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  4915. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  4916. vocab.special_prefix_id = 32007;
  4917. vocab.special_suffix_id = 32008;
  4918. vocab.special_middle_id = 32009;
  4919. vocab.special_eot_id = 32010;
  4920. } else if (model.arch == LLM_ARCH_GEMMA
  4921. && 107 < vocab.id_to_token.size()
  4922. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  4923. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  4924. && vocab.id_to_token[68].text == "<|fim_middle|>"
  4925. && vocab.id_to_token[107].text == "<end_of_turn>") {
  4926. vocab.special_prefix_id = 67;
  4927. vocab.special_suffix_id = 69;
  4928. vocab.special_middle_id = 68;
  4929. // TODO: this is not EOT, it is "file separator" token, needs fix
  4930. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  4931. //vocab.special_eot_id = 70;
  4932. vocab.special_eot_id = 107;
  4933. }
  4934. }
  4935. try {
  4936. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  4937. } catch (const std::exception & e) {
  4938. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  4939. vocab.linefeed_id = vocab.special_pad_id;
  4940. }
  4941. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4942. vocab.linefeed_id = vocab.special_pad_id;
  4943. } else {
  4944. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  4945. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  4946. vocab.linefeed_id = ids[0];
  4947. }
  4948. // special tokens
  4949. {
  4950. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  4951. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  4952. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  4953. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  4954. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  4955. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  4956. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  4957. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  4958. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  4959. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  4960. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  4961. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  4962. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  4963. };
  4964. for (const auto & it : special_token_types) {
  4965. const std::string & key = kv(std::get<0>(it));
  4966. int32_t & id = std::get<1>(it);
  4967. uint32_t new_id;
  4968. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  4969. continue;
  4970. }
  4971. if (new_id >= vocab.id_to_token.size()) {
  4972. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  4973. __func__, key.c_str(), new_id, id);
  4974. } else {
  4975. id = new_id;
  4976. }
  4977. }
  4978. // Handle add_bos_token and add_eos_token
  4979. {
  4980. bool temp = true;
  4981. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  4982. vocab.tokenizer_add_bos = temp;
  4983. }
  4984. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  4985. vocab.tokenizer_add_eos = temp;
  4986. }
  4987. }
  4988. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  4989. //
  4990. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  4991. // for now, we apply this workaround to find the EOT token based on its text
  4992. if (vocab.special_eot_id == -1) {
  4993. for (const auto & t : vocab.token_to_id) {
  4994. if (
  4995. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  4996. // need to fix convert script
  4997. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  4998. (t.first == "<|eot_id|>" ||
  4999. t.first == "<|im_end|>" ||
  5000. t.first == "<|end|>" ||
  5001. t.first == "<end_of_turn>" ||
  5002. t.first == "<|endoftext|>"
  5003. )
  5004. ) {
  5005. vocab.special_eot_id = t.second;
  5006. break;
  5007. }
  5008. }
  5009. }
  5010. // find EOM token: "<|eom_id|>"
  5011. //
  5012. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOM_ID
  5013. // for now, we apply this workaround to find the EOM token based on its text
  5014. if (vocab.special_eom_id == -1) {
  5015. const auto & t = vocab.token_to_id.find("<|eom_id|>");
  5016. if (t != vocab.token_to_id.end()) {
  5017. vocab.special_eom_id = t->second;
  5018. }
  5019. }
  5020. }
  5021. // build special tokens cache
  5022. {
  5023. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  5024. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  5025. vocab.cache_special_tokens.push_back(id);
  5026. }
  5027. }
  5028. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  5029. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  5030. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  5031. }
  5032. );
  5033. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  5034. }
  5035. // build token to piece cache
  5036. {
  5037. size_t size_cache = 0;
  5038. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  5039. for (uint32_t id = 0; id < n_vocab; ++id) {
  5040. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  5041. size_cache += cache_token_to_piece[id].size();
  5042. }
  5043. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  5044. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  5045. }
  5046. // Handle per token attributes
  5047. //NOTE: Each model customizes per token attributes.
  5048. //NOTE: Per token attributes are missing from the GGUF file.
  5049. //TODO: Extract attributes from GGUF file.
  5050. {
  5051. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  5052. for (auto substr : substrs) {
  5053. if (str.find(substr) < std::string::npos) {
  5054. return true;
  5055. }
  5056. }
  5057. return false;
  5058. };
  5059. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  5060. uint32_t current = vocab.id_to_token.at(id).attr;
  5061. current = value ? (current | attr) : (current & ~attr);
  5062. vocab.id_to_token[id].attr = (llama_token_attr) current;
  5063. };
  5064. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  5065. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  5066. };
  5067. std::string model_name;
  5068. std::string tokenizer_pre;
  5069. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  5070. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5071. // model name to lowercase
  5072. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  5073. [] (const std::string::value_type x) {
  5074. return std::tolower(x);
  5075. }
  5076. );
  5077. // set attributes by model/tokenizer name
  5078. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  5079. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  5080. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  5081. for (auto id : vocab.cache_special_tokens) {
  5082. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5083. }
  5084. for (auto token : {"</s>"}) {
  5085. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5086. }
  5087. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  5088. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  5089. }
  5090. }
  5091. }
  5092. }
  5093. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  5094. const auto & hparams = model.hparams;
  5095. const auto & vocab = model.vocab;
  5096. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  5097. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  5098. bool is_var = false;
  5099. std::vector<uint32_t> v;
  5100. for (uint32_t i = 0; i < n; ++i) {
  5101. v.push_back(f(i));
  5102. if (v[i] != v[0]) {
  5103. is_var = true;
  5104. }
  5105. }
  5106. std::stringstream ss;
  5107. if (is_var) {
  5108. ss << "[";
  5109. for (uint32_t i = 0; i < n; ++i) {
  5110. ss << v[i];
  5111. if (i < n - 1) {
  5112. ss << ", ";
  5113. }
  5114. }
  5115. ss << "]";
  5116. } else {
  5117. ss << v[0];
  5118. }
  5119. return ss.str();
  5120. };
  5121. // hparams
  5122. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  5123. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  5124. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  5125. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  5126. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  5127. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  5128. if (!hparams.vocab_only) {
  5129. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  5130. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  5131. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  5132. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  5133. 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());
  5134. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  5135. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  5136. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  5137. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  5138. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  5139. 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());
  5140. 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());
  5141. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  5142. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  5143. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  5144. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  5145. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  5146. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  5147. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  5148. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  5149. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  5150. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  5151. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  5152. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  5153. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  5154. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  5155. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  5156. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  5157. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  5158. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  5159. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  5160. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  5161. }
  5162. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  5163. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  5164. if (ml.n_elements >= 1e12) {
  5165. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  5166. } else if (ml.n_elements >= 1e9) {
  5167. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  5168. } else if (ml.n_elements >= 1e6) {
  5169. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  5170. } else {
  5171. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  5172. }
  5173. if (ml.n_bytes < GiB) {
  5174. 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);
  5175. } else {
  5176. 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);
  5177. }
  5178. // general kv
  5179. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  5180. // special tokens
  5181. 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() ); }
  5182. 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() ); }
  5183. 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() ); }
  5184. 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() ); }
  5185. 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() ); }
  5186. 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() ); }
  5187. 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() ); }
  5188. 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() ); }
  5189. 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() ); }
  5190. 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() ); }
  5191. 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() ); }
  5192. 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() ); }
  5193. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  5194. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  5195. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  5196. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  5197. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  5198. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5199. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  5200. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  5201. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  5202. }
  5203. if (model.arch == LLM_ARCH_QWEN2MOE) {
  5204. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5205. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  5206. }
  5207. }
  5208. // Returns false if cancelled by progress_callback
  5209. static bool llm_load_tensors(
  5210. llama_model_loader & ml,
  5211. llama_model & model,
  5212. int n_gpu_layers,
  5213. enum llama_split_mode split_mode,
  5214. int main_gpu,
  5215. const float * tensor_split,
  5216. bool use_mlock,
  5217. llama_progress_callback progress_callback,
  5218. void * progress_callback_user_data) {
  5219. model.t_start_us = ggml_time_us();
  5220. auto & hparams = model.hparams;
  5221. model.split_mode = split_mode;
  5222. model.main_gpu = main_gpu;
  5223. model.n_gpu_layers = n_gpu_layers;
  5224. const int n_layer = hparams.n_layer;
  5225. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  5226. bool use_mmap_buffer = true;
  5227. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  5228. model.buft_input = llama_default_buffer_type_cpu(true);
  5229. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  5230. model.buft_layer.resize(n_layer);
  5231. // assign cpu layers
  5232. for (int i = 0; i < i_gpu_start; ++i) {
  5233. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  5234. }
  5235. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  5236. // calculate the split points
  5237. int device_count = llama_get_device_count(model);
  5238. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  5239. std::vector<float> splits(device_count);
  5240. if (all_zero) {
  5241. // default split, by free memory
  5242. for (int i = 0; i < device_count; ++i) {
  5243. splits[i] = llama_get_device_memory(model, i);
  5244. }
  5245. } else {
  5246. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  5247. }
  5248. // sum and normalize the splits to get the split points
  5249. float split_sum = 0.0f;
  5250. for (int i = 0; i < device_count; ++i) {
  5251. split_sum += splits[i];
  5252. splits[i] = split_sum;
  5253. }
  5254. for (int i = 0; i < device_count; ++i) {
  5255. splits[i] /= split_sum;
  5256. }
  5257. // assign the repeating layers to the devices according to the splits
  5258. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  5259. for (int i = i_gpu_start; i < n_layer; ++i) {
  5260. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  5261. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  5262. }
  5263. // assign the output layer
  5264. if (n_gpu_layers > n_layer) {
  5265. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  5266. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  5267. } else {
  5268. model.buft_output = llama_default_buffer_type_cpu(true);
  5269. }
  5270. } else {
  5271. ggml_backend_buffer_type_t split_buft;
  5272. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  5273. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  5274. } else {
  5275. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  5276. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  5277. }
  5278. // assign the repeating layers
  5279. for (int i = i_gpu_start; i < n_layer; ++i) {
  5280. model.buft_layer[i] = {
  5281. split_buft,
  5282. llama_default_buffer_type_offload(model, main_gpu)
  5283. };
  5284. }
  5285. // assign the output layer
  5286. if (n_gpu_layers > n_layer) {
  5287. model.buft_output = {
  5288. split_buft,
  5289. llama_default_buffer_type_offload(model, main_gpu)
  5290. };
  5291. } else {
  5292. model.buft_output = llama_default_buffer_type_cpu(true);
  5293. }
  5294. }
  5295. // count used buffer types
  5296. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  5297. buft_layer_count[model.buft_input.buft]++;
  5298. buft_layer_count[model.buft_input.buft_matrix]++;
  5299. buft_layer_count[model.buft_output.buft]++;
  5300. buft_layer_count[model.buft_output.buft_matrix]++;
  5301. for (int i = 0; i < n_layer; ++i) {
  5302. buft_layer_count[model.buft_layer[i].buft]++;
  5303. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  5304. }
  5305. // create one context per buffer type
  5306. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  5307. // for moe merged tensors
  5308. ctx_size += ggml_tensor_overhead()*n_layer*3;
  5309. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  5310. for (auto & it : buft_layer_count) {
  5311. struct ggml_init_params params = {
  5312. /*.mem_size =*/ ctx_size,
  5313. /*.mem_buffer =*/ NULL,
  5314. /*.no_alloc =*/ true,
  5315. };
  5316. ggml_context * ctx = ggml_init(params);
  5317. if (!ctx) {
  5318. throw std::runtime_error(format("failed to create context"));
  5319. }
  5320. ctx_map[it.first] = ctx;
  5321. model.ctxs.push_back(ctx);
  5322. }
  5323. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  5324. // create tensors for the weights
  5325. {
  5326. // note: cast to int64_t since we will use these for the tensor dimensions
  5327. const int64_t n_head = hparams.n_head();
  5328. const int64_t n_head_kv = hparams.n_head_kv();
  5329. const int64_t n_embd = hparams.n_embd;
  5330. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5331. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5332. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5333. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5334. const int64_t n_ff = hparams.n_ff();
  5335. const int64_t n_embd_gqa = n_embd_v_gqa;
  5336. const int64_t n_vocab = hparams.n_vocab;
  5337. const int64_t n_vocab_type = hparams.n_vocab_type;
  5338. const int64_t n_expert = hparams.n_expert;
  5339. const int64_t n_expert_used = hparams.n_expert_used;
  5340. const int64_t n_ctx_train = hparams.n_ctx_train;
  5341. if (n_expert > 0 && hparams.n_expert_used == 0) {
  5342. throw std::runtime_error("model has expert layers but no expert layers are used");
  5343. }
  5344. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  5345. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  5346. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  5347. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  5348. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  5349. model.layers.resize(n_layer);
  5350. const auto tn = LLM_TN(model.arch);
  5351. switch (model.arch) {
  5352. case LLM_ARCH_LLAMA:
  5353. case LLM_ARCH_REFACT:
  5354. case LLM_ARCH_MINICPM:
  5355. {
  5356. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5357. // output
  5358. {
  5359. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5360. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5361. // if output is NULL, init from the input tok embed
  5362. if (model.output == NULL) {
  5363. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5364. }
  5365. }
  5366. for (int i = 0; i < n_layer; ++i) {
  5367. ggml_context * ctx_layer = ctx_for_layer(i);
  5368. ggml_context * ctx_split = ctx_for_layer_split(i);
  5369. auto & layer = model.layers[i];
  5370. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5371. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  5372. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5373. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5374. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  5375. // optional bias tensors
  5376. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5377. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5378. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5379. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5380. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5381. 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));
  5382. if (n_expert == 0) {
  5383. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5384. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5385. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5386. // optional MLP bias
  5387. layer.ffn_gate_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5388. layer.ffn_down_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5389. layer.ffn_up_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5390. } else {
  5391. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5392. 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);
  5393. if (layer.ffn_gate_exps) {
  5394. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5395. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5396. } else {
  5397. // merge split expert into a single tensor for compatibility with older models
  5398. // requires disabling mmap
  5399. use_mmap_buffer = false;
  5400. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5401. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5402. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5403. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5404. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5405. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5406. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5407. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5408. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5409. for (uint32_t x = 0; x < n_expert; ++x) {
  5410. // the individual experts are loaded into a view of the merged tensor
  5411. 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);
  5412. 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);
  5413. 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);
  5414. }
  5415. }
  5416. }
  5417. }
  5418. } break;
  5419. case LLM_ARCH_GROK:
  5420. {
  5421. if (n_expert == 0) {
  5422. throw std::runtime_error("Grok model cannot have zero experts");
  5423. }
  5424. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5425. // output
  5426. {
  5427. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5428. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5429. // if output is NULL, init from the input tok embed
  5430. if (model.output == NULL) {
  5431. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5432. }
  5433. }
  5434. for (int i = 0; i < n_layer; ++i) {
  5435. ggml_context * ctx_layer = ctx_for_layer(i);
  5436. ggml_context * ctx_split = ctx_for_layer_split(i);
  5437. auto & layer = model.layers[i];
  5438. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5439. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5440. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5441. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5442. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5443. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5444. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5445. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5446. 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);
  5447. if (layer.ffn_gate_exps) {
  5448. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5449. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5450. } else {
  5451. // merge split expert into a single tensor for compatibility with older models
  5452. // requires disabling mmap
  5453. use_mmap_buffer = false;
  5454. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5455. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5456. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5457. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5458. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5459. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5460. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5461. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5462. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5463. for (uint32_t x = 0; x < n_expert; ++x) {
  5464. // the individual experts are loaded into a view of the merged tensor
  5465. 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);
  5466. 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);
  5467. 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);
  5468. }
  5469. }
  5470. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5471. }
  5472. } break;
  5473. case LLM_ARCH_DBRX:
  5474. {
  5475. if (n_expert == 0) {
  5476. throw std::runtime_error("DBRX model cannot have zero experts");
  5477. }
  5478. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5479. // output
  5480. {
  5481. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5482. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5483. }
  5484. for (int i = 0; i < n_layer; ++i) {
  5485. ggml_context * ctx_layer = ctx_for_layer(i);
  5486. ggml_context * ctx_split = ctx_for_layer_split(i);
  5487. auto & layer = model.layers[i];
  5488. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5489. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5490. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5491. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5492. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5493. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5494. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  5495. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5496. }
  5497. } break;
  5498. case LLM_ARCH_BAICHUAN:
  5499. {
  5500. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5501. {
  5502. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5503. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5511. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5512. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5513. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5514. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5515. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5516. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5517. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5518. }
  5519. } break;
  5520. case LLM_ARCH_FALCON:
  5521. {
  5522. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  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. 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
  5530. }
  5531. }
  5532. for (int i = 0; i < n_layer; ++i) {
  5533. ggml_context * ctx_layer = ctx_for_layer(i);
  5534. ggml_context * ctx_split = ctx_for_layer_split(i);
  5535. auto & layer = model.layers[i];
  5536. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5537. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5538. 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);
  5539. 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);
  5540. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, 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.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5543. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5544. }
  5545. } break;
  5546. case LLM_ARCH_STARCODER:
  5547. {
  5548. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5549. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5550. // output
  5551. {
  5552. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5553. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5554. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5555. if (!model.output) {
  5556. // needs to be on GPU
  5557. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5558. }
  5559. }
  5560. for (int i = 0; i < n_layer; ++i) {
  5561. ggml_context * ctx_layer = ctx_for_layer(i);
  5562. ggml_context * ctx_split = ctx_for_layer_split(i);
  5563. auto & layer = model.layers[i];
  5564. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5565. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5566. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5567. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5568. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5569. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5570. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5571. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5572. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5573. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5574. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5575. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5576. }
  5577. } break;
  5578. case LLM_ARCH_BERT:
  5579. case LLM_ARCH_NOMIC_BERT:
  5580. {
  5581. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5582. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  5583. if (model.arch == LLM_ARCH_BERT) {
  5584. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5585. }
  5586. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5587. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5588. for (int i = 0; i < n_layer; ++i) {
  5589. ggml_context * ctx_layer = ctx_for_layer(i);
  5590. ggml_context * ctx_split = ctx_for_layer_split(i);
  5591. auto & layer = model.layers[i];
  5592. if (model.arch == LLM_ARCH_BERT) {
  5593. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5594. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5595. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5596. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5597. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5598. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5599. } else {
  5600. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5601. }
  5602. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5603. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5604. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5605. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5606. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5607. if (model.arch == LLM_ARCH_BERT) {
  5608. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5609. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5610. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5611. } else {
  5612. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5613. }
  5614. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5615. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5616. }
  5617. } break;
  5618. case LLM_ARCH_JINA_BERT_V2:
  5619. {
  5620. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  5621. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  5622. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  5623. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  5624. for (int i = 0; i < n_layer; ++i) {
  5625. ggml_context * ctx_layer = ctx_for_layer(i);
  5626. ggml_context * ctx_split = ctx_for_layer_split(i);
  5627. auto & layer = model.layers[i]; // JinaBertLayer
  5628. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5629. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5630. 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);
  5631. 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);
  5632. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5633. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5634. 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);
  5635. 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);
  5636. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5637. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5638. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  5639. layer.bo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  5640. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  5641. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5642. 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);
  5643. 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);
  5644. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5645. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5646. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5647. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5648. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5649. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5650. }
  5651. } break;
  5652. case LLM_ARCH_BLOOM:
  5653. {
  5654. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5655. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5656. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5657. // output
  5658. {
  5659. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5660. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5661. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5662. }
  5663. for (int i = 0; i < n_layer; ++i) {
  5664. ggml_context * ctx_layer = ctx_for_layer(i);
  5665. ggml_context * ctx_split = ctx_for_layer_split(i);
  5666. auto & layer = model.layers[i];
  5667. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5668. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5669. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5670. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5671. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5672. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5673. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5674. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5675. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5676. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5677. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5678. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5679. }
  5680. } break;
  5681. case LLM_ARCH_MPT:
  5682. {
  5683. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5684. 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);
  5685. // output
  5686. {
  5687. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5688. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5689. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5690. if (!model.output) {
  5691. 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
  5692. }
  5693. }
  5694. for (int i = 0; i < n_layer; ++i) {
  5695. ggml_context * ctx_layer = ctx_for_layer(i);
  5696. ggml_context * ctx_split = ctx_for_layer_split(i);
  5697. auto & layer = model.layers[i];
  5698. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5699. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5700. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5701. 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);
  5702. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5703. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5704. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5705. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5706. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5707. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5708. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5709. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5710. 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);
  5711. 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);
  5712. 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);
  5713. 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);
  5714. // AWQ ScaleActivation layer
  5715. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5716. }
  5717. } break;
  5718. case LLM_ARCH_STABLELM:
  5719. {
  5720. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5721. // output
  5722. {
  5723. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5724. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5725. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5726. }
  5727. for (int i = 0; i < n_layer; ++i) {
  5728. ggml_context * ctx_layer = ctx_for_layer(i);
  5729. ggml_context * ctx_split = ctx_for_layer_split(i);
  5730. auto & layer = model.layers[i];
  5731. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5732. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5733. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5734. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5735. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5736. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5737. // optional bias tensors, present in Stable LM 2 1.6B
  5738. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5739. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5740. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5741. // optional q and k layernorms, present in StableLM 2 12B
  5742. 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);
  5743. 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);
  5744. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  5745. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5746. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5747. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5748. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5749. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5750. }
  5751. } break;
  5752. case LLM_ARCH_QWEN:
  5753. {
  5754. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5755. // output
  5756. {
  5757. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5758. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5759. }
  5760. for (int i = 0; i < n_layer; ++i) {
  5761. ggml_context * ctx_layer = ctx_for_layer(i);
  5762. ggml_context * ctx_split = ctx_for_layer_split(i);
  5763. auto & layer = model.layers[i];
  5764. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5765. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  5766. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  5767. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5768. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5769. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  5770. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  5771. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  5772. }
  5773. } break;
  5774. case LLM_ARCH_QWEN2:
  5775. {
  5776. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5777. // output
  5778. {
  5779. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5780. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5781. // if output is NULL, init from the input tok embed
  5782. if (model.output == NULL) {
  5783. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5784. }
  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 = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5801. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5802. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5803. }
  5804. } break;
  5805. case LLM_ARCH_QWEN2MOE:
  5806. {
  5807. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5808. // output
  5809. {
  5810. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5811. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5812. }
  5813. for (int i = 0; i < n_layer; ++i) {
  5814. ggml_context * ctx_layer = ctx_for_layer(i);
  5815. ggml_context * ctx_split = ctx_for_layer_split(i);
  5816. auto & layer = model.layers[i];
  5817. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5818. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5819. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5820. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5821. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5822. // optional bias tensors
  5823. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5824. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5825. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5826. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5827. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5828. GGML_ASSERT(n_expert > 0);
  5829. GGML_ASSERT(n_expert_used > 0);
  5830. // MoE branch
  5831. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  5832. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5833. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  5834. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5835. // Shared expert branch
  5836. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  5837. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  5838. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5839. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  5840. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5841. }
  5842. } break;
  5843. case LLM_ARCH_PHI2:
  5844. {
  5845. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5846. // output
  5847. {
  5848. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5849. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5850. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5851. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  5852. }
  5853. for (int i = 0; i < n_layer; ++i) {
  5854. ggml_context * ctx_layer = ctx_for_layer(i);
  5855. ggml_context * ctx_split = ctx_for_layer_split(i);
  5856. auto & layer = model.layers[i];
  5857. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5858. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5859. 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);
  5860. 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);
  5861. if (layer.wqkv == nullptr) {
  5862. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5863. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5864. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5865. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5866. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5867. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5868. }
  5869. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5870. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5871. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5872. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5873. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5874. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5875. }
  5876. } break;
  5877. case LLM_ARCH_PHI3:
  5878. {
  5879. const int64_t n_embd_head = n_embd / n_head;
  5880. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  5881. // output
  5882. {
  5883. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  5884. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  5885. }
  5886. for (int i = 0; i < n_layer; ++i) {
  5887. ggml_context * ctx_layer = ctx_for_layer(i);
  5888. ggml_context * ctx_split = ctx_for_layer_split(i);
  5889. auto & layer = model.layers[i];
  5890. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  5891. 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);
  5892. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  5893. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  5894. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  5895. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  5896. 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));
  5897. 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));
  5898. }
  5899. } break;
  5900. case LLM_ARCH_PLAMO:
  5901. {
  5902. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5903. // output
  5904. {
  5905. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5906. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5907. }
  5908. for (int i = 0; i < n_layer; ++i) {
  5909. ggml_context * ctx_layer = ctx_for_layer(i);
  5910. ggml_context * ctx_split = ctx_for_layer_split(i);
  5911. auto & layer = model.layers[i];
  5912. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5913. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5914. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5915. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5916. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5917. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5918. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5919. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5920. }
  5921. } break;
  5922. case LLM_ARCH_GPT2:
  5923. {
  5924. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5925. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  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_CODESHELL:
  5951. {
  5952. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5953. // output
  5954. {
  5955. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5956. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5957. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5958. }
  5959. for (int i = 0; i < n_layer; ++i) {
  5960. ggml_context * ctx_layer = ctx_for_layer(i);
  5961. ggml_context * ctx_split = ctx_for_layer_split(i);
  5962. auto & layer = model.layers[i];
  5963. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5964. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5965. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5966. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5967. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5968. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5969. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5970. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5971. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5972. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5973. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5974. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5975. }
  5976. } break;
  5977. case LLM_ARCH_ORION:
  5978. {
  5979. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5980. {
  5981. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5982. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5983. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5984. }
  5985. for (int i = 0; i < n_layer; ++i) {
  5986. ggml_context * ctx_layer = ctx_for_layer(i);
  5987. ggml_context * ctx_split = ctx_for_layer_split(i);
  5988. auto & layer = model.layers[i];
  5989. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5990. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5991. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5992. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5993. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5994. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5995. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5996. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5997. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5998. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5999. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6000. }
  6001. } break;
  6002. case LLM_ARCH_INTERNLM2:
  6003. {
  6004. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6005. // output
  6006. {
  6007. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6008. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6009. }
  6010. for (int i = 0; i < n_layer; ++i) {
  6011. ggml_context * ctx_layer = ctx_for_layer(i);
  6012. ggml_context * ctx_split = ctx_for_layer_split(i);
  6013. auto & layer = model.layers[i];
  6014. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6015. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6016. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6017. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6018. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6019. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6020. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6021. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6022. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6023. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6024. }
  6025. } break;
  6026. case LLM_ARCH_GEMMA:
  6027. {
  6028. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6029. // output
  6030. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6031. 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
  6032. for (int i = 0; i < n_layer; ++i) {
  6033. ggml_context * ctx_layer = ctx_for_layer(i);
  6034. ggml_context * ctx_split = ctx_for_layer_split(i);
  6035. auto & layer = model.layers[i];
  6036. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6037. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6038. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6039. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6040. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6041. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6042. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6043. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6044. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6045. }
  6046. } break;
  6047. case LLM_ARCH_GEMMA2:
  6048. {
  6049. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6050. // output
  6051. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6052. 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
  6053. for (int i = 0; i < n_layer; ++i) {
  6054. ggml_context * ctx_layer = ctx_for_layer(i);
  6055. ggml_context * ctx_split = ctx_for_layer_split(i);
  6056. auto & layer = model.layers[i];
  6057. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6058. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6059. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6060. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6061. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6062. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  6063. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6064. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6065. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6066. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6067. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  6068. }
  6069. } break;
  6070. case LLM_ARCH_STARCODER2:
  6071. {
  6072. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6073. // output
  6074. {
  6075. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6076. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6077. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6078. // if output is NULL, init from the input tok embed
  6079. if (model.output == NULL) {
  6080. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6081. }
  6082. }
  6083. for (int i = 0; i < n_layer; ++i) {
  6084. ggml_context * ctx_layer = ctx_for_layer(i);
  6085. ggml_context * ctx_split = ctx_for_layer_split(i);
  6086. auto & layer = model.layers[i];
  6087. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6088. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6089. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6090. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6091. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6092. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6093. // optional bias tensors
  6094. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6095. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6096. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6097. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6098. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6099. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6100. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6101. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6102. // optional bias tensors
  6103. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6104. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  6105. }
  6106. } break;
  6107. case LLM_ARCH_MAMBA:
  6108. {
  6109. const int64_t d_conv = hparams.ssm_d_conv;
  6110. const int64_t d_inner = hparams.ssm_d_inner;
  6111. const int64_t d_state = hparams.ssm_d_state;
  6112. const int64_t dt_rank = hparams.ssm_dt_rank;
  6113. // only an expansion factor of 2 is supported for now
  6114. GGML_ASSERT(2 * n_embd == d_inner);
  6115. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6116. // output
  6117. {
  6118. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6119. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6120. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  6121. if (model.output == NULL) {
  6122. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6123. }
  6124. }
  6125. for (int i = 0; i < n_layer; ++i) {
  6126. ggml_context * ctx_layer = ctx_for_layer(i);
  6127. ggml_context * ctx_split = ctx_for_layer_split(i);
  6128. auto & layer = model.layers[i];
  6129. // norm
  6130. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6131. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  6132. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  6133. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  6134. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  6135. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  6136. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  6137. // no "weight" suffix for these
  6138. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  6139. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  6140. // out_proj
  6141. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  6142. }
  6143. } break;
  6144. case LLM_ARCH_XVERSE:
  6145. {
  6146. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6147. {
  6148. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6149. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6150. }
  6151. for (int i = 0; i < n_layer; ++i) {
  6152. ggml_context * ctx_layer = ctx_for_layer(i);
  6153. ggml_context * ctx_split = ctx_for_layer_split(i);
  6154. auto & layer = model.layers[i];
  6155. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6156. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6157. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6158. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6159. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6160. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {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_COMMAND_R:
  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_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6172. // init output from the input tok embed
  6173. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6174. }
  6175. for (int i = 0; i < n_layer; ++i) {
  6176. ggml_context * ctx_layer = ctx_for_layer(i);
  6177. ggml_context * ctx_split = ctx_for_layer_split(i);
  6178. auto & layer = model.layers[i];
  6179. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6180. if (n_layer >= 64){
  6181. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  6182. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  6183. }
  6184. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6185. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6186. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6187. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6188. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6189. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6190. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6191. }
  6192. } break;
  6193. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  6194. {
  6195. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6196. // output
  6197. {
  6198. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6199. // if output is NULL, init from the input tok embed
  6200. if (model.output == NULL) {
  6201. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6202. }
  6203. }
  6204. for (int i = 0; i < n_layer; ++i) {
  6205. ggml_context * ctx_split = ctx_for_layer_split(i);
  6206. auto & layer = model.layers[i];
  6207. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6208. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6209. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6210. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, 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_OPENELM:
  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. // init output from the input tok embed
  6223. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6224. }
  6225. for (int i = 0; i < n_layer; ++i) {
  6226. const int64_t n_head = hparams.n_head(i);
  6227. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  6228. const int64_t n_ff = hparams.n_ff(i);
  6229. ggml_context * ctx_layer = ctx_for_layer(i);
  6230. ggml_context * ctx_split = ctx_for_layer_split(i);
  6231. auto & layer = model.layers[i];
  6232. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6233. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  6234. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  6235. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  6236. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  6237. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6238. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6239. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6240. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6241. }
  6242. } break;
  6243. case LLM_ARCH_GPTNEOX:
  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_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6250. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6251. }
  6252. for (int i = 0; i < n_layer; ++i) {
  6253. ggml_context * ctx_layer = ctx_for_layer(i);
  6254. ggml_context * ctx_split = ctx_for_layer_split(i);
  6255. auto & layer = model.layers[i];
  6256. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6257. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6258. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6259. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6260. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6261. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6262. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6263. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6264. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6265. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6266. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6267. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6268. }
  6269. } break;
  6270. case LLM_ARCH_ARCTIC:
  6271. {
  6272. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6273. // output
  6274. {
  6275. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6276. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6277. // if output is NULL, init from the input tok embed
  6278. if (model.output == NULL) {
  6279. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6280. }
  6281. }
  6282. for (int i = 0; i < n_layer; ++i) {
  6283. ggml_context * ctx_layer = ctx_for_layer(i);
  6284. ggml_context * ctx_split = ctx_for_layer_split(i);
  6285. auto & layer = model.layers[i];
  6286. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6287. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6288. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6289. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6290. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6291. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6292. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  6293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  6294. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  6295. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6296. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  6297. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  6298. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6299. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6300. }
  6301. } break;
  6302. case LLM_ARCH_DEEPSEEK2:
  6303. {
  6304. const bool is_lite = (hparams.n_layer == 27);
  6305. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6306. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6307. const int64_t q_lora_rank = hparams.n_lora_q;
  6308. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6309. const int64_t n_ff_exp = hparams.n_ff_exp;
  6310. const int64_t n_expert_shared = hparams.n_expert_shared;
  6311. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6312. // output
  6313. {
  6314. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6315. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6316. }
  6317. for (int i = 0; i < n_layer; ++i) {
  6318. ggml_context * ctx_layer = ctx_for_layer(i);
  6319. ggml_context * ctx_split = ctx_for_layer_split(i);
  6320. auto & layer = model.layers[i];
  6321. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6322. if (!is_lite) {
  6323. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6324. }
  6325. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6326. if (!is_lite) {
  6327. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6328. 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});
  6329. } else {
  6330. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6331. }
  6332. 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)});
  6333. 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)});
  6334. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6335. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6336. if (i < (int) hparams.n_layer_dense_lead) {
  6337. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6338. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6339. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6340. } else {
  6341. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6342. GGML_ASSERT(n_expert > 0);
  6343. GGML_ASSERT(n_expert_used > 0);
  6344. // MoE branch
  6345. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6346. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6347. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6348. // Shared expert branch
  6349. 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});
  6350. 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});
  6351. 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});
  6352. }
  6353. }
  6354. } break;
  6355. case LLM_ARCH_BITNET:
  6356. {
  6357. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6358. // output
  6359. {
  6360. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6361. }
  6362. for (int i = 0; i < n_layer; ++i) {
  6363. ggml_context * ctx_layer = ctx_for_layer(i);
  6364. ggml_context * ctx_split = ctx_for_layer_split(i);
  6365. auto & layer = model.layers[i];
  6366. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6367. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  6368. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6369. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1});
  6370. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6371. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1});
  6372. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6373. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1});
  6374. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6375. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1});
  6376. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6377. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  6378. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6379. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1});
  6380. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6381. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1});
  6382. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6383. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1});
  6384. }
  6385. } break;
  6386. case LLM_ARCH_T5:
  6387. {
  6388. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  6389. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6390. // output
  6391. {
  6392. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  6393. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  6394. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6395. // if output is NULL, init from the input tok embed
  6396. if (model.output == NULL) {
  6397. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6398. }
  6399. }
  6400. for (int i = 0; i < n_layer; ++i) {
  6401. ggml_context * ctx_layer = ctx_for_layer(i);
  6402. ggml_context * ctx_split = ctx_for_layer_split(i);
  6403. auto & layer = model.layers[i];
  6404. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  6405. 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);
  6406. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6407. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6408. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6409. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6410. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  6411. 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);
  6412. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6413. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  6414. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  6415. 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);
  6416. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6417. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6418. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6419. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6420. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  6421. // this tensor seems to be unused in HF transformers implementation
  6422. 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);
  6423. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6424. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6425. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6426. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6427. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  6428. 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);
  6429. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6430. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  6431. }
  6432. } break;
  6433. case LLM_ARCH_JAIS:
  6434. {
  6435. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6436. // Output
  6437. {
  6438. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6439. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6440. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6441. }
  6442. for (int i = 0; i < n_layer; ++i) {
  6443. ggml_context * ctx_layer = ctx_for_layer(i);
  6444. ggml_context * ctx_split = ctx_for_layer_split(i);
  6445. auto & layer = model.layers[i];
  6446. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6447. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6448. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6449. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6450. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6451. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6452. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6453. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6454. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6455. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6456. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6457. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  6458. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6459. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6460. }
  6461. } break;
  6462. case LLM_ARCH_CHATGLM:
  6463. {
  6464. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6465. // output
  6466. {
  6467. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6468. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6469. }
  6470. for (int i = 0; i < n_layer; ++i) {
  6471. ggml_context * ctx_layer = ctx_for_layer(i);
  6472. ggml_context * ctx_split = ctx_for_layer_split(i);
  6473. auto & layer = model.layers[i];
  6474. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6475. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + (hparams.n_embd_head_k << 2)});
  6476. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + (hparams.n_embd_head_k << 2)});
  6477. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6478. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6479. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  6480. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6481. }
  6482. } break;
  6483. default:
  6484. throw std::runtime_error("unknown architecture");
  6485. }
  6486. }
  6487. ml.done_getting_tensors();
  6488. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  6489. model.mappings.reserve(ml.mappings.size());
  6490. // create the backend buffers
  6491. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  6492. ctx_bufs.reserve(ctx_map.size());
  6493. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  6494. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  6495. model.bufs.reserve(n_max_backend_buffer);
  6496. for (auto & it : ctx_map) {
  6497. ggml_backend_buffer_type_t buft = it.first;
  6498. ggml_context * ctx = it.second;
  6499. llama_buf_map bufs;
  6500. bufs.reserve(n_max_backend_buffer);
  6501. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  6502. // 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
  6503. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  6504. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  6505. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6506. void * addr = nullptr;
  6507. size_t first, last;
  6508. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6509. if (first >= last) {
  6510. continue;
  6511. }
  6512. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  6513. if (buf == nullptr) {
  6514. throw std::runtime_error("unable to allocate backend CPU buffer");
  6515. }
  6516. model.bufs.push_back(buf);
  6517. bufs.emplace(idx, buf);
  6518. #ifdef GGML_USE_CUDA
  6519. if (n_layer >= n_gpu_layers) {
  6520. ggml_backend_cuda_register_host_buffer(
  6521. ggml_backend_buffer_get_base(buf),
  6522. ggml_backend_buffer_get_size(buf));
  6523. }
  6524. #endif
  6525. }
  6526. }
  6527. #ifdef GGML_USE_METAL
  6528. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  6529. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6530. const size_t max_size = ggml_get_max_tensor_size(ctx);
  6531. void * addr = nullptr;
  6532. size_t first, last;
  6533. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6534. if (first >= last) {
  6535. continue;
  6536. }
  6537. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  6538. if (buf == nullptr) {
  6539. throw std::runtime_error("unable to allocate backend metal buffer");
  6540. }
  6541. model.bufs.push_back(buf);
  6542. bufs.emplace(idx, buf);
  6543. }
  6544. }
  6545. #endif
  6546. else {
  6547. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  6548. if (buf == nullptr) {
  6549. throw std::runtime_error("unable to allocate backend buffer");
  6550. }
  6551. model.bufs.push_back(buf);
  6552. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  6553. model.mlock_bufs.emplace_back(new llama_mlock);
  6554. auto & mlock_buf = model.mlock_bufs.back();
  6555. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  6556. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  6557. }
  6558. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6559. bufs.emplace(idx, buf);
  6560. }
  6561. }
  6562. if (bufs.empty()) {
  6563. throw std::runtime_error("failed to allocate buffer");
  6564. }
  6565. for (auto & buf : bufs) {
  6566. // indicate that this buffer contains weights
  6567. // 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
  6568. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  6569. }
  6570. ctx_bufs.emplace_back(ctx, bufs);
  6571. }
  6572. if (llama_supports_gpu_offload()) {
  6573. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  6574. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  6575. if (n_gpu_layers > (int) hparams.n_layer) {
  6576. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  6577. }
  6578. const int max_backend_supported_layers = hparams.n_layer + 1;
  6579. const int max_offloadable_layers = hparams.n_layer + 1;
  6580. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  6581. }
  6582. // print memory requirements
  6583. for (ggml_backend_buffer_t buf : model.bufs) {
  6584. 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);
  6585. }
  6586. // populate tensors_by_name
  6587. for (ggml_context * ctx : model.ctxs) {
  6588. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  6589. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  6590. }
  6591. }
  6592. // load tensor data
  6593. for (auto & it : ctx_bufs) {
  6594. ggml_context * ctx = it.first;
  6595. auto & bufs = it.second;
  6596. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  6597. return false;
  6598. }
  6599. }
  6600. if (use_mmap_buffer) {
  6601. for (auto & mapping : ml.mappings) {
  6602. model.mappings.emplace_back(std::move(mapping));
  6603. }
  6604. }
  6605. // loading time will be recalculate after the first eval, so
  6606. // we take page faults deferred by mmap() into consideration
  6607. model.t_load_us = ggml_time_us() - model.t_start_us;
  6608. return true;
  6609. }
  6610. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  6611. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  6612. try {
  6613. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  6614. model.hparams.vocab_only = params.vocab_only;
  6615. try {
  6616. llm_load_arch(ml, model);
  6617. } catch(const std::exception & e) {
  6618. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  6619. }
  6620. try {
  6621. llm_load_hparams(ml, model);
  6622. } catch(const std::exception & e) {
  6623. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  6624. }
  6625. try {
  6626. llm_load_vocab(ml, model);
  6627. } catch(const std::exception & e) {
  6628. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  6629. }
  6630. llm_load_print_meta(ml, model);
  6631. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  6632. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  6633. throw std::runtime_error("vocab size mismatch");
  6634. }
  6635. if (params.vocab_only) {
  6636. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  6637. return 0;
  6638. }
  6639. #ifdef GGML_USE_KOMPUTE
  6640. if (params.n_gpu_layers > 0 && (
  6641. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  6642. || !(
  6643. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  6644. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  6645. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  6646. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  6647. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  6648. )
  6649. )) {
  6650. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  6651. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  6652. params.n_gpu_layers = 0;
  6653. }
  6654. #endif
  6655. if (!llm_load_tensors(
  6656. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  6657. params.progress_callback, params.progress_callback_user_data
  6658. )) {
  6659. return -2;
  6660. }
  6661. } catch (const std::exception & err) {
  6662. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  6663. return -1;
  6664. }
  6665. return 0;
  6666. }
  6667. //
  6668. // llm_build
  6669. //
  6670. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  6671. enum llm_ffn_op_type {
  6672. LLM_FFN_SILU,
  6673. LLM_FFN_GELU,
  6674. LLM_FFN_RELU,
  6675. LLM_FFN_RELU_SQR,
  6676. LLM_FFN_SWIGLU,
  6677. };
  6678. enum llm_ffn_gate_type {
  6679. LLM_FFN_SEQ,
  6680. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  6681. };
  6682. enum llm_norm_type {
  6683. LLM_NORM,
  6684. LLM_NORM_RMS,
  6685. };
  6686. static struct ggml_tensor * llm_build_inp_embd(
  6687. struct ggml_context * ctx,
  6688. struct llama_context & lctx,
  6689. const llama_hparams & hparams,
  6690. const llama_batch & batch,
  6691. struct ggml_tensor * tok_embd,
  6692. const llm_build_cb & cb) {
  6693. const int64_t n_embd = hparams.n_embd;
  6694. struct ggml_tensor * inpL;
  6695. if (batch.token) {
  6696. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  6697. cb(lctx.inp_tokens, "inp_tokens", -1);
  6698. ggml_set_input(lctx.inp_tokens);
  6699. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  6700. } else {
  6701. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  6702. inpL = lctx.inp_embd;
  6703. ggml_set_input(lctx.inp_embd);
  6704. }
  6705. cb(inpL, "inp_embd", -1);
  6706. return inpL;
  6707. }
  6708. static void llm_build_kv_store(
  6709. struct ggml_context * ctx,
  6710. const llama_hparams & hparams,
  6711. const llama_cparams & cparams,
  6712. const llama_kv_cache & kv,
  6713. struct ggml_cgraph * graph,
  6714. struct ggml_tensor * k_cur,
  6715. struct ggml_tensor * v_cur,
  6716. int32_t n_tokens,
  6717. int32_t kv_head,
  6718. const llm_build_cb & cb,
  6719. int64_t il) {
  6720. const int64_t n_ctx = cparams.n_ctx;
  6721. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  6722. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  6723. GGML_ASSERT(kv.size == n_ctx);
  6724. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  6725. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  6726. cb(k_cache_view, "k_cache_view", il);
  6727. // note: storing RoPE-ed version of K in the KV cache
  6728. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  6729. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  6730. struct ggml_tensor * v_cache_view = nullptr;
  6731. if (cparams.flash_attn) {
  6732. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  6733. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  6734. } else {
  6735. // note: the V cache is transposed when not using flash attention
  6736. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  6737. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  6738. (kv_head)*ggml_element_size(kv.v_l[il]));
  6739. v_cur = ggml_transpose(ctx, v_cur);
  6740. }
  6741. cb(v_cache_view, "v_cache_view", il);
  6742. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  6743. }
  6744. // do mat_mul, while optionally apply lora
  6745. static struct ggml_tensor * llm_build_lora_mm(
  6746. struct llama_context & lctx,
  6747. struct ggml_context * ctx0,
  6748. struct ggml_tensor * w,
  6749. struct ggml_tensor * cur) {
  6750. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  6751. for (auto & it : lctx.lora_adapters) {
  6752. struct llama_lora_weight * lora = it.first->get_weight(w);
  6753. if (lora == nullptr) {
  6754. continue;
  6755. }
  6756. const float alpha = it.first->alpha;
  6757. const float rank = (float) lora->b->ne[0];
  6758. const float scale = alpha ? it.second * alpha / rank : it.second;
  6759. struct ggml_tensor * ab_cur = ggml_mul_mat(
  6760. ctx0, lora->b,
  6761. ggml_mul_mat(ctx0, lora->a, cur)
  6762. );
  6763. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6764. res = ggml_add(ctx0, res, ab_cur);
  6765. }
  6766. return res;
  6767. }
  6768. // do mat_mul_id, while optionally apply lora
  6769. static struct ggml_tensor * llm_build_lora_mm_id(
  6770. struct llama_context & lctx,
  6771. struct ggml_context * ctx0,
  6772. struct ggml_tensor * w, // struct ggml_tensor * as
  6773. struct ggml_tensor * cur, // struct ggml_tensor * b
  6774. struct ggml_tensor * ids) {
  6775. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  6776. for (auto & it : lctx.lora_adapters) {
  6777. struct llama_lora_weight * lora = it.first->get_weight(w);
  6778. if (lora == nullptr) {
  6779. continue;
  6780. }
  6781. const float alpha = it.first->alpha;
  6782. const float rank = (float) lora->b->ne[0];
  6783. const float scale = alpha ? it.second * alpha / rank : it.second;
  6784. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  6785. ctx0, lora->b,
  6786. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  6787. ids
  6788. );
  6789. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6790. res = ggml_add(ctx0, res, ab_cur);
  6791. }
  6792. return res;
  6793. }
  6794. static struct ggml_tensor * llm_build_norm(
  6795. struct ggml_context * ctx,
  6796. struct ggml_tensor * cur,
  6797. const llama_hparams & hparams,
  6798. struct ggml_tensor * mw,
  6799. struct ggml_tensor * mb,
  6800. llm_norm_type type,
  6801. const llm_build_cb & cb,
  6802. int il) {
  6803. switch (type) {
  6804. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  6805. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  6806. }
  6807. if (mw || mb) {
  6808. cb(cur, "norm", il);
  6809. }
  6810. if (mw) {
  6811. cur = ggml_mul(ctx, cur, mw);
  6812. if (mb) {
  6813. cb(cur, "norm_w", il);
  6814. }
  6815. }
  6816. if (mb) {
  6817. cur = ggml_add(ctx, cur, mb);
  6818. }
  6819. return cur;
  6820. }
  6821. static struct ggml_tensor * llm_build_ffn(
  6822. struct ggml_context * ctx,
  6823. struct llama_context & lctx,
  6824. struct ggml_tensor * cur,
  6825. struct ggml_tensor * up,
  6826. struct ggml_tensor * up_b,
  6827. struct ggml_tensor * up_s,
  6828. struct ggml_tensor * gate,
  6829. struct ggml_tensor * gate_b,
  6830. struct ggml_tensor * gate_s,
  6831. struct ggml_tensor * down,
  6832. struct ggml_tensor * down_b,
  6833. struct ggml_tensor * down_s,
  6834. struct ggml_tensor * act_scales,
  6835. llm_ffn_op_type type_op,
  6836. llm_ffn_gate_type type_gate,
  6837. const llm_build_cb & cb,
  6838. int il) {
  6839. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  6840. cb(tmp, "ffn_up", il);
  6841. if (up_b) {
  6842. tmp = ggml_add(ctx, tmp, up_b);
  6843. cb(tmp, "ffn_up_b", il);
  6844. }
  6845. if (up_s) {
  6846. tmp = ggml_mul(ctx, tmp, up_s);
  6847. cb(tmp, "ffn_up_s", il);
  6848. }
  6849. if (gate) {
  6850. switch (type_gate) {
  6851. case LLM_FFN_SEQ:
  6852. {
  6853. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  6854. cb(cur, "ffn_gate", il);
  6855. } break;
  6856. case LLM_FFN_PAR:
  6857. {
  6858. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  6859. cb(cur, "ffn_gate", il);
  6860. } break;
  6861. }
  6862. if (gate_b) {
  6863. cur = ggml_add(ctx, cur, gate_b);
  6864. cb(cur, "ffn_gate_b", il);
  6865. }
  6866. if (gate_s) {
  6867. cur = ggml_mul(ctx, cur, gate_s);
  6868. cb(cur, "ffn_gate_s", il);
  6869. }
  6870. } else {
  6871. cur = tmp;
  6872. }
  6873. switch (type_op) {
  6874. case LLM_FFN_SILU:
  6875. {
  6876. cur = ggml_silu(ctx, cur);
  6877. cb(cur, "ffn_silu", il);
  6878. } break;
  6879. case LLM_FFN_GELU:
  6880. {
  6881. cur = ggml_gelu(ctx, cur);
  6882. cb(cur, "ffn_gelu", il);
  6883. if (act_scales != NULL) {
  6884. cur = ggml_div(ctx, cur, act_scales);
  6885. cb(cur, "ffn_act", il);
  6886. }
  6887. } break;
  6888. case LLM_FFN_RELU:
  6889. {
  6890. cur = ggml_relu(ctx, cur);
  6891. cb(cur, "ffn_relu", il);
  6892. } break;
  6893. case LLM_FFN_RELU_SQR:
  6894. {
  6895. cur = ggml_relu(ctx, cur);
  6896. cb(cur, "ffn_relu", il);
  6897. cur = ggml_sqr(ctx, cur);
  6898. cb(cur, "ffn_sqr(relu)", il);
  6899. } break;
  6900. case LLM_FFN_SWIGLU:
  6901. {
  6902. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  6903. int64_t split_point = cur->ne[0] / 2;
  6904. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  6905. 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)));
  6906. x0 = ggml_silu(ctx, x0);
  6907. cb(cur, "ffn_silu", il);
  6908. cur = ggml_mul(ctx, x0, x1);
  6909. cb(cur, "ffn_mul", il);
  6910. } break;
  6911. }
  6912. if (type_gate == LLM_FFN_PAR) {
  6913. cur = ggml_mul(ctx, cur, tmp);
  6914. cb(cur, "ffn_gate_par", il);
  6915. }
  6916. if (down) {
  6917. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  6918. }
  6919. if (down_b) {
  6920. cb(cur, "ffn_down", il);
  6921. }
  6922. if (down_b) {
  6923. cur = ggml_add(ctx, cur, down_b);
  6924. }
  6925. if (down_s) {
  6926. cur = ggml_mul(ctx, cur, down_s);
  6927. cb(cur, "ffn_down_s", il);
  6928. }
  6929. return cur;
  6930. }
  6931. static struct ggml_tensor * llm_build_moe_ffn(
  6932. struct ggml_context * ctx,
  6933. struct llama_context & lctx,
  6934. struct ggml_tensor * cur,
  6935. struct ggml_tensor * gate_inp,
  6936. struct ggml_tensor * up_exps,
  6937. struct ggml_tensor * gate_exps,
  6938. struct ggml_tensor * down_exps,
  6939. int64_t n_expert,
  6940. int64_t n_expert_used,
  6941. llm_ffn_op_type type_op,
  6942. bool norm_w,
  6943. bool scale_w,
  6944. float w_scale,
  6945. const llm_build_cb & cb,
  6946. int il) {
  6947. int64_t n_embd = cur->ne[0];
  6948. int64_t n_tokens = cur->ne[1];
  6949. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  6950. cb(logits, "ffn_moe_logits", il);
  6951. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  6952. cb(probs, "ffn_moe_probs", il);
  6953. // select experts
  6954. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  6955. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  6956. cb(selected_experts, "ffn_moe_topk", il);
  6957. ggml_tensor * weights = ggml_get_rows(ctx,
  6958. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  6959. cb(weights, "ffn_moe_weights", il);
  6960. if (norm_w) {
  6961. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  6962. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  6963. cb(weights_sum, "ffn_moe_weights_sum", il);
  6964. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  6965. cb(weights, "ffn_moe_weights_norm", il);
  6966. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  6967. }
  6968. if (scale_w) {
  6969. weights = ggml_scale(ctx, weights, w_scale);
  6970. cb(weights, "ffn_moe_weights_scaled", il);
  6971. }
  6972. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  6973. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6974. cb(up, "ffn_moe_up", il);
  6975. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6976. cb(gate, "ffn_moe_gate", il);
  6977. switch (type_op) {
  6978. case LLM_FFN_SILU:
  6979. {
  6980. gate = ggml_silu(ctx, gate);
  6981. cb(gate, "ffn_moe_silu", il);
  6982. } break;
  6983. case LLM_FFN_GELU:
  6984. {
  6985. gate = ggml_gelu(ctx, gate);
  6986. cb(gate, "ffn_moe_gelu", il);
  6987. } break;
  6988. default:
  6989. GGML_ABORT("fatal error");
  6990. }
  6991. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  6992. cb(par, "ffn_moe_gate_par", il);
  6993. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  6994. cb(experts, "ffn_moe_down", il);
  6995. experts = ggml_mul(ctx, experts, weights);
  6996. // aggregate experts
  6997. ggml_tensor * moe_out = nullptr;
  6998. for (int i = 0; i < n_expert_used; ++i) {
  6999. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  7000. experts->nb[2], i*experts->nb[1]);
  7001. if (i == 0) {
  7002. moe_out = cur_expert;
  7003. } else {
  7004. moe_out = ggml_add(ctx, moe_out, cur_expert);
  7005. }
  7006. }
  7007. if (n_expert_used == 1) {
  7008. // avoid returning a non-contiguous tensor
  7009. moe_out = ggml_cont(ctx, moe_out);
  7010. }
  7011. return moe_out;
  7012. }
  7013. static struct ggml_tensor * llm_build_kqv(
  7014. struct ggml_context * ctx,
  7015. struct llama_context & lctx,
  7016. const llama_kv_cache & kv,
  7017. struct ggml_cgraph * graph,
  7018. struct ggml_tensor * wo,
  7019. struct ggml_tensor * wo_b,
  7020. struct ggml_tensor * q_cur,
  7021. struct ggml_tensor * kq_mask,
  7022. int32_t n_tokens,
  7023. int32_t n_kv,
  7024. float kq_scale,
  7025. const llm_build_cb & cb,
  7026. int il) {
  7027. const llama_model & model = lctx.model;
  7028. const llama_hparams & hparams = lctx.model.hparams;
  7029. const llama_cparams & cparams = lctx.cparams;
  7030. const int64_t n_ctx = cparams.n_ctx;
  7031. const int64_t n_head = hparams.n_head(il);
  7032. const int64_t n_head_kv = hparams.n_head_kv(il);
  7033. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7034. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7035. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  7036. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7037. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  7038. cb(q, "q", il);
  7039. struct ggml_tensor * k =
  7040. ggml_view_3d(ctx, kv.k_l[il],
  7041. n_embd_head_k, n_kv, n_head_kv,
  7042. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  7043. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  7044. 0);
  7045. cb(k, "k", il);
  7046. struct ggml_tensor * cur;
  7047. if (cparams.flash_attn) {
  7048. GGML_UNUSED(model);
  7049. GGML_UNUSED(n_ctx);
  7050. // split cached v into n_head heads (not transposed)
  7051. struct ggml_tensor * v =
  7052. ggml_view_3d(ctx, kv.v_l[il],
  7053. n_embd_head_v, n_kv, n_head_kv,
  7054. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  7055. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  7056. 0);
  7057. cb(v, "v", il);
  7058. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7059. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX) {
  7060. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  7061. }
  7062. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  7063. } else {
  7064. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  7065. cb(kq, "kq", il);
  7066. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_QWEN2) {
  7067. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  7068. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  7069. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7070. }
  7071. if (model.arch == LLM_ARCH_GROK) {
  7072. // need to do the following:
  7073. // multiply by attn_output_multiplyer of 0.08838834764831845
  7074. // and then :
  7075. // kq = 30 * tanh(kq / 30)
  7076. // before the softmax below
  7077. //try from phi2
  7078. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7079. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  7080. kq = ggml_scale(ctx, kq, 30);
  7081. }
  7082. if (hparams.attn_soft_cap) {
  7083. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  7084. kq = ggml_tanh(ctx, kq);
  7085. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  7086. }
  7087. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7088. cb(kq, "kq_soft_max_ext", il);
  7089. GGML_ASSERT(kv.size == n_ctx);
  7090. // split cached v into n_head heads
  7091. struct ggml_tensor * v =
  7092. ggml_view_3d(ctx, kv.v_l[il],
  7093. n_kv, n_embd_head_v, n_head_kv,
  7094. ggml_element_size(kv.v_l[il])*n_ctx,
  7095. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  7096. 0);
  7097. cb(v, "v", il);
  7098. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  7099. cb(kqv, "kqv", il);
  7100. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  7101. cb(kqv_merged, "kqv_merged", il);
  7102. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  7103. cb(cur, "kqv_merged_cont", il);
  7104. }
  7105. ggml_build_forward_expand(graph, cur);
  7106. if (wo) {
  7107. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  7108. }
  7109. if (wo_b) {
  7110. cb(cur, "kqv_wo", il);
  7111. }
  7112. if (wo_b) {
  7113. cur = ggml_add(ctx, cur, wo_b);
  7114. }
  7115. return cur;
  7116. }
  7117. static struct ggml_tensor * llm_build_kv(
  7118. struct ggml_context * ctx,
  7119. struct llama_context & lctx,
  7120. const llama_kv_cache & kv,
  7121. struct ggml_cgraph * graph,
  7122. struct ggml_tensor * wo,
  7123. struct ggml_tensor * wo_b,
  7124. struct ggml_tensor * k_cur,
  7125. struct ggml_tensor * v_cur,
  7126. struct ggml_tensor * q_cur,
  7127. struct ggml_tensor * kq_mask,
  7128. int32_t n_tokens,
  7129. int32_t kv_head,
  7130. int32_t n_kv,
  7131. float kq_scale,
  7132. const llm_build_cb & cb,
  7133. int il) {
  7134. const llama_hparams & hparams = lctx.model.hparams;
  7135. const llama_cparams & cparams = lctx.cparams;
  7136. // these nodes are added to the graph together so that they are not reordered
  7137. // by doing so, the number of splits in the graph is reduced
  7138. ggml_build_forward_expand(graph, q_cur);
  7139. ggml_build_forward_expand(graph, k_cur);
  7140. ggml_build_forward_expand(graph, v_cur);
  7141. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  7142. struct ggml_tensor * cur;
  7143. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b,
  7144. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  7145. cb(cur, "kqv_out", il);
  7146. return cur;
  7147. }
  7148. struct llm_build_context {
  7149. const llama_model & model;
  7150. llama_context & lctx;
  7151. const llama_hparams & hparams;
  7152. const llama_cparams & cparams;
  7153. const llama_batch & batch;
  7154. const llama_kv_cache & kv_self;
  7155. const int64_t n_embd;
  7156. const int64_t n_layer;
  7157. const int64_t n_rot;
  7158. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  7159. const int64_t n_head;
  7160. const int64_t n_head_kv;
  7161. const int64_t n_embd_head_k;
  7162. const int64_t n_embd_k_gqa;
  7163. const int64_t n_embd_head_v;
  7164. const int64_t n_embd_v_gqa;
  7165. const int64_t n_expert;
  7166. const int64_t n_expert_used;
  7167. const float freq_base;
  7168. const float freq_scale;
  7169. const float ext_factor;
  7170. const float attn_factor;
  7171. const float beta_fast;
  7172. const float beta_slow;
  7173. const float norm_eps;
  7174. const float norm_rms_eps;
  7175. const int32_t n_tokens;
  7176. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  7177. const int32_t n_outputs;
  7178. const int32_t n_outputs_enc;
  7179. const int32_t kv_head; // index of where we store new KV data in the cache
  7180. const int32_t n_ctx_orig;
  7181. const bool flash_attn;
  7182. const enum llama_pooling_type pooling_type;
  7183. const enum llama_rope_type rope_type;
  7184. const llm_build_cb & cb;
  7185. std::vector<uint8_t> & buf_compute_meta;
  7186. struct ggml_context * ctx0 = nullptr;
  7187. // TODO: consider making the entire interface noexcept
  7188. llm_build_context(
  7189. llama_context & lctx,
  7190. const llama_batch & batch,
  7191. const llm_build_cb & cb,
  7192. bool worst_case) :
  7193. model (lctx.model),
  7194. lctx (lctx),
  7195. hparams (model.hparams),
  7196. cparams (lctx.cparams),
  7197. batch (batch),
  7198. kv_self (lctx.kv_self),
  7199. n_embd (hparams.n_embd),
  7200. n_layer (hparams.n_layer),
  7201. n_rot (hparams.n_rot),
  7202. n_ctx (cparams.n_ctx),
  7203. n_head (hparams.n_head()),
  7204. n_head_kv (hparams.n_head_kv()),
  7205. n_embd_head_k (hparams.n_embd_head_k),
  7206. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  7207. n_embd_head_v (hparams.n_embd_head_v),
  7208. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  7209. n_expert (hparams.n_expert),
  7210. n_expert_used (hparams.n_expert_used),
  7211. freq_base (cparams.rope_freq_base),
  7212. freq_scale (cparams.rope_freq_scale),
  7213. ext_factor (cparams.yarn_ext_factor),
  7214. attn_factor (cparams.yarn_attn_factor),
  7215. beta_fast (cparams.yarn_beta_fast),
  7216. beta_slow (cparams.yarn_beta_slow),
  7217. norm_eps (hparams.f_norm_eps),
  7218. norm_rms_eps (hparams.f_norm_rms_eps),
  7219. n_tokens (batch.n_tokens),
  7220. n_kv (worst_case ? kv_self.size : kv_self.n),
  7221. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  7222. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  7223. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  7224. n_ctx_orig (cparams.n_ctx_orig_yarn),
  7225. flash_attn (cparams.flash_attn),
  7226. pooling_type (cparams.pooling_type),
  7227. rope_type (hparams.rope_type),
  7228. cb (cb),
  7229. buf_compute_meta (lctx.buf_compute_meta) {
  7230. // all initializations should be done in init()
  7231. }
  7232. void init() {
  7233. struct ggml_init_params params = {
  7234. /*.mem_size =*/ buf_compute_meta.size(),
  7235. /*.mem_buffer =*/ buf_compute_meta.data(),
  7236. /*.no_alloc =*/ true,
  7237. };
  7238. ctx0 = ggml_init(params);
  7239. lctx.inp_tokens = nullptr;
  7240. lctx.inp_embd = nullptr;
  7241. lctx.inp_pos = nullptr;
  7242. lctx.inp_out_ids = nullptr;
  7243. lctx.inp_KQ_mask = nullptr;
  7244. lctx.inp_KQ_mask_swa = nullptr;
  7245. lctx.inp_K_shift = nullptr;
  7246. lctx.inp_mean = nullptr;
  7247. lctx.inp_cls = nullptr;
  7248. lctx.inp_s_copy = nullptr;
  7249. lctx.inp_s_mask = nullptr;
  7250. lctx.inp_s_seq = nullptr;
  7251. lctx.inp_pos_bucket = nullptr;
  7252. lctx.inp_embd_enc = nullptr;
  7253. lctx.inp_KQ_mask_cross = nullptr;
  7254. }
  7255. void free() {
  7256. if (ctx0) {
  7257. ggml_free(ctx0);
  7258. ctx0 = nullptr;
  7259. }
  7260. }
  7261. struct ggml_cgraph * build_k_shift() {
  7262. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7263. GGML_ASSERT(kv_self.size == n_ctx);
  7264. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  7265. cb(lctx.inp_K_shift, "K_shift", -1);
  7266. ggml_set_input(lctx.inp_K_shift);
  7267. for (int il = 0; il < n_layer; ++il) {
  7268. const int64_t n_head_kv = hparams.n_head_kv(il);
  7269. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7270. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7271. struct ggml_tensor * tmp =
  7272. // we rotate only the first n_rot dimensions
  7273. ggml_rope_ext_inplace(ctx0,
  7274. ggml_view_3d(ctx0, kv_self.k_l[il],
  7275. n_embd_head_k, n_head_kv, n_ctx,
  7276. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  7277. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7278. 0),
  7279. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7280. ext_factor, attn_factor, beta_fast, beta_slow);
  7281. cb(tmp, "K_shifted", il);
  7282. ggml_build_forward_expand(gf, tmp);
  7283. }
  7284. return gf;
  7285. }
  7286. struct ggml_cgraph * build_s_copy() {
  7287. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7288. GGML_ASSERT(kv_self.recurrent);
  7289. struct ggml_tensor * state_copy = build_inp_s_copy();
  7290. for (int il = 0; il < n_layer; ++il) {
  7291. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7292. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7293. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  7294. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  7295. // TODO: name the intermediate tensors with cb()
  7296. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  7297. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  7298. }
  7299. return gf;
  7300. }
  7301. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  7302. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7303. for (uint32_t i = 0; i < ids.size(); ++i) {
  7304. const uint32_t id = ids[i];
  7305. if (i == id || id == ids.size()) {
  7306. continue;
  7307. }
  7308. uint32_t nm = 1;
  7309. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  7310. nm++;
  7311. }
  7312. for (int il = 0; il < n_layer; ++il) {
  7313. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7314. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7315. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  7316. n_embd_k_gqa, nm,
  7317. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7318. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  7319. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  7320. n_embd_k_gqa, nm,
  7321. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7322. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  7323. ggml_tensor * view_v_src;
  7324. ggml_tensor * view_v_dst;
  7325. if (flash_attn) {
  7326. // NOTE: the V cache is not transposed when using flash attention
  7327. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7328. n_embd_v_gqa, nm,
  7329. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7330. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  7331. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7332. n_embd_v_gqa, nm,
  7333. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7334. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  7335. } else {
  7336. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7337. nm, n_embd_v_gqa,
  7338. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7339. ggml_row_size(kv_self.v_l[il]->type, i));
  7340. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7341. nm, n_embd_v_gqa,
  7342. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7343. ggml_row_size(kv_self.v_l[il]->type, id));
  7344. }
  7345. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  7346. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  7347. }
  7348. i += nm - 1;
  7349. }
  7350. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  7351. return gf;
  7352. }
  7353. struct ggml_tensor * build_inp_pos() {
  7354. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7355. cb(lctx.inp_pos, "inp_pos", -1);
  7356. ggml_set_input(lctx.inp_pos);
  7357. return lctx.inp_pos;
  7358. }
  7359. struct ggml_tensor * build_rope_factors(int il) {
  7360. // choose long/short freq factors based on the context size
  7361. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  7362. if (model.layers[il].rope_freqs != nullptr) {
  7363. return model.layers[il].rope_freqs;
  7364. }
  7365. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  7366. return model.layers[il].rope_long;
  7367. }
  7368. return model.layers[il].rope_short;
  7369. }
  7370. struct ggml_tensor * build_inp_out_ids() {
  7371. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  7372. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  7373. ggml_set_input(lctx.inp_out_ids);
  7374. return lctx.inp_out_ids;
  7375. }
  7376. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  7377. lctx.inp_KQ_mask = causal
  7378. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7379. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7380. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  7381. ggml_set_input(lctx.inp_KQ_mask);
  7382. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  7383. }
  7384. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  7385. GGML_ASSERT(hparams.n_swa > 0);
  7386. lctx.inp_KQ_mask_swa = causal
  7387. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7388. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7389. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  7390. ggml_set_input(lctx.inp_KQ_mask_swa);
  7391. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  7392. }
  7393. struct ggml_tensor * build_inp_mean() {
  7394. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  7395. cb(lctx.inp_mean, "inp_mean", -1);
  7396. ggml_set_input(lctx.inp_mean);
  7397. return lctx.inp_mean;
  7398. }
  7399. struct ggml_tensor * build_inp_cls() {
  7400. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7401. cb(lctx.inp_cls, "inp_cls", -1);
  7402. ggml_set_input(lctx.inp_cls);
  7403. return lctx.inp_cls;
  7404. }
  7405. struct ggml_tensor * build_inp_s_copy() {
  7406. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  7407. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  7408. ggml_set_input(lctx.inp_s_copy);
  7409. return lctx.inp_s_copy;
  7410. }
  7411. struct ggml_tensor * build_inp_s_mask() {
  7412. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  7413. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  7414. ggml_set_input(lctx.inp_s_mask);
  7415. return lctx.inp_s_mask;
  7416. }
  7417. struct ggml_tensor * build_inp_s_seq() {
  7418. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7419. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  7420. ggml_set_input(lctx.inp_s_seq);
  7421. return lctx.inp_s_seq;
  7422. }
  7423. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  7424. // find result_norm tensor for input
  7425. struct ggml_tensor * inp = nullptr;
  7426. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  7427. inp = gf->nodes[i];
  7428. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  7429. break;
  7430. } else {
  7431. inp = nullptr;
  7432. }
  7433. }
  7434. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  7435. struct ggml_tensor * cur;
  7436. switch (pooling_type) {
  7437. case LLAMA_POOLING_TYPE_MEAN:
  7438. {
  7439. struct ggml_tensor * inp_mean = build_inp_mean();
  7440. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  7441. } break;
  7442. case LLAMA_POOLING_TYPE_CLS:
  7443. case LLAMA_POOLING_TYPE_LAST:
  7444. {
  7445. struct ggml_tensor * inp_cls = build_inp_cls();
  7446. cur = ggml_get_rows(ctx0, inp, inp_cls);
  7447. } break;
  7448. case LLAMA_POOLING_TYPE_NONE:
  7449. {
  7450. cur = inp;
  7451. } break;
  7452. default:
  7453. {
  7454. GGML_ABORT("unknown pooling type");
  7455. }
  7456. }
  7457. cb(cur, "result_embd_pooled", -1);
  7458. ggml_build_forward_expand(gf, cur);
  7459. return gf;
  7460. }
  7461. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  7462. if (causal) {
  7463. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7464. } else {
  7465. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  7466. }
  7467. ggml_set_input(lctx.inp_pos_bucket);
  7468. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  7469. return lctx.inp_pos_bucket;
  7470. }
  7471. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  7472. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  7473. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  7474. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  7475. cb(pos_bias, "pos_bias", -1);
  7476. 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);
  7477. cb(pos_bias, "pos_bias", -1);
  7478. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  7479. cb(pos_bias, "pos_bias", -1);
  7480. pos_bias = ggml_cont(ctx0, pos_bias);
  7481. cb(pos_bias, "pos_bias", -1);
  7482. return pos_bias;
  7483. }
  7484. struct ggml_tensor * llm_build_inp_embd_enc() {
  7485. const int64_t n_embd = hparams.n_embd;
  7486. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  7487. ggml_set_input(lctx.inp_embd_enc);
  7488. cb(lctx.inp_embd_enc, "embd_enc", -1);
  7489. return lctx.inp_embd_enc;
  7490. }
  7491. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  7492. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7493. ggml_set_input(lctx.inp_KQ_mask_cross);
  7494. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  7495. return lctx.inp_KQ_mask_cross;
  7496. }
  7497. struct ggml_cgraph * build_llama() {
  7498. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7499. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7500. int32_t n_tokens = this->n_tokens;
  7501. const int64_t n_embd_head = hparams.n_embd_head_v;
  7502. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7503. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7504. struct ggml_tensor * cur;
  7505. struct ggml_tensor * inpL;
  7506. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7507. // inp_pos - contains the positions
  7508. struct ggml_tensor * inp_pos = build_inp_pos();
  7509. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7510. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7511. for (int il = 0; il < n_layer; ++il) {
  7512. struct ggml_tensor * inpSA = inpL;
  7513. // norm
  7514. cur = llm_build_norm(ctx0, inpL, hparams,
  7515. model.layers[il].attn_norm, NULL,
  7516. LLM_NORM_RMS, cb, il);
  7517. cb(cur, "attn_norm", il);
  7518. // self-attention
  7519. {
  7520. // rope freq factors for llama3; may return nullptr for llama2 and other models
  7521. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7522. // compute Q and K and RoPE them
  7523. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7524. cb(Qcur, "Qcur", il);
  7525. if (model.layers[il].bq) {
  7526. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7527. cb(Qcur, "Qcur", il);
  7528. }
  7529. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7530. cb(Kcur, "Kcur", il);
  7531. if (model.layers[il].bk) {
  7532. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7533. cb(Kcur, "Kcur", il);
  7534. }
  7535. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7536. cb(Vcur, "Vcur", il);
  7537. if (model.layers[il].bv) {
  7538. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7539. cb(Vcur, "Vcur", il);
  7540. }
  7541. Qcur = ggml_rope_ext(
  7542. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  7543. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7544. ext_factor, attn_factor, beta_fast, beta_slow
  7545. );
  7546. cb(Qcur, "Qcur", il);
  7547. Kcur = ggml_rope_ext(
  7548. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  7549. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7550. ext_factor, attn_factor, beta_fast, beta_slow
  7551. );
  7552. cb(Kcur, "Kcur", il);
  7553. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7554. model.layers[il].wo, model.layers[il].bo,
  7555. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7556. }
  7557. if (il == n_layer - 1) {
  7558. // skip computing output for unused tokens
  7559. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7560. n_tokens = n_outputs;
  7561. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7562. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7563. }
  7564. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7565. cb(ffn_inp, "ffn_inp", il);
  7566. // feed-forward network
  7567. if (model.layers[il].ffn_gate_inp == nullptr) {
  7568. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7569. model.layers[il].ffn_norm, NULL,
  7570. LLM_NORM_RMS, cb, il);
  7571. cb(cur, "ffn_norm", il);
  7572. cur = llm_build_ffn(ctx0, lctx, cur,
  7573. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  7574. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  7575. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  7576. NULL,
  7577. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7578. cb(cur, "ffn_out", il);
  7579. } else {
  7580. // MoE branch
  7581. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7582. model.layers[il].ffn_norm, NULL,
  7583. LLM_NORM_RMS, cb, il);
  7584. cb(cur, "ffn_norm", il);
  7585. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7586. model.layers[il].ffn_gate_inp,
  7587. model.layers[il].ffn_up_exps,
  7588. model.layers[il].ffn_gate_exps,
  7589. model.layers[il].ffn_down_exps,
  7590. n_expert, n_expert_used,
  7591. LLM_FFN_SILU, true,
  7592. false, 0.0,
  7593. cb, il);
  7594. cb(cur, "ffn_moe_out", il);
  7595. }
  7596. cur = ggml_add(ctx0, cur, ffn_inp);
  7597. cb(cur, "ffn_out", il);
  7598. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7599. cb(cur, "l_out", il);
  7600. // input for next layer
  7601. inpL = cur;
  7602. }
  7603. cur = inpL;
  7604. cur = llm_build_norm(ctx0, cur, hparams,
  7605. model.output_norm, NULL,
  7606. LLM_NORM_RMS, cb, -1);
  7607. cb(cur, "result_norm", -1);
  7608. // lm_head
  7609. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7610. cb(cur, "result_output", -1);
  7611. ggml_build_forward_expand(gf, cur);
  7612. return gf;
  7613. }
  7614. struct ggml_cgraph * build_baichuan() {
  7615. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7616. const int64_t n_embd_head = hparams.n_embd_head_v;
  7617. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7618. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7619. struct ggml_tensor * cur;
  7620. struct ggml_tensor * inpL;
  7621. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7622. // inp_pos - contains the positions
  7623. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  7624. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7625. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7626. for (int il = 0; il < n_layer; ++il) {
  7627. struct ggml_tensor * inpSA = inpL;
  7628. cur = llm_build_norm(ctx0, inpL, hparams,
  7629. model.layers[il].attn_norm, NULL,
  7630. LLM_NORM_RMS, cb, il);
  7631. cb(cur, "attn_norm", il);
  7632. // self-attention
  7633. {
  7634. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7635. cb(Qcur, "Qcur", il);
  7636. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7637. cb(Kcur, "Kcur", il);
  7638. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7639. cb(Vcur, "Vcur", il);
  7640. switch (model.type) {
  7641. case MODEL_7B:
  7642. Qcur = ggml_rope_ext(
  7643. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7644. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7645. ext_factor, attn_factor, beta_fast, beta_slow
  7646. );
  7647. Kcur = ggml_rope_ext(
  7648. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7649. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7650. ext_factor, attn_factor, beta_fast, beta_slow
  7651. );
  7652. break;
  7653. case MODEL_13B:
  7654. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  7655. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  7656. break;
  7657. default:
  7658. GGML_ABORT("fatal error");
  7659. }
  7660. cb(Qcur, "Qcur", il);
  7661. cb(Kcur, "Kcur", il);
  7662. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7663. model.layers[il].wo, NULL,
  7664. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7665. }
  7666. if (il == n_layer - 1) {
  7667. // skip computing output for unused tokens
  7668. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7669. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7670. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7671. }
  7672. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7673. cb(ffn_inp, "ffn_inp", il);
  7674. // feed-forward network
  7675. {
  7676. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7677. model.layers[il].ffn_norm, NULL,
  7678. LLM_NORM_RMS, cb, il);
  7679. cb(cur, "ffn_norm", il);
  7680. cur = llm_build_ffn(ctx0, lctx, cur,
  7681. model.layers[il].ffn_up, NULL, NULL,
  7682. model.layers[il].ffn_gate, NULL, NULL,
  7683. model.layers[il].ffn_down, NULL, NULL,
  7684. NULL,
  7685. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7686. cb(cur, "ffn_out", il);
  7687. }
  7688. cur = ggml_add(ctx0, cur, ffn_inp);
  7689. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7690. cb(cur, "l_out", il);
  7691. // input for next layer
  7692. inpL = cur;
  7693. }
  7694. cur = inpL;
  7695. cur = llm_build_norm(ctx0, cur, hparams,
  7696. model.output_norm, NULL,
  7697. LLM_NORM_RMS, cb, -1);
  7698. cb(cur, "result_norm", -1);
  7699. // lm_head
  7700. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7701. cb(cur, "result_output", -1);
  7702. ggml_build_forward_expand(gf, cur);
  7703. return gf;
  7704. }
  7705. struct ggml_cgraph * build_xverse() {
  7706. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7707. const int64_t n_embd_head = hparams.n_embd_head_v;
  7708. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7709. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7710. struct ggml_tensor * cur;
  7711. struct ggml_tensor * inpL;
  7712. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7713. // inp_pos - contains the positions
  7714. struct ggml_tensor * inp_pos = build_inp_pos();
  7715. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7716. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7717. for (int il = 0; il < n_layer; ++il) {
  7718. struct ggml_tensor * inpSA = inpL;
  7719. cur = llm_build_norm(ctx0, inpL, hparams,
  7720. model.layers[il].attn_norm, NULL,
  7721. LLM_NORM_RMS, cb, il);
  7722. cb(cur, "attn_norm", il);
  7723. // self-attention
  7724. {
  7725. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7726. cb(Qcur, "Qcur", il);
  7727. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7728. cb(Kcur, "Kcur", il);
  7729. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7730. cb(Vcur, "Vcur", il);
  7731. Qcur = ggml_rope_ext(
  7732. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7733. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7734. ext_factor, attn_factor, beta_fast, beta_slow
  7735. );
  7736. cb(Qcur, "Qcur", il);
  7737. Kcur = ggml_rope_ext(
  7738. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7739. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7740. ext_factor, attn_factor, beta_fast, beta_slow
  7741. );
  7742. cb(Kcur, "Kcur", il);
  7743. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7744. model.layers[il].wo, NULL,
  7745. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7746. }
  7747. if (il == n_layer - 1) {
  7748. // skip computing output for unused tokens
  7749. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7750. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7751. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7752. }
  7753. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7754. cb(ffn_inp, "ffn_inp", il);
  7755. // feed-forward network
  7756. {
  7757. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7758. model.layers[il].ffn_norm, NULL,
  7759. LLM_NORM_RMS, cb, il);
  7760. cb(cur, "ffn_norm", il);
  7761. cur = llm_build_ffn(ctx0, lctx, cur,
  7762. model.layers[il].ffn_up, NULL, NULL,
  7763. model.layers[il].ffn_gate, NULL, NULL,
  7764. model.layers[il].ffn_down, NULL, NULL,
  7765. NULL,
  7766. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7767. cb(cur, "ffn_out", il);
  7768. }
  7769. cur = ggml_add(ctx0, cur, ffn_inp);
  7770. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7771. cb(cur, "l_out", il);
  7772. // input for next layer
  7773. inpL = cur;
  7774. }
  7775. cur = inpL;
  7776. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  7777. cb(cur, "result_norm", -1);
  7778. // lm_head
  7779. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7780. cb(cur, "result_output", -1);
  7781. ggml_build_forward_expand(gf, cur);
  7782. return gf;
  7783. }
  7784. struct ggml_cgraph * build_falcon() {
  7785. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7786. const int64_t n_embd_head = hparams.n_embd_head_v;
  7787. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7788. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7789. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7790. struct ggml_tensor * cur;
  7791. struct ggml_tensor * inpL;
  7792. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7793. // inp_pos - contains the positions
  7794. struct ggml_tensor * inp_pos = build_inp_pos();
  7795. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7796. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7797. for (int il = 0; il < n_layer; ++il) {
  7798. struct ggml_tensor * attn_norm;
  7799. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  7800. model.layers[il].attn_norm,
  7801. model.layers[il].attn_norm_b,
  7802. LLM_NORM, cb, il);
  7803. cb(attn_norm, "attn_norm", il);
  7804. // self-attention
  7805. {
  7806. if (model.layers[il].attn_norm_2) {
  7807. // Falcon-40B
  7808. cur = llm_build_norm(ctx0, inpL, hparams,
  7809. model.layers[il].attn_norm_2,
  7810. model.layers[il].attn_norm_2_b,
  7811. LLM_NORM, cb, il);
  7812. cb(cur, "attn_norm_2", il);
  7813. } else {
  7814. cur = attn_norm;
  7815. }
  7816. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  7817. cb(cur, "wqkv", il);
  7818. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7819. 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)));
  7820. 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)));
  7821. cb(Qcur, "Qcur", il);
  7822. cb(Kcur, "Kcur", il);
  7823. cb(Vcur, "Vcur", il);
  7824. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7825. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7826. // using mode = 2 for neox mode
  7827. Qcur = ggml_rope_ext(
  7828. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7829. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7830. );
  7831. cb(Qcur, "Qcur", il);
  7832. Kcur = ggml_rope_ext(
  7833. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7834. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7835. );
  7836. cb(Kcur, "Kcur", il);
  7837. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7838. model.layers[il].wo, NULL,
  7839. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7840. }
  7841. if (il == n_layer - 1) {
  7842. // skip computing output for unused tokens
  7843. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7844. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7845. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7846. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  7847. }
  7848. struct ggml_tensor * ffn_inp = cur;
  7849. // feed forward
  7850. {
  7851. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  7852. model.layers[il].ffn_up, NULL, NULL,
  7853. NULL, NULL, NULL,
  7854. model.layers[il].ffn_down, NULL, NULL,
  7855. NULL,
  7856. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7857. cb(cur, "ffn_out", il);
  7858. }
  7859. cur = ggml_add(ctx0, cur, ffn_inp);
  7860. cur = ggml_add(ctx0, cur, inpL);
  7861. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7862. cb(cur, "l_out", il);
  7863. // input for next layer
  7864. inpL = cur;
  7865. }
  7866. cur = inpL;
  7867. // norm
  7868. cur = llm_build_norm(ctx0, cur, hparams,
  7869. model.output_norm,
  7870. model.output_norm_b,
  7871. LLM_NORM, cb, -1);
  7872. cb(cur, "result_norm", -1);
  7873. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7874. cb(cur, "result_output", -1);
  7875. ggml_build_forward_expand(gf, cur);
  7876. return gf;
  7877. }
  7878. struct ggml_cgraph * build_grok() {
  7879. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7880. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7881. int32_t n_tokens = this->n_tokens;
  7882. const int64_t n_embd_head = hparams.n_embd_head_v;
  7883. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7884. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7885. struct ggml_tensor * cur;
  7886. struct ggml_tensor * inpL;
  7887. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7888. // multiply by embedding_multiplier_scale of 78.38367176906169
  7889. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  7890. // inp_pos - contains the positions
  7891. struct ggml_tensor * inp_pos = build_inp_pos();
  7892. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7893. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7894. for (int il = 0; il < n_layer; ++il) {
  7895. struct ggml_tensor * inpSA = inpL;
  7896. // norm
  7897. cur = llm_build_norm(ctx0, inpL, hparams,
  7898. model.layers[il].attn_norm, NULL,
  7899. LLM_NORM_RMS, cb, il);
  7900. cb(cur, "attn_norm", il);
  7901. // self-attention
  7902. {
  7903. // compute Q and K and RoPE them
  7904. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7905. cb(Qcur, "Qcur", il);
  7906. if (model.layers[il].bq) {
  7907. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7908. cb(Qcur, "Qcur", il);
  7909. }
  7910. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7911. cb(Kcur, "Kcur", il);
  7912. if (model.layers[il].bk) {
  7913. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7914. cb(Kcur, "Kcur", il);
  7915. }
  7916. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7917. cb(Vcur, "Vcur", il);
  7918. if (model.layers[il].bv) {
  7919. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7920. cb(Vcur, "Vcur", il);
  7921. }
  7922. Qcur = ggml_rope_ext(
  7923. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7924. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7925. ext_factor, attn_factor, beta_fast, beta_slow
  7926. );
  7927. cb(Qcur, "Qcur", il);
  7928. Kcur = ggml_rope_ext(
  7929. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7930. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7931. ext_factor, attn_factor, beta_fast, beta_slow
  7932. );
  7933. cb(Kcur, "Kcur", il);
  7934. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7935. model.layers[il].wo, model.layers[il].bo,
  7936. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7937. }
  7938. if (il == n_layer - 1) {
  7939. // skip computing output for unused tokens
  7940. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7941. n_tokens = n_outputs;
  7942. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7943. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7944. }
  7945. // Grok
  7946. // if attn_out_norm is present then apply it before adding the input
  7947. if (model.layers[il].attn_out_norm) {
  7948. cur = llm_build_norm(ctx0, cur, hparams,
  7949. model.layers[il].attn_out_norm, NULL,
  7950. LLM_NORM_RMS, cb, il);
  7951. cb(cur, "attn_out_norm", il);
  7952. }
  7953. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7954. cb(ffn_inp, "ffn_inp", il);
  7955. // feed-forward network
  7956. // MoE branch
  7957. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7958. model.layers[il].ffn_norm, NULL,
  7959. LLM_NORM_RMS, cb, il);
  7960. cb(cur, "ffn_norm", il);
  7961. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7962. model.layers[il].ffn_gate_inp,
  7963. model.layers[il].ffn_up_exps,
  7964. model.layers[il].ffn_gate_exps,
  7965. model.layers[il].ffn_down_exps,
  7966. n_expert, n_expert_used,
  7967. LLM_FFN_GELU, true,
  7968. false, 0.0,
  7969. cb, il);
  7970. cb(cur, "ffn_moe_out", il);
  7971. // Grok
  7972. // if layer_out_norm is present then apply it before adding the input
  7973. // Idea: maybe ffn_out_norm is a better name
  7974. if (model.layers[il].layer_out_norm) {
  7975. cur = llm_build_norm(ctx0, cur, hparams,
  7976. model.layers[il].layer_out_norm, NULL,
  7977. LLM_NORM_RMS, cb, il);
  7978. cb(cur, "layer_out_norm", il);
  7979. }
  7980. cur = ggml_add(ctx0, cur, ffn_inp);
  7981. cb(cur, "ffn_out", il);
  7982. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7983. cb(cur, "l_out", il);
  7984. // input for next layer
  7985. inpL = cur;
  7986. }
  7987. cur = inpL;
  7988. cur = llm_build_norm(ctx0, cur, hparams,
  7989. model.output_norm, NULL,
  7990. LLM_NORM_RMS, cb, -1);
  7991. cb(cur, "result_norm", -1);
  7992. // lm_head
  7993. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7994. // Grok
  7995. // multiply logits by output_multiplier_scale of 0.5773502691896257
  7996. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  7997. cb(cur, "result_output", -1);
  7998. ggml_build_forward_expand(gf, cur);
  7999. return gf;
  8000. }
  8001. struct ggml_cgraph * build_dbrx() {
  8002. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8003. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8004. int32_t n_tokens = this->n_tokens;
  8005. const int64_t n_embd_head = hparams.n_embd_head_v;
  8006. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8007. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8008. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8009. struct ggml_tensor * cur;
  8010. struct ggml_tensor * inpL;
  8011. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8012. // inp_pos - contains the positions
  8013. struct ggml_tensor * inp_pos = build_inp_pos();
  8014. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8015. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8016. for (int il = 0; il < n_layer; ++il) {
  8017. struct ggml_tensor * inpSA = inpL;
  8018. // norm
  8019. cur = llm_build_norm(ctx0, inpL, hparams,
  8020. model.layers[il].attn_norm, NULL,
  8021. LLM_NORM, cb, il);
  8022. cb(cur, "attn_norm", il);
  8023. // self-attention
  8024. {
  8025. struct ggml_tensor * Qcur = nullptr;
  8026. struct ggml_tensor * Kcur = nullptr;
  8027. struct ggml_tensor * Vcur = nullptr;
  8028. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8029. cb(cur, "wqkv", il);
  8030. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8031. cb(cur, "wqkv_clamped", il);
  8032. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8033. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8034. 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)));
  8035. cb(Qcur, "Qcur", il);
  8036. cb(Kcur, "Kcur", il);
  8037. cb(Vcur, "Vcur", il);
  8038. Qcur = ggml_rope_ext(
  8039. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8040. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8041. ext_factor, attn_factor, beta_fast, beta_slow
  8042. );
  8043. cb(Qcur, "Qcur", il);
  8044. Kcur = ggml_rope_ext(
  8045. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8046. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8047. ext_factor, attn_factor, beta_fast, beta_slow
  8048. );
  8049. cb(Kcur, "Kcur", il);
  8050. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8051. model.layers[il].wo, NULL,
  8052. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8053. }
  8054. if (il == n_layer - 1) {
  8055. // skip computing output for unused tokens
  8056. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8057. n_tokens = n_outputs;
  8058. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8059. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8060. }
  8061. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8062. cb(ffn_inp, "ffn_inp", il);
  8063. // feed-forward network
  8064. // MoE branch
  8065. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8066. model.layers[il].attn_out_norm, NULL,
  8067. LLM_NORM, cb, il);
  8068. cb(cur, "attn_out_norm", il);
  8069. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8070. model.layers[il].ffn_gate_inp,
  8071. model.layers[il].ffn_up_exps,
  8072. model.layers[il].ffn_gate_exps,
  8073. model.layers[il].ffn_down_exps,
  8074. n_expert, n_expert_used,
  8075. LLM_FFN_SILU, true,
  8076. false, 0.0,
  8077. cb, il);
  8078. cb(cur, "ffn_moe_out", il);
  8079. cur = ggml_add(ctx0, cur, ffn_inp);
  8080. cb(cur, "ffn_out", il);
  8081. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8082. cb(cur, "l_out", il);
  8083. // input for next layer
  8084. inpL = cur;
  8085. }
  8086. cur = inpL;
  8087. cur = llm_build_norm(ctx0, cur, hparams,
  8088. model.output_norm, NULL,
  8089. LLM_NORM, cb, -1);
  8090. cb(cur, "result_norm", -1);
  8091. // lm_head
  8092. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8093. cb(cur, "result_output", -1);
  8094. ggml_build_forward_expand(gf, cur);
  8095. return gf;
  8096. }
  8097. struct ggml_cgraph * build_starcoder() {
  8098. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8099. const int64_t n_embd_head = hparams.n_embd_head_v;
  8100. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8101. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8102. struct ggml_tensor * cur;
  8103. struct ggml_tensor * inpL;
  8104. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8105. // inp_pos - contains the positions
  8106. struct ggml_tensor * inp_pos = build_inp_pos();
  8107. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8108. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8109. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8110. cb(pos, "pos_embd", -1);
  8111. inpL = ggml_add(ctx0, inpL, pos);
  8112. cb(inpL, "inpL", -1);
  8113. for (int il = 0; il < n_layer; ++il) {
  8114. cur = llm_build_norm(ctx0, inpL, hparams,
  8115. model.layers[il].attn_norm,
  8116. model.layers[il].attn_norm_b,
  8117. LLM_NORM, cb, il);
  8118. cb(cur, "attn_norm", il);
  8119. // self-attention
  8120. {
  8121. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8122. cb(cur, "wqkv", il);
  8123. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8124. cb(cur, "bqkv", il);
  8125. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8126. 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)));
  8127. 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)));
  8128. cb(Qcur, "Qcur", il);
  8129. cb(Kcur, "Kcur", il);
  8130. cb(Vcur, "Vcur", il);
  8131. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8132. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8133. model.layers[il].wo, model.layers[il].bo,
  8134. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8135. }
  8136. if (il == n_layer - 1) {
  8137. // skip computing output for unused tokens
  8138. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8139. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8140. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8141. }
  8142. // add the input
  8143. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8144. cb(ffn_inp, "ffn_inp", il);
  8145. // FF
  8146. {
  8147. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8148. model.layers[il].ffn_norm,
  8149. model.layers[il].ffn_norm_b,
  8150. LLM_NORM, cb, il);
  8151. cb(cur, "ffn_norm", il);
  8152. cur = llm_build_ffn(ctx0, lctx, cur,
  8153. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8154. NULL, NULL, NULL,
  8155. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8156. NULL,
  8157. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8158. cb(cur, "ffn_out", il);
  8159. }
  8160. cur = ggml_add(ctx0, cur, ffn_inp);
  8161. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8162. cb(cur, "l_out", il);
  8163. // input for next layer
  8164. inpL = cur;
  8165. }
  8166. cur = llm_build_norm(ctx0, inpL, hparams,
  8167. model.output_norm,
  8168. model.output_norm_b,
  8169. LLM_NORM, cb, -1);
  8170. cb(cur, "result_norm", -1);
  8171. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8172. cb(cur, "result_output", -1);
  8173. ggml_build_forward_expand(gf, cur);
  8174. return gf;
  8175. }
  8176. struct ggml_cgraph * build_refact() {
  8177. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8178. const int64_t n_embd_head = hparams.n_embd_head_v;
  8179. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8180. struct ggml_tensor * cur;
  8181. struct ggml_tensor * inpL;
  8182. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8183. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8184. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8185. for (int il = 0; il < n_layer; ++il) {
  8186. struct ggml_tensor * inpSA = inpL;
  8187. cur = llm_build_norm(ctx0, inpL, hparams,
  8188. model.layers[il].attn_norm, NULL,
  8189. LLM_NORM_RMS, cb, il);
  8190. cb(cur, "attn_norm", il);
  8191. // self-attention
  8192. {
  8193. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8194. cb(Qcur, "Qcur", il);
  8195. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8196. cb(Kcur, "Kcur", il);
  8197. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8198. cb(Vcur, "Vcur", il);
  8199. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8200. cb(Kcur, "Kcur", il);
  8201. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8202. cb(Qcur, "Qcur", il);
  8203. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8204. model.layers[il].wo, NULL,
  8205. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8206. }
  8207. if (il == n_layer - 1) {
  8208. // skip computing output for unused tokens
  8209. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8210. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8211. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8212. }
  8213. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8214. cb(ffn_inp, "ffn_inp", il);
  8215. // feed-forward network
  8216. {
  8217. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8218. model.layers[il].ffn_norm, NULL,
  8219. LLM_NORM_RMS, cb, il);
  8220. cb(cur, "ffn_norm", il);
  8221. cur = llm_build_ffn(ctx0, lctx, cur,
  8222. model.layers[il].ffn_up, NULL, NULL,
  8223. model.layers[il].ffn_gate, NULL, NULL,
  8224. model.layers[il].ffn_down, NULL, NULL,
  8225. NULL,
  8226. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8227. cb(cur, "ffn_out", il);
  8228. }
  8229. cur = ggml_add(ctx0, cur, ffn_inp);
  8230. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8231. cb(cur, "l_out", il);
  8232. // input for next layer
  8233. inpL = cur;
  8234. }
  8235. cur = inpL;
  8236. cur = llm_build_norm(ctx0, cur, hparams,
  8237. model.output_norm, NULL,
  8238. LLM_NORM_RMS, cb, -1);
  8239. cb(cur, "result_norm", -1);
  8240. // lm_head
  8241. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8242. cb(cur, "result_output", -1);
  8243. ggml_build_forward_expand(gf, cur);
  8244. return gf;
  8245. }
  8246. struct ggml_cgraph * build_bert() {
  8247. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8248. const int64_t n_embd_head = hparams.n_embd_head_v;
  8249. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8250. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8251. struct ggml_tensor * cur;
  8252. struct ggml_tensor * inpL;
  8253. struct ggml_tensor * inp_pos = nullptr;
  8254. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  8255. inp_pos = build_inp_pos();
  8256. }
  8257. // construct input embeddings (token, type, position)
  8258. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8259. // token types are hardcoded to zero ("Sentence A")
  8260. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  8261. inpL = ggml_add(ctx0, inpL, type_row0);
  8262. if (model.arch == LLM_ARCH_BERT) {
  8263. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  8264. }
  8265. cb(inpL, "inp_embd", -1);
  8266. // embed layer norm
  8267. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  8268. cb(inpL, "inp_norm", -1);
  8269. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8270. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  8271. // iterate layers
  8272. for (int il = 0; il < n_layer; ++il) {
  8273. struct ggml_tensor * cur = inpL;
  8274. struct ggml_tensor * Qcur;
  8275. struct ggml_tensor * Kcur;
  8276. struct ggml_tensor * Vcur;
  8277. // self-attention
  8278. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  8279. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  8280. cb(Qcur, "Qcur", il);
  8281. if (model.layers[il].attn_q_norm) {
  8282. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8283. model.layers[il].attn_q_norm,
  8284. model.layers[il].attn_q_norm_b,
  8285. LLM_NORM, cb, il);
  8286. }
  8287. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  8288. cb(Kcur, "Kcur", il);
  8289. if (model.layers[il].attn_k_norm) {
  8290. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8291. model.layers[il].attn_k_norm,
  8292. model.layers[il].attn_k_norm_b,
  8293. LLM_NORM, cb, il);
  8294. }
  8295. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  8296. cb(Vcur, "Vcur", il);
  8297. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8298. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8299. } else {
  8300. // compute Q and K and RoPE them
  8301. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8302. cb(cur, "wqkv", il);
  8303. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8304. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8305. 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)));
  8306. cb(Qcur, "Qcur", il);
  8307. cb(Kcur, "Kcur", il);
  8308. cb(Vcur, "Vcur", il);
  8309. Qcur = ggml_rope_ext(
  8310. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8311. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8312. ext_factor, attn_factor, beta_fast, beta_slow
  8313. );
  8314. cb(Qcur, "Qcur", il);
  8315. Kcur = ggml_rope_ext(
  8316. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8317. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8318. ext_factor, attn_factor, beta_fast, beta_slow
  8319. );
  8320. cb(Kcur, "Kcur", il);
  8321. }
  8322. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  8323. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  8324. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  8325. cb(kq, "kq", il);
  8326. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  8327. cb(kq, "kq_soft_max_ext", il);
  8328. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  8329. cb(v, "v", il);
  8330. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  8331. cb(kqv, "kqv", il);
  8332. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  8333. cb(kqv_merged, "kqv_merged", il);
  8334. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  8335. cb(cur, "kqv_merged_cont", il);
  8336. ggml_build_forward_expand(gf, cur);
  8337. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  8338. if (model.layers[il].bo) {
  8339. cb(cur, "kqv_wo", il);
  8340. }
  8341. if (model.layers[il].bo) {
  8342. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  8343. }
  8344. cb(cur, "kqv_out", il);
  8345. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8346. // skip computing output for unused tokens
  8347. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8348. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8349. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8350. }
  8351. // re-add the layer input
  8352. cur = ggml_add(ctx0, cur, inpL);
  8353. // attention layer norm
  8354. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  8355. if (model.layers[il].attn_norm_2 != nullptr) {
  8356. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  8357. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  8358. }
  8359. struct ggml_tensor * ffn_inp = cur;
  8360. cb(ffn_inp, "ffn_inp", il);
  8361. // feed-forward network
  8362. if (model.arch == LLM_ARCH_BERT) {
  8363. cur = llm_build_ffn(ctx0, lctx, cur,
  8364. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8365. NULL, NULL, NULL,
  8366. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8367. NULL,
  8368. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8369. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  8370. cur = llm_build_ffn(ctx0, lctx, cur,
  8371. model.layers[il].ffn_up, NULL, NULL,
  8372. model.layers[il].ffn_gate, NULL, NULL,
  8373. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8374. NULL,
  8375. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  8376. } else {
  8377. cur = llm_build_ffn(ctx0, lctx, cur,
  8378. model.layers[il].ffn_up, NULL, NULL,
  8379. model.layers[il].ffn_gate, NULL, NULL,
  8380. model.layers[il].ffn_down, NULL, NULL,
  8381. NULL,
  8382. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8383. }
  8384. cb(cur, "ffn_out", il);
  8385. // attentions bypass the intermediate layer
  8386. cur = ggml_add(ctx0, cur, ffn_inp);
  8387. // output layer norm
  8388. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  8389. // input for next layer
  8390. inpL = cur;
  8391. }
  8392. // final output
  8393. cur = inpL;
  8394. cb(cur, "result_embd", -1);
  8395. ggml_build_forward_expand(gf, cur);
  8396. return gf;
  8397. }
  8398. struct ggml_cgraph * build_bloom() {
  8399. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8400. const int64_t n_embd_head = hparams.n_embd_head_v;
  8401. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8402. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8403. struct ggml_tensor * cur;
  8404. struct ggml_tensor * inpL;
  8405. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8406. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8407. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8408. inpL = llm_build_norm(ctx0, inpL, hparams,
  8409. model.tok_norm,
  8410. model.tok_norm_b,
  8411. LLM_NORM, cb, -1);
  8412. cb(inpL, "inp_norm", -1);
  8413. for (int il = 0; il < n_layer; ++il) {
  8414. cur = llm_build_norm(ctx0, inpL, hparams,
  8415. model.layers[il].attn_norm,
  8416. model.layers[il].attn_norm_b,
  8417. LLM_NORM, cb, il);
  8418. cb(cur, "attn_norm", il);
  8419. // self-attention
  8420. {
  8421. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8422. cb(cur, "wqkv", il);
  8423. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8424. cb(cur, "bqkv", il);
  8425. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8426. 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)));
  8427. 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)));
  8428. cb(Qcur, "Qcur", il);
  8429. cb(Kcur, "Kcur", il);
  8430. cb(Vcur, "Vcur", il);
  8431. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8432. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8433. model.layers[il].wo, model.layers[il].bo,
  8434. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8435. }
  8436. if (il == n_layer - 1) {
  8437. // skip computing output for unused tokens
  8438. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8439. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8440. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8441. }
  8442. // Add the input
  8443. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8444. cb(ffn_inp, "ffn_inp", il);
  8445. // FF
  8446. {
  8447. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8448. model.layers[il].ffn_norm,
  8449. model.layers[il].ffn_norm_b,
  8450. LLM_NORM, cb, il);
  8451. cb(cur, "ffn_norm", il);
  8452. cur = llm_build_ffn(ctx0, lctx, cur,
  8453. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8454. NULL, NULL, NULL,
  8455. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8456. NULL,
  8457. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8458. cb(cur, "ffn_out", il);
  8459. }
  8460. cur = ggml_add(ctx0, cur, ffn_inp);
  8461. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8462. cb(cur, "l_out", il);
  8463. // input for next layer
  8464. inpL = cur;
  8465. }
  8466. cur = llm_build_norm(ctx0, inpL, hparams,
  8467. model.output_norm,
  8468. model.output_norm_b,
  8469. LLM_NORM, cb, -1);
  8470. cb(cur, "result_norm", -1);
  8471. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8472. cb(cur, "result_output", -1);
  8473. ggml_build_forward_expand(gf, cur);
  8474. return gf;
  8475. }
  8476. struct ggml_cgraph * build_mpt() {
  8477. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8478. const int64_t n_embd_head = hparams.n_embd_head_v;
  8479. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8480. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8481. struct ggml_tensor * cur;
  8482. struct ggml_tensor * pos;
  8483. struct ggml_tensor * inpL;
  8484. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8485. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8486. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8487. if (model.pos_embd) {
  8488. // inp_pos - contains the positions
  8489. struct ggml_tensor * inp_pos = build_inp_pos();
  8490. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8491. cb(pos, "pos_embd", -1);
  8492. inpL = ggml_add(ctx0, inpL, pos);
  8493. cb(inpL, "inpL", -1);
  8494. }
  8495. for (int il = 0; il < n_layer; ++il) {
  8496. struct ggml_tensor * attn_norm;
  8497. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  8498. model.layers[il].attn_norm,
  8499. model.layers[il].attn_norm_b,
  8500. LLM_NORM, cb, il);
  8501. cb(attn_norm, "attn_norm", il);
  8502. // self-attention
  8503. {
  8504. cur = attn_norm;
  8505. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8506. cb(cur, "wqkv", il);
  8507. if (model.layers[il].bqkv){
  8508. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8509. cb(cur, "bqkv", il);
  8510. }
  8511. if (hparams.f_clamp_kqv > 0.0f) {
  8512. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8513. cb(cur, "wqkv_clamped", il);
  8514. }
  8515. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8516. 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)));
  8517. 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)));
  8518. cb(Qcur, "Qcur", il);
  8519. cb(Kcur, "Kcur", il);
  8520. cb(Vcur, "Vcur", il);
  8521. // Q/K Layernorm
  8522. if (model.layers[il].attn_q_norm) {
  8523. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8524. model.layers[il].attn_q_norm,
  8525. model.layers[il].attn_q_norm_b,
  8526. LLM_NORM, cb, il);
  8527. cb(Qcur, "Qcur", il);
  8528. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8529. model.layers[il].attn_k_norm,
  8530. model.layers[il].attn_k_norm_b,
  8531. LLM_NORM, cb, il);
  8532. cb(Kcur, "Kcur", il);
  8533. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8534. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8535. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8536. model.layers[il].wo, model.layers[il].bo,
  8537. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8538. } else {
  8539. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8540. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8541. model.layers[il].wo, model.layers[il].bo,
  8542. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8543. }
  8544. }
  8545. if (il == n_layer - 1) {
  8546. // skip computing output for unused tokens
  8547. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8548. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8549. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8550. }
  8551. // Add the input
  8552. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8553. cb(ffn_inp, "ffn_inp", il);
  8554. // feed forward
  8555. {
  8556. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8557. model.layers[il].ffn_norm,
  8558. model.layers[il].ffn_norm_b,
  8559. LLM_NORM, cb, il);
  8560. cb(cur, "ffn_norm", il);
  8561. cur = llm_build_ffn(ctx0, lctx, cur,
  8562. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8563. NULL, NULL, NULL,
  8564. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8565. model.layers[il].ffn_act,
  8566. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8567. cb(cur, "ffn_out", il);
  8568. }
  8569. cur = ggml_add(ctx0, cur, ffn_inp);
  8570. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8571. cb(cur, "l_out", il);
  8572. // input for next layer
  8573. inpL = cur;
  8574. }
  8575. cur = inpL;
  8576. cur = llm_build_norm(ctx0, cur, hparams,
  8577. model.output_norm,
  8578. model.output_norm_b,
  8579. LLM_NORM, cb, -1);
  8580. cb(cur, "result_norm", -1);
  8581. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8582. cb(cur, "result_output", -1);
  8583. ggml_build_forward_expand(gf, cur);
  8584. return gf;
  8585. }
  8586. struct ggml_cgraph * build_stablelm() {
  8587. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  8588. const int64_t n_embd_head = hparams.n_embd_head_v;
  8589. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8590. struct ggml_tensor * cur;
  8591. struct ggml_tensor * inpL;
  8592. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8593. // inp_pos - contains the positions
  8594. struct ggml_tensor * inp_pos = build_inp_pos();
  8595. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8596. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8597. for (int il = 0; il < n_layer; ++il) {
  8598. // norm
  8599. cur = llm_build_norm(ctx0, inpL, hparams,
  8600. model.layers[il].attn_norm,
  8601. model.layers[il].attn_norm_b,
  8602. LLM_NORM, cb, il);
  8603. cb(cur, "attn_norm", il);
  8604. struct ggml_tensor * inpSA = cur;
  8605. // self-attention
  8606. {
  8607. // compute Q and K and RoPE them
  8608. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8609. cb(Qcur, "Qcur", il);
  8610. if (model.layers[il].bq) {
  8611. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8612. cb(Qcur, "Qcur", il);
  8613. }
  8614. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8615. cb(Kcur, "Kcur", il);
  8616. if (model.layers[il].bk) {
  8617. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8618. cb(Kcur, "Kcur", il);
  8619. }
  8620. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8621. cb(Vcur, "Vcur", il);
  8622. if (model.layers[il].bv) {
  8623. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8624. cb(Vcur, "Vcur", il);
  8625. }
  8626. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8627. cb(Qcur, "Qcur", il);
  8628. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8629. cb(Kcur, "Kcur", il);
  8630. if (model.layers[il].attn_q_norm) {
  8631. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8632. model.layers[il].attn_q_norm,
  8633. NULL,
  8634. LLM_NORM, cb, il);
  8635. cb(Qcur, "Qcur", il);
  8636. }
  8637. if (model.layers[il].attn_k_norm) {
  8638. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8639. model.layers[il].attn_k_norm,
  8640. NULL,
  8641. LLM_NORM, cb, il);
  8642. cb(Kcur, "Kcur", il);
  8643. }
  8644. Qcur = ggml_rope_ext(
  8645. ctx0, Qcur, inp_pos, nullptr,
  8646. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8647. ext_factor, attn_factor, beta_fast, beta_slow
  8648. );
  8649. cb(Qcur, "Qcur", il);
  8650. Kcur = ggml_rope_ext(
  8651. ctx0, Kcur, inp_pos, nullptr,
  8652. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8653. ext_factor, attn_factor, beta_fast, beta_slow
  8654. );
  8655. cb(Kcur, "Kcur", il);
  8656. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8657. model.layers[il].wo, NULL,
  8658. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8659. }
  8660. if (il == n_layer - 1) {
  8661. // skip computing output for unused tokens
  8662. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8663. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8664. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8665. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8666. }
  8667. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8668. cb(ffn_inp, "ffn_inp", il);
  8669. // feed-forward network
  8670. {
  8671. if (model.layers[il].ffn_norm) {
  8672. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8673. model.layers[il].ffn_norm,
  8674. model.layers[il].ffn_norm_b,
  8675. LLM_NORM, cb, il);
  8676. cb(cur, "ffn_norm", il);
  8677. } else {
  8678. // parallel residual
  8679. cur = inpSA;
  8680. }
  8681. cur = llm_build_ffn(ctx0, lctx, cur,
  8682. model.layers[il].ffn_up, NULL, NULL,
  8683. model.layers[il].ffn_gate, NULL, NULL,
  8684. model.layers[il].ffn_down, NULL, NULL,
  8685. NULL,
  8686. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8687. cb(cur, "ffn_out", il);
  8688. }
  8689. cur = ggml_add(ctx0, cur, ffn_inp);
  8690. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8691. cb(cur, "l_out", il);
  8692. // input for next layer
  8693. inpL = cur;
  8694. }
  8695. cur = inpL;
  8696. cur = llm_build_norm(ctx0, cur, hparams,
  8697. model.output_norm,
  8698. model.output_norm_b,
  8699. LLM_NORM, cb, -1);
  8700. cb(cur, "result_norm", -1);
  8701. // lm_head
  8702. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8703. cb(cur, "result_output", -1);
  8704. ggml_build_forward_expand(gf, cur);
  8705. return gf;
  8706. }
  8707. struct ggml_cgraph * build_qwen() {
  8708. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8709. const int64_t n_embd_head = hparams.n_embd_head_v;
  8710. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8711. struct ggml_tensor * cur;
  8712. struct ggml_tensor * inpL;
  8713. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8714. // inp_pos - contains the positions
  8715. struct ggml_tensor * inp_pos = build_inp_pos();
  8716. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8717. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8718. for (int il = 0; il < n_layer; ++il) {
  8719. struct ggml_tensor * inpSA = inpL;
  8720. cur = llm_build_norm(ctx0, inpL, hparams,
  8721. model.layers[il].attn_norm, NULL,
  8722. LLM_NORM_RMS, cb, il);
  8723. cb(cur, "attn_norm", il);
  8724. // self-attention
  8725. {
  8726. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8727. cb(cur, "wqkv", il);
  8728. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8729. cb(cur, "bqkv", il);
  8730. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8731. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8732. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  8733. cb(Qcur, "Qcur", il);
  8734. cb(Kcur, "Kcur", il);
  8735. cb(Vcur, "Vcur", il);
  8736. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8737. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8738. // using mode = 2 for neox mode
  8739. Qcur = ggml_rope_ext(
  8740. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8741. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8742. );
  8743. cb(Qcur, "Qcur", il);
  8744. Kcur = ggml_rope_ext(
  8745. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8746. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8747. );
  8748. cb(Kcur, "Kcur", il);
  8749. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8750. model.layers[il].wo, NULL,
  8751. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8752. }
  8753. if (il == n_layer - 1) {
  8754. // skip computing output for unused tokens
  8755. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8756. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8757. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8758. }
  8759. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8760. cb(ffn_inp, "ffn_inp", il);
  8761. // feed-forward forward
  8762. {
  8763. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8764. model.layers[il].ffn_norm, NULL,
  8765. LLM_NORM_RMS, cb, il);
  8766. cb(cur, "ffn_norm", il);
  8767. cur = llm_build_ffn(ctx0, lctx, cur,
  8768. model.layers[il].ffn_up, NULL, NULL,
  8769. model.layers[il].ffn_gate, NULL, NULL,
  8770. model.layers[il].ffn_down, NULL, NULL,
  8771. NULL,
  8772. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8773. cb(cur, "ffn_out", il);
  8774. }
  8775. cur = ggml_add(ctx0, cur, ffn_inp);
  8776. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8777. cb(cur, "l_out", il);
  8778. // input for next layer
  8779. inpL = cur;
  8780. }
  8781. cur = inpL;
  8782. cur = llm_build_norm(ctx0, cur, hparams,
  8783. model.output_norm, NULL,
  8784. LLM_NORM_RMS, cb, -1);
  8785. cb(cur, "result_norm", -1);
  8786. // lm_head
  8787. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8788. cb(cur, "result_output", -1);
  8789. ggml_build_forward_expand(gf, cur);
  8790. return gf;
  8791. }
  8792. struct ggml_cgraph * build_qwen2() {
  8793. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8794. const int64_t n_embd_head = hparams.n_embd_head_v;
  8795. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8796. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8797. struct ggml_tensor * cur;
  8798. struct ggml_tensor * inpL;
  8799. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8800. // inp_pos - contains the positions
  8801. struct ggml_tensor * inp_pos = build_inp_pos();
  8802. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8803. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8804. for (int il = 0; il < n_layer; ++il) {
  8805. struct ggml_tensor * inpSA = inpL;
  8806. // norm
  8807. cur = llm_build_norm(ctx0, inpL, hparams,
  8808. model.layers[il].attn_norm, NULL,
  8809. LLM_NORM_RMS, cb, il);
  8810. cb(cur, "attn_norm", il);
  8811. // self-attention
  8812. {
  8813. // compute Q and K and RoPE them
  8814. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8815. cb(Qcur, "Qcur", il);
  8816. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8817. cb(Qcur, "Qcur", il);
  8818. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8819. cb(Kcur, "Kcur", il);
  8820. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8821. cb(Kcur, "Kcur", il);
  8822. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8823. cb(Vcur, "Vcur", il);
  8824. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8825. cb(Vcur, "Vcur", il);
  8826. Qcur = ggml_rope_ext(
  8827. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8828. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8829. ext_factor, attn_factor, beta_fast, beta_slow
  8830. );
  8831. cb(Qcur, "Qcur", il);
  8832. Kcur = ggml_rope_ext(
  8833. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8834. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8835. ext_factor, attn_factor, beta_fast, beta_slow
  8836. );
  8837. cb(Kcur, "Kcur", il);
  8838. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8839. model.layers[il].wo, model.layers[il].bo,
  8840. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8841. }
  8842. if (il == n_layer - 1) {
  8843. // skip computing output for unused tokens
  8844. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8845. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8846. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8847. }
  8848. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8849. cb(ffn_inp, "ffn_inp", il);
  8850. // feed-forward network
  8851. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8852. model.layers[il].ffn_norm, NULL,
  8853. LLM_NORM_RMS, cb, il);
  8854. cb(cur, "ffn_norm", il);
  8855. cur = llm_build_ffn(ctx0, lctx, cur,
  8856. model.layers[il].ffn_up, NULL, NULL,
  8857. model.layers[il].ffn_gate, NULL, NULL,
  8858. model.layers[il].ffn_down, NULL, NULL,
  8859. NULL,
  8860. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8861. cb(cur, "ffn_out", il);
  8862. cur = ggml_add(ctx0, cur, ffn_inp);
  8863. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8864. cb(cur, "l_out", il);
  8865. // input for next layer
  8866. inpL = cur;
  8867. }
  8868. cur = inpL;
  8869. cur = llm_build_norm(ctx0, cur, hparams,
  8870. model.output_norm, NULL,
  8871. LLM_NORM_RMS, cb, -1);
  8872. cb(cur, "result_norm", -1);
  8873. // lm_head
  8874. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8875. cb(cur, "result_output", -1);
  8876. ggml_build_forward_expand(gf, cur);
  8877. return gf;
  8878. }
  8879. struct ggml_cgraph * build_qwen2moe() {
  8880. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8881. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8882. int32_t n_tokens = this->n_tokens;
  8883. const int64_t n_embd_head = hparams.n_embd_head_v;
  8884. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8885. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8886. struct ggml_tensor * cur;
  8887. struct ggml_tensor * inpL;
  8888. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8889. // inp_pos - contains the positions
  8890. struct ggml_tensor * inp_pos = build_inp_pos();
  8891. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8892. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8893. for (int il = 0; il < n_layer; ++il) {
  8894. struct ggml_tensor * inpSA = inpL;
  8895. // norm
  8896. cur = llm_build_norm(ctx0, inpL, hparams,
  8897. model.layers[il].attn_norm, NULL,
  8898. LLM_NORM_RMS, cb, il);
  8899. cb(cur, "attn_norm", il);
  8900. // self_attention
  8901. {
  8902. // compute Q and K and RoPE them
  8903. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8904. cb(Qcur, "Qcur", il);
  8905. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8906. cb(Qcur, "Qcur", il);
  8907. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8908. cb(Kcur, "Kcur", il);
  8909. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8910. cb(Kcur, "Kcur", il);
  8911. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8912. cb(Vcur, "Vcur", il);
  8913. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8914. cb(Vcur, "Vcur", il);
  8915. Qcur = ggml_rope_ext(
  8916. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8917. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8918. ext_factor, attn_factor, beta_fast, beta_slow
  8919. );
  8920. cb(Qcur, "Qcur", il);
  8921. Kcur = ggml_rope_ext(
  8922. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8923. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8924. ext_factor, attn_factor, beta_fast, beta_slow
  8925. );
  8926. cb(Kcur, "Kcur", il);
  8927. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8928. model.layers[il].wo, model.layers[il].bo,
  8929. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8930. }
  8931. if (il == n_layer - 1) {
  8932. // skip computing output for unused tokens
  8933. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8934. n_tokens = n_outputs;
  8935. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8936. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8937. }
  8938. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8939. cb(ffn_inp, "ffn_inp", il);
  8940. // MoE branch
  8941. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8942. model.layers[il].ffn_norm, NULL,
  8943. LLM_NORM_RMS, cb, il);
  8944. cb(cur, "ffn_norm", il);
  8945. ggml_tensor * moe_out =
  8946. llm_build_moe_ffn(ctx0, lctx, cur,
  8947. model.layers[il].ffn_gate_inp,
  8948. model.layers[il].ffn_up_exps,
  8949. model.layers[il].ffn_gate_exps,
  8950. model.layers[il].ffn_down_exps,
  8951. n_expert, n_expert_used,
  8952. LLM_FFN_SILU, false,
  8953. false, 0.0,
  8954. cb, il);
  8955. cb(cur, "ffn_moe_out", il);
  8956. // FFN shared expert
  8957. {
  8958. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  8959. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  8960. // sigmoid
  8961. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  8962. cb(cur_gate, "ffn_shexp_gate", il);
  8963. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  8964. model.layers[il].ffn_up_shexp, NULL, NULL,
  8965. model.layers[il].ffn_gate_shexp, NULL, NULL,
  8966. model.layers[il].ffn_down_shexp, NULL, NULL,
  8967. NULL,
  8968. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8969. cb(cur_ffn, "ffn_shexp", il);
  8970. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  8971. cb(ffn_shexp_out, "ffn_shexp_out", il);
  8972. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  8973. cb(moe_out, "ffn_out", il);
  8974. cur = moe_out;
  8975. }
  8976. cur = ggml_add(ctx0, cur, ffn_inp);
  8977. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8978. cb(cur, "l_out", il);
  8979. // input for next layer
  8980. inpL = cur;
  8981. }
  8982. cur = inpL;
  8983. cur = llm_build_norm(ctx0, cur, hparams,
  8984. model.output_norm, NULL,
  8985. LLM_NORM_RMS, cb, -1);
  8986. cb(cur, "result_norm", -1);
  8987. // lm_head
  8988. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8989. cb(cur, "result_output", -1);
  8990. ggml_build_forward_expand(gf, cur);
  8991. return gf;
  8992. }
  8993. struct ggml_cgraph * build_phi2() {
  8994. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8995. const int64_t n_embd_head = hparams.n_embd_head_v;
  8996. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8997. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8998. struct ggml_tensor * cur;
  8999. struct ggml_tensor * attn_norm_output;
  9000. struct ggml_tensor * ffn_output;
  9001. struct ggml_tensor * inpL;
  9002. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9003. // inp_pos - contains the positions
  9004. struct ggml_tensor * inp_pos = build_inp_pos();
  9005. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9006. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9007. for (int il = 0; il < n_layer; ++il) {
  9008. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9009. model.layers[il].attn_norm,
  9010. model.layers[il].attn_norm_b,
  9011. LLM_NORM, cb, il);
  9012. cb(attn_norm_output, "attn_norm", il);
  9013. // self-attention
  9014. {
  9015. struct ggml_tensor * Qcur = nullptr;
  9016. struct ggml_tensor * Kcur = nullptr;
  9017. struct ggml_tensor * Vcur = nullptr;
  9018. if (model.layers[il].wqkv) {
  9019. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9020. cb(cur, "wqkv", il);
  9021. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9022. cb(cur, "bqkv", il);
  9023. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9024. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9025. 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)));
  9026. } else {
  9027. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9028. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9029. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9030. }
  9031. cb(Qcur, "Qcur", il);
  9032. cb(Kcur, "Kcur", il);
  9033. cb(Vcur, "Vcur", il);
  9034. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9035. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9036. Qcur = ggml_rope_ext(
  9037. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9038. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9039. );
  9040. cb(Qcur, "Qcur", il);
  9041. // with phi2, we scale the Q to avoid precision issues
  9042. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  9043. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  9044. cb(Qcur, "Qcur", il);
  9045. Kcur = ggml_rope_ext(
  9046. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9047. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9048. );
  9049. cb(Kcur, "Kcur", il);
  9050. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9051. model.layers[il].wo, model.layers[il].bo,
  9052. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9053. }
  9054. if (il == n_layer - 1) {
  9055. // skip computing output for unused tokens
  9056. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9057. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9058. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9059. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  9060. }
  9061. // FF
  9062. {
  9063. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  9064. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9065. NULL, NULL, NULL,
  9066. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9067. NULL,
  9068. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9069. cb(ffn_output, "ffn_out", il);
  9070. }
  9071. cur = ggml_add(ctx0, cur, ffn_output);
  9072. cur = ggml_add(ctx0, cur, inpL);
  9073. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9074. cb(cur, "l_out", il);
  9075. // input for next layer
  9076. inpL = cur;
  9077. }
  9078. cur = llm_build_norm(ctx0, inpL, hparams,
  9079. model.output_norm,
  9080. model.output_norm_b,
  9081. LLM_NORM, cb, -1);
  9082. cb(cur, "result_norm", -1);
  9083. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9084. cb(cur, "result_output_no_bias", -1);
  9085. cur = ggml_add(ctx0, cur, model.output_b);
  9086. cb(cur, "result_output", -1);
  9087. ggml_build_forward_expand(gf, cur);
  9088. return gf;
  9089. }
  9090. struct ggml_cgraph * build_phi3() {
  9091. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9092. const int64_t n_embd_head = hparams.n_embd_head_v;
  9093. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9094. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9095. struct ggml_tensor * cur;
  9096. struct ggml_tensor * inpL;
  9097. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9098. // inp_pos - contains the positions
  9099. struct ggml_tensor * inp_pos = build_inp_pos();
  9100. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9101. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  9102. for (int il = 0; il < n_layer; ++il) {
  9103. auto residual = inpL;
  9104. // self-attention
  9105. {
  9106. // rope freq factors for 128k context
  9107. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9108. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9109. model.layers[il].attn_norm,
  9110. NULL,
  9111. LLM_NORM_RMS, cb, il);
  9112. cb(attn_norm_output, "attn_norm", il);
  9113. struct ggml_tensor * Qcur = nullptr;
  9114. struct ggml_tensor * Kcur = nullptr;
  9115. struct ggml_tensor * Vcur = nullptr;
  9116. if (model.layers[il].wqkv) {
  9117. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9118. cb(cur, "wqkv", il);
  9119. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  9120. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  9121. 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)));
  9122. }
  9123. else {
  9124. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9125. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9126. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9127. }
  9128. cb(Qcur, "Qcur", il);
  9129. cb(Kcur, "Kcur", il);
  9130. cb(Vcur, "Vcur", il);
  9131. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9132. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9133. Qcur = ggml_rope_ext(
  9134. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9135. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9136. );
  9137. cb(Qcur, "Qcur", il);
  9138. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  9139. cb(Qcur, "Qcur", il);
  9140. Kcur = ggml_rope_ext(
  9141. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9142. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9143. );
  9144. cb(Kcur, "Kcur", il);
  9145. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9146. model.layers[il].wo, model.layers[il].bo,
  9147. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9148. }
  9149. if (il == n_layer - 1) {
  9150. // skip computing output for unused tokens
  9151. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  9152. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9153. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  9154. }
  9155. cur = ggml_add(ctx0, cur, residual);
  9156. residual = cur;
  9157. cur = llm_build_norm(ctx0, cur, hparams,
  9158. model.layers[il].ffn_norm, NULL,
  9159. LLM_NORM_RMS, cb, il);
  9160. cb(cur, "ffn_norm", il);
  9161. // FF
  9162. // special-case: the up and gate tensors are merged into a single tensor
  9163. // TOOD: support into llm_build_ffn
  9164. {
  9165. cur = llm_build_ffn(ctx0, lctx, cur,
  9166. model.layers[il].ffn_up, NULL, NULL,
  9167. NULL, NULL, NULL,
  9168. model.layers[il].ffn_down, NULL, NULL,
  9169. NULL,
  9170. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  9171. cb(cur, "ffn_out", il);
  9172. }
  9173. cur = ggml_add(ctx0, residual, cur);
  9174. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9175. cb(cur, "l_out", il);
  9176. // input for next layer
  9177. inpL = cur;
  9178. }
  9179. cur = llm_build_norm(ctx0, inpL, hparams,
  9180. model.output_norm,
  9181. NULL,
  9182. LLM_NORM_RMS, cb, -1);
  9183. cb(cur, "result_norm", -1);
  9184. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9185. cb(cur, "result_output", -1);
  9186. ggml_build_forward_expand(gf, cur);
  9187. return gf;
  9188. }
  9189. struct ggml_cgraph * build_plamo() {
  9190. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  9191. const int64_t n_embd_head = hparams.n_embd_head_v;
  9192. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9193. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9194. struct ggml_tensor * cur;
  9195. struct ggml_tensor * inpL;
  9196. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9197. // inp_pos - contains the positions
  9198. struct ggml_tensor * inp_pos = build_inp_pos();
  9199. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9200. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9201. for (int il = 0; il < n_layer; ++il) {
  9202. // norm
  9203. cur = llm_build_norm(ctx0, inpL, hparams,
  9204. model.layers[il].attn_norm, NULL,
  9205. LLM_NORM_RMS, cb, il);
  9206. cb(cur, "attn_norm", il);
  9207. struct ggml_tensor * attention_norm = cur;
  9208. // self-attention
  9209. {
  9210. // compute Q and K and RoPE them
  9211. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9212. cb(Qcur, "Qcur", il);
  9213. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9214. cb(Kcur, "Kcur", il);
  9215. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9216. cb(Vcur, "Vcur", il);
  9217. Qcur = ggml_rope_ext(
  9218. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  9219. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9220. ext_factor, attn_factor, beta_fast, beta_slow);
  9221. cb(Qcur, "Qcur", il);
  9222. Kcur = ggml_rope_ext(
  9223. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  9224. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9225. ext_factor, attn_factor, beta_fast, beta_slow);
  9226. cb(Kcur, "Kcur", il);
  9227. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9228. model.layers[il].wo, NULL,
  9229. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9230. }
  9231. struct ggml_tensor * sa_out = cur;
  9232. cur = attention_norm;
  9233. if (il == n_layer - 1) {
  9234. // skip computing output for unused tokens
  9235. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9236. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9237. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  9238. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9239. }
  9240. // feed-forward network
  9241. {
  9242. cur = llm_build_ffn(ctx0, lctx, cur,
  9243. model.layers[il].ffn_up, NULL, NULL,
  9244. model.layers[il].ffn_gate, NULL, NULL,
  9245. model.layers[il].ffn_down, NULL, NULL,
  9246. NULL,
  9247. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9248. cb(cur, "ffn_out", il);
  9249. }
  9250. cur = ggml_add(ctx0, cur, sa_out);
  9251. cur = ggml_add(ctx0, cur, inpL);
  9252. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9253. cb(cur, "l_out", il);
  9254. // input for next layer
  9255. inpL = cur;
  9256. }
  9257. cur = inpL;
  9258. cur = llm_build_norm(ctx0, cur, hparams,
  9259. model.output_norm, NULL,
  9260. LLM_NORM_RMS, cb, -1);
  9261. cb(cur, "result_norm", -1);
  9262. // lm_head
  9263. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9264. cb(cur, "result_output", -1);
  9265. ggml_build_forward_expand(gf, cur);
  9266. return gf;
  9267. }
  9268. struct ggml_cgraph * build_gpt2() {
  9269. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9270. const int64_t n_embd_head = hparams.n_embd_head_v;
  9271. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9272. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9273. struct ggml_tensor * cur;
  9274. struct ggml_tensor * pos;
  9275. struct ggml_tensor * inpL;
  9276. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9277. // inp_pos - contains the positions
  9278. struct ggml_tensor * inp_pos = build_inp_pos();
  9279. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9280. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9281. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  9282. cb(pos, "pos_embd", -1);
  9283. inpL = ggml_add(ctx0, inpL, pos);
  9284. cb(inpL, "inpL", -1);
  9285. for (int il = 0; il < n_layer; ++il) {
  9286. cur = llm_build_norm(ctx0, inpL, hparams,
  9287. model.layers[il].attn_norm,
  9288. model.layers[il].attn_norm_b,
  9289. LLM_NORM, cb, il);
  9290. cb(cur, "attn_norm", il);
  9291. // self-attention
  9292. {
  9293. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9294. cb(cur, "wqkv", il);
  9295. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9296. cb(cur, "bqkv", il);
  9297. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9298. 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)));
  9299. 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)));
  9300. cb(Qcur, "Qcur", il);
  9301. cb(Kcur, "Kcur", il);
  9302. cb(Vcur, "Vcur", il);
  9303. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9304. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9305. model.layers[il].wo, model.layers[il].bo,
  9306. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9307. }
  9308. if (il == n_layer - 1) {
  9309. // skip computing output for unused tokens
  9310. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9311. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9312. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9313. }
  9314. // add the input
  9315. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9316. cb(ffn_inp, "ffn_inp", il);
  9317. // FF
  9318. {
  9319. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9320. model.layers[il].ffn_norm,
  9321. model.layers[il].ffn_norm_b,
  9322. LLM_NORM, cb, il);
  9323. cb(cur, "ffn_norm", il);
  9324. cur = llm_build_ffn(ctx0, lctx, cur,
  9325. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9326. NULL, NULL, NULL,
  9327. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9328. NULL,
  9329. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9330. cb(cur, "ffn_out", il);
  9331. }
  9332. cur = ggml_add(ctx0, cur, ffn_inp);
  9333. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9334. cb(cur, "l_out", il);
  9335. // input for next layer
  9336. inpL = cur;
  9337. }
  9338. cur = llm_build_norm(ctx0, inpL, hparams,
  9339. model.output_norm,
  9340. model.output_norm_b,
  9341. LLM_NORM, cb, -1);
  9342. cb(cur, "result_norm", -1);
  9343. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9344. cb(cur, "result_output", -1);
  9345. ggml_build_forward_expand(gf, cur);
  9346. return gf;
  9347. }
  9348. struct ggml_cgraph * build_codeshell() {
  9349. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9350. const int64_t n_embd_head = hparams.n_embd_head_v;
  9351. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9352. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9353. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9354. struct ggml_tensor * cur;
  9355. struct ggml_tensor * inpL;
  9356. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9357. // inp_pos - contains the positions
  9358. struct ggml_tensor * inp_pos = build_inp_pos();
  9359. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9360. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9361. for (int il = 0; il < n_layer; ++il) {
  9362. cur = llm_build_norm(ctx0, inpL, hparams,
  9363. model.layers[il].attn_norm,
  9364. model.layers[il].attn_norm_b,
  9365. LLM_NORM, cb, il);
  9366. cb(cur, "attn_norm", il);
  9367. // self-attention
  9368. {
  9369. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9370. cb(cur, "wqkv", il);
  9371. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9372. cb(cur, "bqkv", il);
  9373. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9374. 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)));
  9375. 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)));
  9376. cb(tmpq, "tmpq", il);
  9377. cb(tmpk, "tmpk", il);
  9378. cb(Vcur, "Vcur", il);
  9379. struct ggml_tensor * Qcur = ggml_rope_ext(
  9380. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9381. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9382. ext_factor, attn_factor, beta_fast, beta_slow
  9383. );
  9384. cb(Qcur, "Qcur", il);
  9385. struct ggml_tensor * Kcur = ggml_rope_ext(
  9386. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9387. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9388. ext_factor, attn_factor, beta_fast, beta_slow
  9389. );
  9390. cb(Kcur, "Kcur", il);
  9391. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9392. model.layers[il].wo, model.layers[il].bo,
  9393. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9394. }
  9395. if (il == n_layer - 1) {
  9396. // skip computing output for unused tokens
  9397. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9398. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9399. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9400. }
  9401. // add the input
  9402. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9403. cb(ffn_inp, "ffn_inp", il);
  9404. // FF
  9405. {
  9406. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9407. model.layers[il].ffn_norm,
  9408. model.layers[il].ffn_norm_b,
  9409. LLM_NORM, cb, il);
  9410. cb(cur, "ffn_norm", il);
  9411. cur = llm_build_ffn(ctx0, lctx, cur,
  9412. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9413. NULL, NULL, NULL,
  9414. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9415. NULL,
  9416. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9417. cb(cur, "ffn_out", il);
  9418. }
  9419. cur = ggml_add(ctx0, cur, ffn_inp);
  9420. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9421. cb(cur, "l_out", il);
  9422. // input for next layer
  9423. inpL = cur;
  9424. }
  9425. cur = llm_build_norm(ctx0, inpL, hparams,
  9426. model.output_norm,
  9427. model.output_norm_b,
  9428. LLM_NORM, cb, -1);
  9429. cb(cur, "result_norm", -1);
  9430. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9431. cb(cur, "result_output", -1);
  9432. ggml_build_forward_expand(gf, cur);
  9433. return gf;
  9434. }
  9435. struct ggml_cgraph * build_orion() {
  9436. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9437. const int64_t n_embd_head = hparams.n_embd_head_v;
  9438. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9439. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9440. struct ggml_tensor * cur;
  9441. struct ggml_tensor * inpL;
  9442. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9443. // inp_pos - contains the positions
  9444. struct ggml_tensor * inp_pos = build_inp_pos();
  9445. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9446. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9447. for (int il = 0; il < n_layer; ++il) {
  9448. struct ggml_tensor * inpSA = inpL;
  9449. // norm
  9450. cur = llm_build_norm(ctx0, inpL, hparams,
  9451. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9452. LLM_NORM, cb, il);
  9453. cb(cur, "attn_norm", il);
  9454. // self-attention
  9455. {
  9456. // compute Q and K and RoPE them
  9457. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9458. cb(Qcur, "Qcur", il);
  9459. // if (model.layers[il].bq) {
  9460. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9461. // cb(Qcur, "Qcur", il);
  9462. // }
  9463. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9464. cb(Kcur, "Kcur", il);
  9465. // if (model.layers[il].bk) {
  9466. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9467. // cb(Kcur, "Kcur", il);
  9468. // }
  9469. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9470. cb(Vcur, "Vcur", il);
  9471. // if (model.layers[il].bv) {
  9472. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9473. // cb(Vcur, "Vcur", il);
  9474. // }
  9475. Qcur = ggml_rope_ext(
  9476. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9477. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9478. ext_factor, attn_factor, beta_fast, beta_slow
  9479. );
  9480. cb(Qcur, "Qcur", il);
  9481. Kcur = ggml_rope_ext(
  9482. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9483. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9484. ext_factor, attn_factor, beta_fast, beta_slow
  9485. );
  9486. cb(Kcur, "Kcur", il);
  9487. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9488. model.layers[il].wo, NULL,
  9489. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9490. }
  9491. if (il == n_layer - 1) {
  9492. // skip computing output for unused tokens
  9493. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9494. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9495. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9496. }
  9497. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9498. cb(ffn_inp, "ffn_inp", il);
  9499. // feed-forward network
  9500. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9501. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9502. LLM_NORM, cb, il);
  9503. cb(cur, "ffn_norm", il);
  9504. cur = llm_build_ffn(ctx0, lctx, cur,
  9505. model.layers[il].ffn_up, NULL, NULL,
  9506. model.layers[il].ffn_gate, NULL, NULL,
  9507. model.layers[il].ffn_down, NULL, NULL,
  9508. NULL,
  9509. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9510. cb(cur, "ffn_out", il);
  9511. cur = ggml_add(ctx0, cur, ffn_inp);
  9512. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9513. cb(cur, "l_out", il);
  9514. // input for next layer
  9515. inpL = cur;
  9516. }
  9517. cur = inpL;
  9518. cur = llm_build_norm(ctx0, cur, hparams,
  9519. model.output_norm, model.output_norm_b,
  9520. LLM_NORM, cb, -1);
  9521. cb(cur, "result_norm", -1);
  9522. // lm_head
  9523. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9524. cb(cur, "result_output", -1);
  9525. ggml_build_forward_expand(gf, cur);
  9526. return gf;
  9527. }
  9528. struct ggml_cgraph * build_internlm2() {
  9529. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9530. const int64_t n_embd_head = hparams.n_embd_head_v;
  9531. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9532. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9533. struct ggml_tensor * cur;
  9534. struct ggml_tensor * inpL;
  9535. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9536. // inp_pos - contains the positions
  9537. struct ggml_tensor * inp_pos = build_inp_pos();
  9538. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9539. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9540. for (int il = 0; il < n_layer; ++il) {
  9541. struct ggml_tensor * inpSA = inpL;
  9542. // norm
  9543. cur = llm_build_norm(ctx0, inpL, hparams,
  9544. model.layers[il].attn_norm, NULL,
  9545. LLM_NORM_RMS, cb, il);
  9546. cb(cur, "attn_norm", il);
  9547. // self-attention
  9548. {
  9549. // compute Q and K and RoPE them
  9550. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9551. cb(Qcur, "Qcur", il);
  9552. if (model.layers[il].bq) {
  9553. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9554. cb(Qcur, "Qcur", il);
  9555. }
  9556. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9557. cb(Kcur, "Kcur", il);
  9558. if (model.layers[il].bk) {
  9559. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9560. cb(Kcur, "Kcur", il);
  9561. }
  9562. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9563. cb(Vcur, "Vcur", il);
  9564. if (model.layers[il].bv) {
  9565. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9566. cb(Vcur, "Vcur", il);
  9567. }
  9568. Qcur = ggml_rope_ext(
  9569. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9570. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9571. ext_factor, attn_factor, beta_fast, beta_slow
  9572. );
  9573. cb(Qcur, "Qcur", il);
  9574. Kcur = ggml_rope_ext(
  9575. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9576. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9577. ext_factor, attn_factor, beta_fast, beta_slow
  9578. );
  9579. cb(Kcur, "Kcur", il);
  9580. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9581. model.layers[il].wo, model.layers[il].bo,
  9582. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9583. }
  9584. if (il == n_layer - 1) {
  9585. // skip computing output for unused tokens
  9586. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9587. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9588. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9589. }
  9590. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9591. cb(ffn_inp, "ffn_inp", il);
  9592. // feed-forward network
  9593. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9594. model.layers[il].ffn_norm, NULL,
  9595. LLM_NORM_RMS, cb, il);
  9596. cb(cur, "ffn_norm", il);
  9597. cur = llm_build_ffn(ctx0, lctx, cur,
  9598. model.layers[il].ffn_up, NULL, NULL,
  9599. model.layers[il].ffn_gate, NULL, NULL,
  9600. model.layers[il].ffn_down, NULL, NULL,
  9601. NULL,
  9602. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9603. cb(cur, "ffn_out", il);
  9604. cur = ggml_add(ctx0, cur, ffn_inp);
  9605. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9606. cb(cur, "l_out", il);
  9607. // input for next layer
  9608. inpL = cur;
  9609. }
  9610. cur = inpL;
  9611. cur = llm_build_norm(ctx0, cur, hparams,
  9612. model.output_norm, NULL,
  9613. LLM_NORM_RMS, cb, -1);
  9614. cb(cur, "result_norm", -1);
  9615. // lm_head
  9616. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9617. cb(cur, "result_output", -1);
  9618. ggml_build_forward_expand(gf, cur);
  9619. return gf;
  9620. }
  9621. // ref: https://arxiv.org/abs/2203.03466
  9622. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  9623. // based on the original build_llama() function
  9624. struct ggml_cgraph * build_minicpm() {
  9625. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9626. const int64_t n_embd_head = hparams.n_embd_head_v;
  9627. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9628. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9629. const int64_t n_embd = hparams.n_embd;
  9630. //TODO: if the model varies, these parameters need to be read from the model
  9631. const int64_t n_embd_base = 256;
  9632. const float scale_embd = 12.0f;
  9633. const float scale_depth = 1.4f;
  9634. struct ggml_tensor * cur;
  9635. struct ggml_tensor * inpL;
  9636. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9637. // scale the input embeddings
  9638. inpL = ggml_scale(ctx0, inpL, scale_embd);
  9639. cb(inpL, "inp_scaled", -1);
  9640. // inp_pos - contains the positions
  9641. struct ggml_tensor * inp_pos = build_inp_pos();
  9642. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9643. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9644. for (int il = 0; il < n_layer; ++il) {
  9645. struct ggml_tensor * inpSA = inpL;
  9646. // norm
  9647. cur = llm_build_norm(ctx0, inpL, hparams,
  9648. model.layers[il].attn_norm, NULL,
  9649. LLM_NORM_RMS, cb, il);
  9650. cb(cur, "attn_norm", il);
  9651. // self-attention
  9652. {
  9653. // compute Q and K and RoPE them
  9654. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9655. cb(Qcur, "Qcur", il);
  9656. if (model.layers[il].bq) {
  9657. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9658. cb(Qcur, "Qcur", il);
  9659. }
  9660. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9661. cb(Kcur, "Kcur", il);
  9662. if (model.layers[il].bk) {
  9663. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9664. cb(Kcur, "Kcur", il);
  9665. }
  9666. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9667. cb(Vcur, "Vcur", il);
  9668. if (model.layers[il].bv) {
  9669. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9670. cb(Vcur, "Vcur", il);
  9671. }
  9672. Qcur = ggml_rope_ext(
  9673. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9674. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9675. ext_factor, attn_factor, beta_fast, beta_slow
  9676. );
  9677. cb(Qcur, "Qcur", il);
  9678. Kcur = ggml_rope_ext(
  9679. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9680. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9681. ext_factor, attn_factor, beta_fast, beta_slow
  9682. );
  9683. cb(Kcur, "Kcur", il);
  9684. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9685. model.layers[il].wo, model.layers[il].bo,
  9686. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9687. }
  9688. if (il == n_layer - 1) {
  9689. // skip computing output for unused tokens
  9690. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9691. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9692. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9693. }
  9694. // scale_res - scale the hidden states for residual connection
  9695. const float scale_res = scale_depth/sqrtf(float(n_layer));
  9696. cur = ggml_scale(ctx0, cur, scale_res);
  9697. cb(cur, "hidden_scaled", -1);
  9698. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9699. cb(ffn_inp, "ffn_inp", il);
  9700. // feed-forward network
  9701. {
  9702. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9703. model.layers[il].ffn_norm, NULL,
  9704. LLM_NORM_RMS, cb, il);
  9705. cb(cur, "ffn_norm", il);
  9706. cur = llm_build_ffn(ctx0, lctx, cur,
  9707. model.layers[il].ffn_up, NULL, NULL,
  9708. model.layers[il].ffn_gate, NULL, NULL,
  9709. model.layers[il].ffn_down, NULL, NULL,
  9710. NULL,
  9711. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9712. cb(cur, "ffn_out", il);
  9713. }
  9714. // scale the hidden states for residual connection
  9715. cur = ggml_scale(ctx0, cur, scale_res);
  9716. cb(cur, "hidden_scaled_ffn", -1);
  9717. cur = ggml_add(ctx0, cur, ffn_inp);
  9718. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9719. cb(cur, "l_out", il);
  9720. // input for next layer
  9721. inpL = cur;
  9722. }
  9723. cur = inpL;
  9724. cur = llm_build_norm(ctx0, cur, hparams,
  9725. model.output_norm, NULL,
  9726. LLM_NORM_RMS, cb, -1);
  9727. cb(cur, "result_norm", -1);
  9728. // lm_head scaling
  9729. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  9730. cur = ggml_scale(ctx0, cur, scale_lmhead);
  9731. cb(cur, "lmhead_scaling", -1);
  9732. // lm_head
  9733. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9734. cb(cur, "result_output", -1);
  9735. ggml_build_forward_expand(gf, cur);
  9736. return gf;
  9737. }
  9738. struct ggml_cgraph * build_gemma() {
  9739. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9740. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9741. struct ggml_tensor * cur;
  9742. struct ggml_tensor * inpL;
  9743. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9744. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9745. cb(inpL, "inp_scaled", -1);
  9746. // inp_pos - contains the positions
  9747. struct ggml_tensor * inp_pos = build_inp_pos();
  9748. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9749. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9750. for (int il = 0; il < n_layer; ++il) {
  9751. // norm
  9752. cur = llm_build_norm(ctx0, inpL, hparams,
  9753. model.layers[il].attn_norm, NULL,
  9754. LLM_NORM_RMS, cb, il);
  9755. cb(cur, "attn_norm", il);
  9756. // self-attention
  9757. {
  9758. // compute Q and K and RoPE them
  9759. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9760. cb(Qcur, "Qcur", il);
  9761. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9762. cb(Kcur, "Kcur", il);
  9763. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9764. cb(Vcur, "Vcur", il);
  9765. Qcur = ggml_rope_ext(
  9766. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9767. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9768. ext_factor, attn_factor, beta_fast, beta_slow);
  9769. cb(Qcur, "Qcur", il);
  9770. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  9771. cb(Qcur, "Qcur_scaled", il);
  9772. Kcur = ggml_rope_ext(
  9773. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9774. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9775. ext_factor, attn_factor, beta_fast, beta_slow);
  9776. cb(Kcur, "Kcur", il);
  9777. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9778. model.layers[il].wo, NULL,
  9779. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9780. }
  9781. if (il == n_layer - 1) {
  9782. // skip computing output for unused tokens
  9783. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9784. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9785. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9786. }
  9787. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9788. cb(sa_out, "sa_out", il);
  9789. cur = llm_build_norm(ctx0, sa_out, hparams,
  9790. model.layers[il].ffn_norm, NULL,
  9791. LLM_NORM_RMS, cb, il);
  9792. cb(cur, "ffn_norm", il);
  9793. // feed-forward network
  9794. {
  9795. cur = llm_build_ffn(ctx0, lctx, cur,
  9796. model.layers[il].ffn_up, NULL, NULL,
  9797. model.layers[il].ffn_gate, NULL, NULL,
  9798. model.layers[il].ffn_down, NULL, NULL,
  9799. NULL,
  9800. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9801. cb(cur, "ffn_out", il);
  9802. }
  9803. cur = ggml_add(ctx0, cur, sa_out);
  9804. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9805. cb(cur, "l_out", il);
  9806. // input for next layer
  9807. inpL = cur;
  9808. }
  9809. cur = inpL;
  9810. cur = llm_build_norm(ctx0, cur, hparams,
  9811. model.output_norm, NULL,
  9812. LLM_NORM_RMS, cb, -1);
  9813. cb(cur, "result_norm", -1);
  9814. // lm_head
  9815. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9816. cb(cur, "result_output", -1);
  9817. ggml_build_forward_expand(gf, cur);
  9818. return gf;
  9819. }
  9820. struct ggml_cgraph * build_gemma2() {
  9821. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9822. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9823. struct ggml_tensor * cur;
  9824. struct ggml_tensor * inpL;
  9825. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9826. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9827. cb(inpL, "inp_scaled", -1);
  9828. // inp_pos - contains the positions
  9829. struct ggml_tensor * inp_pos = build_inp_pos();
  9830. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9831. // gemma 2 requires different mask for layers using sliding window (SWA)
  9832. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  9833. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  9834. for (int il = 0; il < n_layer; ++il) {
  9835. // (il % 2) layers use SWA
  9836. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  9837. // norm
  9838. cur = llm_build_norm(ctx0, inpL, hparams,
  9839. model.layers[il].attn_norm, NULL,
  9840. LLM_NORM_RMS, cb, il);
  9841. cb(cur, "attn_norm", il);
  9842. // self-attention
  9843. {
  9844. // compute Q and K and RoPE them
  9845. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9846. cb(Qcur, "Qcur", il);
  9847. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9848. cb(Kcur, "Kcur", il);
  9849. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9850. cb(Vcur, "Vcur", il);
  9851. Qcur = ggml_rope_ext(
  9852. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9853. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9854. ext_factor, attn_factor, beta_fast, beta_slow);
  9855. cb(Qcur, "Qcur", il);
  9856. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  9857. switch (model.type) {
  9858. case e_model::MODEL_2B:
  9859. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  9860. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  9861. default: GGML_ABORT("fatal error");
  9862. };
  9863. cb(Qcur, "Qcur_scaled", il);
  9864. Kcur = ggml_rope_ext(
  9865. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9866. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9867. ext_factor, attn_factor, beta_fast, beta_slow);
  9868. cb(Kcur, "Kcur", il);
  9869. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9870. model.layers[il].wo, NULL,
  9871. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9872. }
  9873. cur = llm_build_norm(ctx0, cur, hparams,
  9874. model.layers[il].attn_post_norm, NULL,
  9875. LLM_NORM_RMS, cb, il);
  9876. cb(cur, "attn_post_norm", il);
  9877. if (il == n_layer - 1) {
  9878. // skip computing output for unused tokens
  9879. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9880. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9881. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9882. }
  9883. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9884. cb(sa_out, "sa_out", il);
  9885. cur = llm_build_norm(ctx0, sa_out, hparams,
  9886. model.layers[il].ffn_norm, NULL,
  9887. LLM_NORM_RMS, cb, il);
  9888. cb(cur, "ffn_norm", il);
  9889. // feed-forward network
  9890. {
  9891. cur = llm_build_ffn(ctx0, lctx, cur,
  9892. model.layers[il].ffn_up, NULL, NULL,
  9893. model.layers[il].ffn_gate, NULL, NULL,
  9894. model.layers[il].ffn_down, NULL, NULL,
  9895. NULL,
  9896. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9897. cb(cur, "ffn_out", il);
  9898. }
  9899. cur = llm_build_norm(ctx0, cur, hparams,
  9900. model.layers[il].ffn_post_norm, NULL,
  9901. LLM_NORM_RMS, cb, -1);
  9902. cb(cur, "ffn_post_norm", -1);
  9903. cur = ggml_add(ctx0, cur, sa_out);
  9904. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9905. cb(cur, "l_out", il);
  9906. // input for next layer
  9907. inpL = cur;
  9908. }
  9909. cur = inpL;
  9910. cur = llm_build_norm(ctx0, cur, hparams,
  9911. model.output_norm, NULL,
  9912. LLM_NORM_RMS, cb, -1);
  9913. cb(cur, "result_norm", -1);
  9914. // lm_head
  9915. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9916. // final logit soft-capping
  9917. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  9918. cur = ggml_tanh(ctx0, cur);
  9919. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  9920. cb(cur, "result_output", -1);
  9921. ggml_build_forward_expand(gf, cur);
  9922. return gf;
  9923. }
  9924. struct ggml_cgraph * build_starcoder2() {
  9925. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9926. const int64_t n_embd_head = hparams.n_embd_head_v;
  9927. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9928. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9929. struct ggml_tensor * cur;
  9930. struct ggml_tensor * inpL;
  9931. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9932. // inp_pos - contains the positions
  9933. struct ggml_tensor * inp_pos = build_inp_pos();
  9934. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9935. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9936. for (int il = 0; il < n_layer; ++il) {
  9937. struct ggml_tensor * inpSA = inpL;
  9938. // norm
  9939. cur = llm_build_norm(ctx0, inpL, hparams,
  9940. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9941. LLM_NORM, cb, il);
  9942. cb(cur, "attn_norm", il);
  9943. // self-attention
  9944. {
  9945. // compute Q and K and RoPE them
  9946. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9947. cb(Qcur, "Qcur", il);
  9948. if (model.layers[il].bq) {
  9949. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9950. cb(Qcur, "Qcur", il);
  9951. }
  9952. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9953. cb(Kcur, "Kcur", il);
  9954. if (model.layers[il].bk) {
  9955. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9956. cb(Kcur, "Kcur", il);
  9957. }
  9958. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9959. cb(Vcur, "Vcur", il);
  9960. if (model.layers[il].bv) {
  9961. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9962. cb(Vcur, "Vcur", il);
  9963. }
  9964. Qcur = ggml_rope_ext(
  9965. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9966. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9967. ext_factor, attn_factor, beta_fast, beta_slow
  9968. );
  9969. cb(Qcur, "Qcur", il);
  9970. Kcur = ggml_rope_ext(
  9971. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9972. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9973. ext_factor, attn_factor, beta_fast, beta_slow
  9974. );
  9975. cb(Kcur, "Kcur", il);
  9976. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9977. model.layers[il].wo, model.layers[il].bo,
  9978. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9979. }
  9980. if (il == n_layer - 1) {
  9981. // skip computing output for unused tokens
  9982. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9983. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9984. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9985. }
  9986. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9987. cb(ffn_inp, "ffn_inp", il);
  9988. // feed-forward network
  9989. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9990. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9991. LLM_NORM, cb, il);
  9992. cb(cur, "ffn_norm", il);
  9993. cur = llm_build_ffn(ctx0, lctx, cur,
  9994. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9995. NULL, NULL, NULL,
  9996. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9997. NULL,
  9998. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9999. cb(cur, "ffn_out", il);
  10000. cur = ggml_add(ctx0, cur, ffn_inp);
  10001. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10002. cb(cur, "l_out", il);
  10003. // input for next layer
  10004. inpL = cur;
  10005. }
  10006. cur = inpL;
  10007. cur = llm_build_norm(ctx0, cur, hparams,
  10008. model.output_norm, model.output_norm_b,
  10009. LLM_NORM, cb, -1);
  10010. cb(cur, "result_norm", -1);
  10011. // lm_head
  10012. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10013. cb(cur, "result_output", -1);
  10014. ggml_build_forward_expand(gf, cur);
  10015. return gf;
  10016. }
  10017. struct ggml_cgraph * build_mamba() {
  10018. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10019. const int64_t d_model = n_embd;
  10020. const int64_t d_conv = hparams.ssm_d_conv;
  10021. const int64_t d_inner = hparams.ssm_d_inner;
  10022. GGML_ASSERT(2 * d_model == d_inner);
  10023. const int64_t d_state = hparams.ssm_d_state;
  10024. const int64_t dt_rank = hparams.ssm_dt_rank;
  10025. struct ggml_tensor * cur;
  10026. struct ggml_tensor * inpL;
  10027. // {n_embd, n_tokens}
  10028. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10029. struct ggml_tensor * state_mask = build_inp_s_mask();
  10030. struct ggml_tensor * state_seq = build_inp_s_seq();
  10031. for (int il = 0; il < n_layer; ++il) {
  10032. // (ab)using the KV cache to store the states
  10033. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  10034. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  10035. // clear states of sequences which are starting at the beginning of this batch
  10036. {
  10037. conv_states = ggml_mul(ctx0,
  10038. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  10039. state_mask);
  10040. ssm_states = ggml_mul(ctx0,
  10041. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  10042. state_mask);
  10043. }
  10044. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  10045. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  10046. // norm
  10047. cur = llm_build_norm(ctx0, inpL, hparams,
  10048. model.layers[il].attn_norm, NULL,
  10049. LLM_NORM_RMS, cb, il);
  10050. cb(cur, "attn_norm", il);
  10051. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  10052. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_in, cur);
  10053. // split the above in two
  10054. // => {d_inner, n_tokens}
  10055. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  10056. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  10057. // conv
  10058. {
  10059. // Custom operator which is needed only to ease simultaneous sequence processing.
  10060. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  10061. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  10062. // then element-wise multiply that with the conv1d weigth,
  10063. // then sum the elements of each row,
  10064. // (the last two steps are a dot product over rows (also doable with mul_mat))
  10065. // then permute away the ne[0] dimension,
  10066. // and then you're left with the resulting x tensor.
  10067. // The new conv_states is the last (d_conv - 1) columns
  10068. // of the last 3rd dimensional "layer" of the self-overlapping view.
  10069. // For simultaneous sequences, it's more complicated.
  10070. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  10071. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  10072. ggml_build_forward_expand(gf,
  10073. ggml_cpy(ctx0,
  10074. 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)),
  10075. 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))));
  10076. // extract x from x_conv
  10077. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  10078. // bias
  10079. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  10080. x = ggml_silu(ctx0, x);
  10081. }
  10082. // ssm
  10083. {
  10084. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  10085. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_x, x);
  10086. // split
  10087. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  10088. 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);
  10089. 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));
  10090. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  10091. dt = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_dt, dt);
  10092. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  10093. // Custom operator to optimize the parallel associative scan
  10094. // as described in the Annex D of the Mamba paper.
  10095. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  10096. // because only a single tensor can be returned.
  10097. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  10098. // store last states (the second part of y_ssm_states)
  10099. ggml_build_forward_expand(gf,
  10100. ggml_cpy(ctx0,
  10101. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  10102. 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))));
  10103. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  10104. if (il == n_layer - 1) {
  10105. // skip computing output for unused tokens
  10106. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10107. x = ggml_get_rows(ctx0, x, inp_out_ids);
  10108. y = ggml_get_rows(ctx0, y, inp_out_ids);
  10109. z = ggml_get_rows(ctx0, z, inp_out_ids);
  10110. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10111. }
  10112. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  10113. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  10114. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  10115. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  10116. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_out, y);
  10117. }
  10118. // residual
  10119. cur = ggml_add(ctx0, cur, inpL);
  10120. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10121. cb(cur, "l_out", il);
  10122. // input for next layer
  10123. inpL = cur;
  10124. }
  10125. // final rmsnorm
  10126. cur = llm_build_norm(ctx0, inpL, hparams,
  10127. model.output_norm, NULL,
  10128. LLM_NORM_RMS, cb, -1);
  10129. cb(cur, "result_norm", -1);
  10130. // lm_head
  10131. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10132. cb(cur, "result_output", -1);
  10133. ggml_build_forward_expand(gf, cur);
  10134. return gf;
  10135. }
  10136. struct ggml_cgraph * build_command_r() {
  10137. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10138. const int64_t n_embd_head = hparams.n_embd_head_v;
  10139. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10140. const float f_logit_scale = hparams.f_logit_scale;
  10141. struct ggml_tensor * cur;
  10142. struct ggml_tensor * inpL;
  10143. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10144. // inp_pos - contains the positions
  10145. struct ggml_tensor * inp_pos = build_inp_pos();
  10146. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10147. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10148. for (int il = 0; il < n_layer; ++il) {
  10149. // norm
  10150. cur = llm_build_norm(ctx0, inpL, hparams,
  10151. model.layers[il].attn_norm, NULL,
  10152. LLM_NORM, cb, il);
  10153. cb(cur, "attn_norm", il);
  10154. struct ggml_tensor * ffn_inp = cur;
  10155. // self-attention
  10156. {
  10157. // compute Q and K and RoPE them
  10158. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10159. cb(Qcur, "Qcur", il);
  10160. if (model.layers[il].bq) {
  10161. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10162. cb(Qcur, "Qcur", il);
  10163. }
  10164. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10165. cb(Kcur, "Kcur", il);
  10166. if (model.layers[il].bk) {
  10167. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10168. cb(Kcur, "Kcur", il);
  10169. }
  10170. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10171. cb(Vcur, "Vcur", il);
  10172. if (model.layers[il].bv) {
  10173. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10174. cb(Vcur, "Vcur", il);
  10175. }
  10176. if (model.layers[il].attn_q_norm) {
  10177. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  10178. ggml_element_size(Qcur) * n_embd_head,
  10179. ggml_element_size(Qcur) * n_embd_head * n_head,
  10180. 0);
  10181. cb(Qcur, "Qcur", il);
  10182. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  10183. ggml_element_size(Kcur) * n_embd_head,
  10184. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  10185. 0);
  10186. cb(Kcur, "Kcur", il);
  10187. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10188. model.layers[il].attn_q_norm,
  10189. NULL,
  10190. LLM_NORM, cb, il);
  10191. cb(Qcur, "Qcur", il);
  10192. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10193. model.layers[il].attn_k_norm,
  10194. NULL,
  10195. LLM_NORM, cb, il);
  10196. cb(Kcur, "Kcur", il);
  10197. }
  10198. Qcur = ggml_rope_ext(
  10199. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10200. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10201. ext_factor, attn_factor, beta_fast, beta_slow
  10202. );
  10203. cb(Qcur, "Qcur", il);
  10204. Kcur = ggml_rope_ext(
  10205. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10206. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10207. ext_factor, attn_factor, beta_fast, beta_slow
  10208. );
  10209. cb(Kcur, "Kcur", il);
  10210. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10211. model.layers[il].wo, model.layers[il].bo,
  10212. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10213. }
  10214. if (il == n_layer - 1) {
  10215. // skip computing output for unused tokens
  10216. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10217. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10218. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10219. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  10220. }
  10221. struct ggml_tensor * attn_out = cur;
  10222. // feed-forward network
  10223. {
  10224. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  10225. model.layers[il].ffn_up, NULL, NULL,
  10226. model.layers[il].ffn_gate, NULL, NULL,
  10227. model.layers[il].ffn_down, NULL, NULL,
  10228. NULL,
  10229. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10230. cb(cur, "ffn_out", il);
  10231. }
  10232. // add together residual + FFN + self-attention
  10233. cur = ggml_add(ctx0, cur, inpL);
  10234. cur = ggml_add(ctx0, cur, attn_out);
  10235. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10236. cb(cur, "l_out", il);
  10237. // input for next layer
  10238. inpL = cur;
  10239. }
  10240. cur = inpL;
  10241. cur = llm_build_norm(ctx0, cur, hparams,
  10242. model.output_norm, NULL,
  10243. LLM_NORM, cb, -1);
  10244. cb(cur, "result_norm", -1);
  10245. // lm_head
  10246. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10247. if (f_logit_scale) {
  10248. cur = ggml_scale(ctx0, cur, f_logit_scale);
  10249. }
  10250. cb(cur, "result_output", -1);
  10251. ggml_build_forward_expand(gf, cur);
  10252. return gf;
  10253. }
  10254. // ref: https://allenai.org/olmo
  10255. // based on the original build_llama() function, changes:
  10256. // * non-parametric layer norm
  10257. // * clamp qkv
  10258. // * removed bias
  10259. // * removed MoE
  10260. struct ggml_cgraph * build_olmo() {
  10261. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10262. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10263. int32_t n_tokens = this->n_tokens;
  10264. const int64_t n_embd_head = hparams.n_embd_head_v;
  10265. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10266. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10267. struct ggml_tensor * cur;
  10268. struct ggml_tensor * inpL;
  10269. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10270. // inp_pos - contains the positions
  10271. struct ggml_tensor * inp_pos = build_inp_pos();
  10272. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10273. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10274. for (int il = 0; il < n_layer; ++il) {
  10275. struct ggml_tensor * inpSA = inpL;
  10276. // norm
  10277. cur = llm_build_norm(ctx0, inpL, hparams,
  10278. NULL, NULL,
  10279. LLM_NORM, cb, il);
  10280. cb(cur, "attn_norm", il);
  10281. // self-attention
  10282. {
  10283. // compute Q and K and RoPE them
  10284. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10285. cb(Qcur, "Qcur", il);
  10286. if (hparams.f_clamp_kqv > 0.0f) {
  10287. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10288. cb(Qcur, "Qcur", il);
  10289. }
  10290. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10291. cb(Kcur, "Kcur", il);
  10292. if (hparams.f_clamp_kqv > 0.0f) {
  10293. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10294. cb(Kcur, "Kcur", il);
  10295. }
  10296. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10297. cb(Vcur, "Vcur", il);
  10298. if (hparams.f_clamp_kqv > 0.0f) {
  10299. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10300. cb(Vcur, "Vcur", il);
  10301. }
  10302. Qcur = ggml_rope_ext(
  10303. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10304. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10305. ext_factor, attn_factor, beta_fast, beta_slow
  10306. );
  10307. cb(Qcur, "Qcur", il);
  10308. Kcur = ggml_rope_ext(
  10309. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10310. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10311. ext_factor, attn_factor, beta_fast, beta_slow
  10312. );
  10313. cb(Kcur, "Kcur", il);
  10314. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10315. model.layers[il].wo, nullptr,
  10316. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10317. }
  10318. if (il == n_layer - 1) {
  10319. // skip computing output for unused tokens
  10320. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10321. n_tokens = n_outputs;
  10322. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10323. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10324. }
  10325. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10326. cb(ffn_inp, "ffn_inp", il);
  10327. // feed-forward network
  10328. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10329. NULL, NULL,
  10330. LLM_NORM, cb, il);
  10331. cb(cur, "ffn_norm", il);
  10332. cur = llm_build_ffn(ctx0, lctx, cur,
  10333. model.layers[il].ffn_up, NULL, NULL,
  10334. model.layers[il].ffn_gate, NULL, NULL,
  10335. model.layers[il].ffn_down, NULL, NULL,
  10336. NULL,
  10337. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10338. cb(cur, "ffn_out", il);
  10339. cur = ggml_add(ctx0, cur, ffn_inp);
  10340. cb(cur, "ffn_out", il);
  10341. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10342. cb(cur, "l_out", il);
  10343. // input for next layer
  10344. inpL = cur;
  10345. }
  10346. cur = inpL;
  10347. cur = llm_build_norm(ctx0, cur, hparams,
  10348. NULL, NULL,
  10349. LLM_NORM, cb, -1);
  10350. cb(cur, "result_norm", -1);
  10351. // lm_head
  10352. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10353. cb(cur, "result_output", -1);
  10354. ggml_build_forward_expand(gf, cur);
  10355. return gf;
  10356. }
  10357. struct ggml_cgraph * build_openelm() {
  10358. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10359. const int64_t n_embd_head = hparams.n_embd_head_v;
  10360. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10361. struct ggml_tensor * cur;
  10362. struct ggml_tensor * inpL;
  10363. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10364. // inp_pos - contains the positions
  10365. struct ggml_tensor * inp_pos = build_inp_pos();
  10366. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10367. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10368. for (int il = 0; il < n_layer; ++il) {
  10369. const int64_t n_head = hparams.n_head(il);
  10370. const int64_t n_head_kv = hparams.n_head_kv(il);
  10371. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  10372. cur = inpL;
  10373. struct ggml_tensor * residual = cur;
  10374. // norm
  10375. cur = llm_build_norm(ctx0, inpL, hparams,
  10376. model.layers[il].attn_norm, NULL,
  10377. LLM_NORM_RMS, cb, il);
  10378. cb(cur, "attn_norm", il);
  10379. // self-attention
  10380. {
  10381. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10382. cb(cur, "wqkv", il);
  10383. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  10384. 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));
  10385. cb(Qcur, "Qcur", il);
  10386. 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));
  10387. cb(Kcur, "Kcur", il);
  10388. 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)));
  10389. cb(Vcur, "Vcur", il);
  10390. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10391. model.layers[il].attn_q_norm, NULL,
  10392. LLM_NORM_RMS, cb, il);
  10393. cb(Qcur, "Qcur", il);
  10394. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10395. model.layers[il].attn_k_norm, NULL,
  10396. LLM_NORM_RMS, cb, il);
  10397. cb(Kcur, "Kcur", il);
  10398. Qcur = ggml_rope_ext(
  10399. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10400. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10401. );
  10402. cb(Qcur, "Qcur", il);
  10403. Kcur = ggml_rope_ext(
  10404. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10405. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10406. );
  10407. cb(Kcur, "Kcur", il);
  10408. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  10409. cb(Qcur, "Vcur", il);
  10410. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10411. model.layers[il].wo, NULL,
  10412. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10413. }
  10414. if (il == n_layer - 1) {
  10415. // skip computing output for unused tokens
  10416. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10417. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  10418. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10419. }
  10420. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  10421. cb(ffn_inp, "ffn_inp", il);
  10422. // feed-forward network
  10423. {
  10424. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10425. model.layers[il].ffn_norm, NULL,
  10426. LLM_NORM_RMS, cb, il);
  10427. cb(cur, "ffn_norm", il);
  10428. cur = llm_build_ffn(ctx0, lctx, cur,
  10429. model.layers[il].ffn_up, NULL, NULL,
  10430. model.layers[il].ffn_gate, NULL, NULL,
  10431. model.layers[il].ffn_down, NULL, NULL,
  10432. NULL,
  10433. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10434. cb(cur, "ffn_out", il);
  10435. }
  10436. cur = ggml_add(ctx0, cur, ffn_inp);
  10437. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10438. cb(cur, "l_out", il);
  10439. inpL = cur;
  10440. }
  10441. cur = inpL;
  10442. // norm
  10443. cur = llm_build_norm(ctx0, cur, hparams,
  10444. model.output_norm, NULL,
  10445. LLM_NORM_RMS, cb, -1);
  10446. cb(cur, "result_norm", -1);
  10447. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10448. cb(cur, "result_output", -1);
  10449. ggml_build_forward_expand(gf, cur);
  10450. return gf;
  10451. }
  10452. struct ggml_cgraph * build_gptneox() {
  10453. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10454. const int64_t n_embd_head = hparams.n_embd_head_v;
  10455. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10456. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10457. struct ggml_tensor * cur;
  10458. struct ggml_tensor * inpL;
  10459. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10460. // inp_pos - contains the positions
  10461. struct ggml_tensor * inp_pos = build_inp_pos();
  10462. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10463. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10464. for (int il = 0; il < n_layer; ++il) {
  10465. cur = llm_build_norm(ctx0, inpL, hparams,
  10466. model.layers[il].attn_norm,
  10467. model.layers[il].attn_norm_b,
  10468. LLM_NORM, cb, il);
  10469. cb(cur, "attn_norm", il);
  10470. // self-attention
  10471. {
  10472. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10473. cb(cur, "wqkv", il);
  10474. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10475. cb(cur, "bqkv", il);
  10476. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10477. 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)));
  10478. 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)));
  10479. cb(Qcur, "Qcur", il);
  10480. cb(Kcur, "Kcur", il);
  10481. cb(Vcur, "Vcur", il);
  10482. Qcur = ggml_rope_ext(
  10483. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10484. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10485. ext_factor, attn_factor, beta_fast, beta_slow
  10486. );
  10487. cb(Qcur, "Qcur", il);
  10488. Kcur = ggml_rope_ext(
  10489. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10490. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10491. ext_factor, attn_factor, beta_fast, beta_slow
  10492. );
  10493. cb(Kcur, "Kcur", il);
  10494. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10495. model.layers[il].wo, model.layers[il].bo,
  10496. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10497. }
  10498. if (il == n_layer - 1) {
  10499. // skip computing output for unused tokens
  10500. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10501. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10502. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10503. }
  10504. // ffn
  10505. if (hparams.use_par_res) {
  10506. // attention and ffn are computed in parallel
  10507. // x = x + attn(ln1(x)) + ffn(ln2(x))
  10508. struct ggml_tensor * attn_out = cur;
  10509. cur = llm_build_norm(ctx0, inpL, hparams,
  10510. model.layers[il].ffn_norm,
  10511. model.layers[il].ffn_norm_b,
  10512. LLM_NORM, cb, il);
  10513. cb(cur, "ffn_norm", il);
  10514. cur = llm_build_ffn(ctx0, lctx, cur,
  10515. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10516. NULL, NULL, NULL,
  10517. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10518. NULL,
  10519. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10520. cb(cur, "ffn_out", il);
  10521. cur = ggml_add(ctx0, cur, inpL);
  10522. cb(cur, "ffn_out", il);
  10523. cur = ggml_add(ctx0, cur, attn_out);
  10524. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10525. cb(cur, "l_out", il);
  10526. // input for next layer
  10527. inpL = cur;
  10528. } else {
  10529. // attention and ffn are computed sequentially
  10530. // x = x + attn(ln1(x))
  10531. // x = x + ffn(ln2(x))
  10532. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10533. cb(ffn_inp, "ffn_inp", il);
  10534. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10535. model.layers[il].ffn_norm,
  10536. model.layers[il].ffn_norm_b,
  10537. LLM_NORM, cb, il);
  10538. cb(cur, "ffn_norm", il);
  10539. cur = llm_build_ffn(ctx0, lctx, cur,
  10540. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10541. NULL, NULL, NULL,
  10542. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10543. NULL,
  10544. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10545. cb(cur, "ffn_out", il);
  10546. cur = ggml_add(ctx0, cur, ffn_inp);
  10547. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10548. cb(cur, "l_out", il);
  10549. // input for next layer
  10550. inpL = cur;
  10551. }
  10552. }
  10553. cur = llm_build_norm(ctx0, inpL, hparams,
  10554. model.output_norm,
  10555. model.output_norm_b,
  10556. LLM_NORM, cb, -1);
  10557. cb(cur, "result_norm", -1);
  10558. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10559. cb(cur, "result_output", -1);
  10560. ggml_build_forward_expand(gf, cur);
  10561. return gf;
  10562. }
  10563. struct ggml_cgraph * build_arctic() {
  10564. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10565. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10566. int32_t n_tokens = this->n_tokens;
  10567. const int64_t n_embd_head = hparams.n_embd_head_v;
  10568. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10569. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10570. struct ggml_tensor * cur;
  10571. struct ggml_tensor * inpL;
  10572. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10573. // inp_pos - contains the positions
  10574. struct ggml_tensor * inp_pos = build_inp_pos();
  10575. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10576. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10577. for (int il = 0; il < n_layer; ++il) {
  10578. struct ggml_tensor * inpSA = inpL;
  10579. // norm
  10580. cur = llm_build_norm(ctx0, inpL, hparams,
  10581. model.layers[il].attn_norm, NULL,
  10582. LLM_NORM_RMS, cb, il);
  10583. cb(cur, "attn_norm", il);
  10584. // self-attention
  10585. {
  10586. // compute Q and K and RoPE them
  10587. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10588. cb(Qcur, "Qcur", il);
  10589. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10590. cb(Kcur, "Kcur", il);
  10591. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10592. cb(Vcur, "Vcur", il);
  10593. Qcur = ggml_rope_ext(
  10594. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10595. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10596. ext_factor, attn_factor, beta_fast, beta_slow
  10597. );
  10598. cb(Qcur, "Qcur", il);
  10599. Kcur = ggml_rope_ext(
  10600. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10601. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10602. ext_factor, attn_factor, beta_fast, beta_slow
  10603. );
  10604. cb(Kcur, "Kcur", il);
  10605. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10606. model.layers[il].wo, NULL,
  10607. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10608. }
  10609. if (il == n_layer - 1) {
  10610. // skip computing output for unused tokens
  10611. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10612. n_tokens = n_outputs;
  10613. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10614. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10615. }
  10616. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10617. cb(ffn_inp, "ffn_inp", il);
  10618. // feed-forward network
  10619. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10620. model.layers[il].ffn_norm, NULL,
  10621. LLM_NORM_RMS, cb, il);
  10622. cb(cur, "ffn_norm", il);
  10623. cur = llm_build_ffn(ctx0, lctx, cur,
  10624. model.layers[il].ffn_up, NULL, NULL,
  10625. model.layers[il].ffn_gate, NULL, NULL,
  10626. model.layers[il].ffn_down, NULL, NULL,
  10627. NULL,
  10628. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10629. cb(cur, "ffn_out", il);
  10630. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  10631. cb(ffn_out, "ffn_out", il);
  10632. // MoE
  10633. cur = llm_build_norm(ctx0, inpSA, hparams,
  10634. model.layers[il].ffn_norm_exps, NULL,
  10635. LLM_NORM_RMS, cb, il);
  10636. cb(cur, "ffn_norm_exps", il);
  10637. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10638. model.layers[il].ffn_gate_inp,
  10639. model.layers[il].ffn_up_exps,
  10640. model.layers[il].ffn_gate_exps,
  10641. model.layers[il].ffn_down_exps,
  10642. n_expert, n_expert_used,
  10643. LLM_FFN_SILU, true,
  10644. false, 0.0,
  10645. cb, il);
  10646. cb(cur, "ffn_moe_out", il);
  10647. cur = ggml_add(ctx0, cur, ffn_out);
  10648. cb(cur, "ffn_out", il);
  10649. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10650. cb(cur, "l_out", il);
  10651. // input for next layer
  10652. inpL = cur;
  10653. }
  10654. cur = inpL;
  10655. cur = llm_build_norm(ctx0, cur, hparams,
  10656. model.output_norm, NULL,
  10657. LLM_NORM_RMS, cb, -1);
  10658. cb(cur, "result_norm", -1);
  10659. // lm_head
  10660. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10661. cb(cur, "result_output", -1);
  10662. ggml_build_forward_expand(gf, cur);
  10663. return gf;
  10664. }
  10665. struct ggml_cgraph * build_deepseek2() {
  10666. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10667. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10668. int32_t n_tokens = this->n_tokens;
  10669. bool is_lite = (hparams.n_layer == 27);
  10670. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  10671. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  10672. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  10673. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  10674. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  10675. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  10676. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  10677. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  10678. struct ggml_tensor * cur;
  10679. struct ggml_tensor * inpL;
  10680. // {n_embd, n_tokens}
  10681. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10682. // inp_pos - contains the positions
  10683. struct ggml_tensor * inp_pos = build_inp_pos();
  10684. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10685. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10686. for (int il = 0; il < n_layer; ++il) {
  10687. struct ggml_tensor * inpSA = inpL;
  10688. // norm
  10689. cur = llm_build_norm(ctx0, inpL, hparams,
  10690. model.layers[il].attn_norm, NULL,
  10691. LLM_NORM_RMS, cb, il);
  10692. cb(cur, "attn_norm", il);
  10693. // self_attention
  10694. {
  10695. struct ggml_tensor * q = NULL;
  10696. if (!is_lite) {
  10697. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  10698. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  10699. cb(q, "q", il);
  10700. q = llm_build_norm(ctx0, q, hparams,
  10701. model.layers[il].attn_q_a_norm, NULL,
  10702. LLM_NORM_RMS, cb, il);
  10703. cb(q, "q", il);
  10704. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  10705. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  10706. cb(q, "q", il);
  10707. } else {
  10708. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  10709. cb(q, "q", il);
  10710. }
  10711. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10712. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  10713. ggml_row_size(q->type, hparams.n_embd_head_k),
  10714. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10715. 0);
  10716. cb(q_nope, "q_nope", il);
  10717. // and {n_head * n_embd_head_qk_rope, n_tokens}
  10718. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  10719. ggml_row_size(q->type, hparams.n_embd_head_k),
  10720. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10721. ggml_row_size(q->type, n_embd_head_qk_nope));
  10722. cb(q_pe, "q_pe", il);
  10723. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  10724. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  10725. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  10726. // split into {kv_lora_rank, n_tokens}
  10727. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  10728. kv_pe_compresseed->nb[1],
  10729. 0);
  10730. cb(kv_compressed, "kv_compressed", il);
  10731. // and {n_embd_head_qk_rope, n_tokens}
  10732. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  10733. kv_pe_compresseed->nb[1],
  10734. kv_pe_compresseed->nb[1],
  10735. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  10736. cb(k_pe, "k_pe", il);
  10737. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  10738. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  10739. model.layers[il].attn_kv_a_norm, NULL,
  10740. LLM_NORM_RMS, cb, il);
  10741. cb(kv_compressed, "kv_compressed", il);
  10742. // {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}
  10743. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  10744. cb(kv, "kv", il);
  10745. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10746. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  10747. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  10748. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10749. 0);
  10750. cb(k_nope, "k_nope", il);
  10751. // and {n_head * n_embd_head_v, n_tokens}
  10752. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  10753. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10754. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  10755. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  10756. cb(v_states, "v_states", il);
  10757. v_states = ggml_cont(ctx0, v_states);
  10758. cb(v_states, "v_states", il);
  10759. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  10760. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  10761. 0);
  10762. cb(v_states, "v_states", il);
  10763. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10764. q_pe = ggml_rope_ext(
  10765. ctx0, q_pe, inp_pos, nullptr,
  10766. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10767. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10768. );
  10769. cb(q_pe, "q_pe", il);
  10770. // shared RoPE key
  10771. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10772. k_pe = ggml_rope_ext(
  10773. ctx0, k_pe, inp_pos, nullptr,
  10774. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10775. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10776. );
  10777. cb(k_pe, "k_pe", il);
  10778. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  10779. cb(q_states, "q_states", il);
  10780. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  10781. cb(k_states, "k_states", il);
  10782. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10783. model.layers[il].wo, NULL,
  10784. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  10785. }
  10786. if (il == n_layer - 1) {
  10787. // skip computing output for unused tokens
  10788. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10789. n_tokens = n_outputs;
  10790. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10791. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10792. }
  10793. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10794. cb(ffn_inp, "ffn_inp", il);
  10795. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10796. model.layers[il].ffn_norm, NULL,
  10797. LLM_NORM_RMS, cb, il);
  10798. cb(cur, "ffn_norm", il);
  10799. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  10800. cur = llm_build_ffn(ctx0, lctx, cur,
  10801. model.layers[il].ffn_up, NULL, NULL,
  10802. model.layers[il].ffn_gate, NULL, NULL,
  10803. model.layers[il].ffn_down, NULL, NULL,
  10804. NULL,
  10805. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10806. cb(cur, "ffn_out", il);
  10807. } else {
  10808. // MoE branch
  10809. ggml_tensor * moe_out =
  10810. llm_build_moe_ffn(ctx0, lctx, cur,
  10811. model.layers[il].ffn_gate_inp,
  10812. model.layers[il].ffn_up_exps,
  10813. model.layers[il].ffn_gate_exps,
  10814. model.layers[il].ffn_down_exps,
  10815. n_expert, n_expert_used,
  10816. LLM_FFN_SILU, false,
  10817. true, hparams.expert_weights_scale,
  10818. cb, il);
  10819. cb(moe_out, "ffn_moe_out", il);
  10820. // FFN shared expert
  10821. {
  10822. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  10823. model.layers[il].ffn_up_shexp, NULL, NULL,
  10824. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10825. model.layers[il].ffn_down_shexp, NULL, NULL,
  10826. NULL,
  10827. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10828. cb(ffn_shexp, "ffn_shexp", il);
  10829. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  10830. cb(cur, "ffn_out", il);
  10831. }
  10832. }
  10833. cur = ggml_add(ctx0, cur, ffn_inp);
  10834. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10835. cb(cur, "l_out", il);
  10836. // input for next layer
  10837. inpL = cur;
  10838. }
  10839. cur = inpL;
  10840. cur = llm_build_norm(ctx0, cur, hparams,
  10841. model.output_norm, NULL,
  10842. LLM_NORM_RMS, cb, -1);
  10843. cb(cur, "result_norm", -1);
  10844. // lm_head
  10845. cur = ggml_mul_mat(ctx0, model.output, cur);
  10846. cb(cur, "result_output", -1);
  10847. ggml_build_forward_expand(gf, cur);
  10848. return gf;
  10849. }
  10850. struct ggml_cgraph * build_bitnet() {
  10851. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10852. const int64_t n_embd_head = hparams.n_embd_head_v;
  10853. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10854. struct ggml_tensor * cur;
  10855. struct ggml_tensor * inpL;
  10856. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10857. // inp_pos - contains the positions
  10858. struct ggml_tensor * inp_pos = build_inp_pos();
  10859. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10860. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10861. for (int il = 0; il < n_layer; ++il) {
  10862. struct ggml_tensor * inpSA = inpL;
  10863. cur = llm_build_norm(ctx0, inpL, hparams,
  10864. model.layers[il].attn_norm, NULL,
  10865. LLM_NORM_RMS, cb, il);
  10866. cb(cur, "attn_norm", il);
  10867. // self-attention
  10868. {
  10869. // compute Q and K and RoPE them
  10870. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10871. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  10872. cb(Qcur, "Qcur", il);
  10873. if (model.layers[il].bq) {
  10874. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10875. cb(Qcur, "Qcur", il);
  10876. }
  10877. // B1.K
  10878. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10879. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  10880. cb(Kcur, "Kcur", il);
  10881. if (model.layers[il].bk) {
  10882. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10883. cb(Kcur, "Kcur", il);
  10884. }
  10885. // B1.V
  10886. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10887. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  10888. cb(Vcur, "Vcur", il);
  10889. if (model.layers[il].bv) {
  10890. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10891. cb(Vcur, "Vcur", il);
  10892. }
  10893. Qcur = ggml_rope_ext(
  10894. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10895. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10896. ext_factor, attn_factor, beta_fast, beta_slow
  10897. );
  10898. cb(Qcur, "Qcur", il);
  10899. Kcur = ggml_rope_ext(
  10900. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10901. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10902. ext_factor, attn_factor, beta_fast, beta_slow
  10903. );
  10904. cb(Kcur, "Kcur", il);
  10905. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10906. NULL, NULL,
  10907. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10908. cur = llm_build_norm(ctx0, cur, hparams,
  10909. model.layers[il].attn_sub_norm, NULL,
  10910. LLM_NORM_RMS, cb, il);
  10911. cb(cur, "attn_sub_norm", il);
  10912. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10913. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  10914. if (model.layers[il].bo) {
  10915. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10916. }
  10917. cb(cur, "attn_o_out", il);
  10918. }
  10919. if (il == n_layer - 1) {
  10920. // skip computing output for unused tokens
  10921. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10922. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10923. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10924. }
  10925. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10926. cb(ffn_inp, "ffn_inp", il);
  10927. // feed-forward forward
  10928. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10929. model.layers[il].ffn_norm, NULL,
  10930. LLM_NORM_RMS, cb, il);
  10931. cb(cur, "ffn_norm", il);
  10932. cur = llm_build_ffn(ctx0, lctx, cur,
  10933. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  10934. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  10935. NULL, NULL, NULL,
  10936. NULL,
  10937. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10938. cb(cur, "ffn_sub_out", il);
  10939. cur = llm_build_norm(ctx0, cur, hparams,
  10940. model.layers[il].ffn_sub_norm, NULL,
  10941. LLM_NORM_RMS, cb, il);
  10942. cb(cur, "ffn_sub_norm", il);
  10943. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  10944. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  10945. cb(cur, "ffn_down", il);
  10946. cur = ggml_add(ctx0, cur, ffn_inp);
  10947. cb(cur, "l_out", il);
  10948. // input for next layer
  10949. inpL = cur;
  10950. }
  10951. cur = inpL;
  10952. cur = llm_build_norm(ctx0, cur, hparams,
  10953. model.output_norm, NULL,
  10954. LLM_NORM_RMS, cb, -1);
  10955. cb(cur, "result_norm", -1);
  10956. // lm_head
  10957. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  10958. cb(cur, "result_output", -1);
  10959. ggml_build_forward_expand(gf, cur);
  10960. return gf;
  10961. }
  10962. struct ggml_cgraph * build_t5() {
  10963. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10964. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10965. int32_t n_tokens = this->n_tokens;
  10966. const int64_t n_embd_head = hparams.n_embd_head_v;
  10967. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10968. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10969. struct ggml_tensor * cur;
  10970. struct ggml_tensor * inpL;
  10971. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10972. if (lctx.is_encoding) {
  10973. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  10974. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10975. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  10976. for (int il = 0; il < n_layer; ++il) {
  10977. struct ggml_tensor * inpSA = inpL;
  10978. // norm
  10979. cur = llm_build_norm(ctx0, inpL, hparams,
  10980. model.layers[il].attn_norm_enc, NULL,
  10981. LLM_NORM_RMS, cb, il);
  10982. cb(cur, "attn_norm", il);
  10983. // self-attention
  10984. {
  10985. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_enc, cur);
  10986. cb(Qcur, "Qcur", il);
  10987. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_enc, cur);
  10988. cb(Kcur, "Kcur", il);
  10989. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_enc, cur);
  10990. cb(Vcur, "Vcur", il);
  10991. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10992. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10993. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10994. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10995. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10996. cb(kq, "kq", il);
  10997. 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;
  10998. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  10999. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11000. cb(kq_b, "kq_b", il);
  11001. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  11002. cb(kq, "kq_soft_max_ext", il);
  11003. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  11004. cb(v, "v", il);
  11005. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  11006. cb(kqv, "kqv", il);
  11007. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11008. cb(kqv_merged, "kqv_merged", il);
  11009. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11010. cb(cur, "kqv_merged_cont", il);
  11011. ggml_build_forward_expand(gf, cur);
  11012. cur = ggml_mul_mat(ctx0, model.layers[il].wo_enc, cur);
  11013. cb(cur, "kqv_out", il);
  11014. }
  11015. if (il == n_layer - 1) {
  11016. // skip computing output for unused tokens
  11017. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11018. n_tokens = n_outputs;
  11019. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11020. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11021. }
  11022. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11023. cb(ffn_inp, "ffn_inp", il);
  11024. // feed-forward network
  11025. {
  11026. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11027. model.layers[il].ffn_norm_enc, NULL,
  11028. LLM_NORM_RMS, cb, il);
  11029. cb(cur, "ffn_norm", il);
  11030. // T5 uses relu, flan-T5 uses gelu-gated
  11031. cur = llm_build_ffn(ctx0, lctx, cur,
  11032. model.layers[il].ffn_up_enc, NULL, NULL,
  11033. model.layers[il].ffn_gate_enc, NULL, NULL,
  11034. model.layers[il].ffn_down_enc, NULL, NULL,
  11035. NULL,
  11036. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11037. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11038. cb, il);
  11039. cb(cur, "ffn_out", il);
  11040. }
  11041. cur = ggml_add(ctx0, cur, ffn_inp);
  11042. cb(cur, "ffn_out", il);
  11043. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11044. if (layer_dir != nullptr) {
  11045. cur = ggml_add(ctx0, cur, layer_dir);
  11046. }
  11047. cb(cur, "l_out", il);
  11048. // input for next layer
  11049. inpL = cur;
  11050. }
  11051. cur = inpL;
  11052. cb(cur, "result_embd", -1);
  11053. cur = llm_build_norm(ctx0, cur, hparams,
  11054. model.output_norm_enc, NULL,
  11055. LLM_NORM_RMS, cb, -1);
  11056. cb(cur, "result_norm", -1);
  11057. } else {
  11058. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  11059. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  11060. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  11061. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  11062. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  11063. for (int il = 0; il < n_layer; ++il) {
  11064. struct ggml_tensor * inpSA = inpL;
  11065. // norm
  11066. cur = llm_build_norm(ctx0, inpL, hparams,
  11067. model.layers[il].attn_norm, NULL,
  11068. LLM_NORM_RMS, cb, il);
  11069. cb(cur, "attn_norm", il);
  11070. // self-attention
  11071. {
  11072. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  11073. cb(Qcur, "Qcur", il);
  11074. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  11075. cb(Kcur, "Kcur", il);
  11076. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  11077. cb(Vcur, "Vcur", il);
  11078. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  11079. struct ggml_tensor * k =
  11080. ggml_view_3d(ctx0, kv_self.k_l[il],
  11081. n_embd_head_k, n_kv, n_head_kv,
  11082. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  11083. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  11084. 0);
  11085. cb(k, "k", il);
  11086. struct ggml_tensor * v =
  11087. ggml_view_3d(ctx0, kv_self.v_l[il],
  11088. n_kv, n_embd_head_v, n_head_kv,
  11089. ggml_element_size(kv_self.v_l[il])*n_ctx,
  11090. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  11091. 0);
  11092. cb(v, "v", il);
  11093. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11094. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11095. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11096. cb(kq, "kq", il);
  11097. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  11098. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  11099. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11100. cb(kq_b, "kq_b", il);
  11101. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  11102. cb(kq, "kq_soft_max_ext", il);
  11103. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  11104. cb(kqv, "kqv", il);
  11105. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11106. cb(kqv_merged, "kqv_merged", il);
  11107. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11108. cb(cur, "kqv_merged_cont", il);
  11109. ggml_build_forward_expand(gf, cur);
  11110. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  11111. cb(cur, "kqv_out", il);
  11112. }
  11113. cur = ggml_add(ctx0, cur, inpSA);
  11114. cb(cur, "cross_inp", il);
  11115. struct ggml_tensor * inpCA = cur;
  11116. // norm
  11117. cur = llm_build_norm(ctx0, cur, hparams,
  11118. model.layers[il].attn_norm_cross, NULL,
  11119. LLM_NORM_RMS, cb, il);
  11120. cb(cur, "attn_norm_cross", il);
  11121. // cross-attention
  11122. {
  11123. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_cross, cur);
  11124. cb(Qcur, "Qcur", il);
  11125. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_cross, embd_enc);
  11126. cb(Kcur, "Kcur", il);
  11127. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_cross, embd_enc);
  11128. cb(Vcur, "Vcur", il);
  11129. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11130. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  11131. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11132. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  11133. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11134. cb(kq, "kq", il);
  11135. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  11136. cb(kq, "kq_soft_max_ext", il);
  11137. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  11138. cb(v, "v", il);
  11139. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  11140. cb(kqv, "kqv", il);
  11141. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11142. cb(kqv_merged, "kqv_merged", il);
  11143. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11144. cb(cur, "kqv_merged_cont", il);
  11145. ggml_build_forward_expand(gf, cur);
  11146. cur = ggml_mul_mat(ctx0, model.layers[il].wo_cross, cur);
  11147. cb(cur, "kqv_out", il);
  11148. }
  11149. if (il == n_layer - 1) {
  11150. // skip computing output for unused tokens
  11151. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11152. n_tokens = n_outputs;
  11153. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11154. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11155. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  11156. }
  11157. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  11158. cb(ffn_inp, "ffn_inp", il);
  11159. // feed-forward network
  11160. {
  11161. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11162. model.layers[il].ffn_norm, NULL,
  11163. LLM_NORM_RMS, cb, il);
  11164. cb(cur, "ffn_norm", il);
  11165. // T5 uses relu, flan-T5 uses gelu-gated
  11166. cur = llm_build_ffn(ctx0, lctx, cur,
  11167. model.layers[il].ffn_up, NULL, NULL,
  11168. model.layers[il].ffn_gate, NULL, NULL,
  11169. model.layers[il].ffn_down, NULL, NULL,
  11170. NULL,
  11171. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11172. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11173. cb, il);
  11174. cb(cur, "ffn_out", il);
  11175. }
  11176. cur = ggml_add(ctx0, cur, ffn_inp);
  11177. cb(cur, "ffn_out", il);
  11178. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11179. if (layer_dir != nullptr) {
  11180. cur = ggml_add(ctx0, cur, layer_dir);
  11181. }
  11182. cb(cur, "l_out", il);
  11183. // input for next layer
  11184. inpL = cur;
  11185. }
  11186. cur = inpL;
  11187. cb(cur, "result_embd", -1);
  11188. cur = llm_build_norm(ctx0, cur, hparams,
  11189. model.output_norm, NULL,
  11190. LLM_NORM_RMS, cb, -1);
  11191. cb(cur, "result_norm", -1);
  11192. // lm_head
  11193. cur = ggml_mul_mat(ctx0, model.output, cur);
  11194. cb(cur, "result_output", -1);
  11195. }
  11196. ggml_build_forward_expand(gf, cur);
  11197. return gf;
  11198. }
  11199. struct ggml_cgraph * build_jais() {
  11200. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11201. const int64_t n_embd_head = hparams.n_embd_head_v;
  11202. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11203. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11204. struct ggml_tensor * cur;
  11205. struct ggml_tensor * inpL;
  11206. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11207. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11208. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11209. for (int il = 0; il < n_layer; ++il) {
  11210. cur = llm_build_norm(ctx0, inpL, hparams,
  11211. model.layers[il].attn_norm,
  11212. model.layers[il].attn_norm_b,
  11213. LLM_NORM, cb, il);
  11214. cb(cur, "attn_norm", il);
  11215. // self-attention
  11216. {
  11217. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11218. cb(cur, "wqkv", il);
  11219. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11220. cb(cur, "bqkv", il);
  11221. 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)));
  11222. 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)));
  11223. 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)));
  11224. cb(Qcur, "Qcur", il);
  11225. cb(Kcur, "Kcur", il);
  11226. cb(Vcur, "Vcur", il);
  11227. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11228. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11229. model.layers[il].wo, model.layers[il].bo,
  11230. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  11231. }
  11232. if (il == n_layer - 1) {
  11233. // skip computing output for unused tokens
  11234. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11235. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11236. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11237. }
  11238. // add the input
  11239. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11240. cb(ffn_inp, "ffn_inp", il);
  11241. // FF
  11242. {
  11243. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11244. model.layers[il].ffn_norm,
  11245. model.layers[il].ffn_norm_b,
  11246. LLM_NORM, cb, il);
  11247. cb(cur, "ffn_norm", il);
  11248. cur = llm_build_ffn(ctx0, lctx, cur,
  11249. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11250. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  11251. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11252. NULL,
  11253. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11254. cb(cur, "ffn_out", il);
  11255. }
  11256. inpL = ggml_add(ctx0, cur, ffn_inp);
  11257. cb(inpL, "l_out", il);
  11258. }
  11259. cur = llm_build_norm(ctx0, inpL, hparams,
  11260. model.output_norm,
  11261. model.output_norm_b,
  11262. LLM_NORM, cb, -1);
  11263. cb(cur, "result_norm", -1);
  11264. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11265. cb(cur, "result_output", -1);
  11266. ggml_build_forward_expand(gf, cur);
  11267. return gf;
  11268. }
  11269. struct ggml_cgraph * build_chatglm() {
  11270. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11271. const int64_t n_embd_head = hparams.n_embd_head_v;
  11272. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11273. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11274. struct ggml_tensor * cur;
  11275. struct ggml_tensor * inpL;
  11276. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11277. // inp_pos - contains the positions
  11278. struct ggml_tensor * inp_pos = build_inp_pos();
  11279. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11280. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11281. for (int il = 0; il < n_layer; ++il) {
  11282. struct ggml_tensor * inpSA = inpL;
  11283. cur = llm_build_norm(ctx0, inpL, hparams,
  11284. model.layers[il].attn_norm,
  11285. NULL,
  11286. LLM_NORM_RMS, cb, il);
  11287. cb(cur, "attn_norm", il);
  11288. // self-attention
  11289. {
  11290. struct ggml_tensor * Qcur = nullptr;
  11291. struct ggml_tensor * Kcur = nullptr;
  11292. struct ggml_tensor * Vcur = nullptr;
  11293. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11294. cb(cur, "wqkv", il);
  11295. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11296. cb(cur, "bqkv", il);
  11297. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11298. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11299. 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)));
  11300. cb(Qcur, "Qcur", il);
  11301. cb(Kcur, "Kcur", il);
  11302. cb(Vcur, "Vcur", il);
  11303. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  11304. Qcur = ggml_rope_ext(
  11305. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11306. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11307. ext_factor, attn_factor, beta_fast, beta_slow
  11308. );
  11309. cb(Qcur, "Qcur_rope", il);
  11310. Kcur = ggml_rope_ext(
  11311. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11312. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11313. ext_factor, attn_factor, beta_fast, beta_slow
  11314. );
  11315. cb(Kcur, "Kcur_rope", il);
  11316. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11317. model.layers[il].wo, NULL,
  11318. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11319. }
  11320. if (il == n_layer - 1) {
  11321. // skip computing output for unused tokens
  11322. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11323. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11324. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11325. }
  11326. // Add the input
  11327. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11328. cb(ffn_inp, "ffn_inp", il);
  11329. // FF
  11330. {
  11331. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11332. model.layers[il].ffn_norm,
  11333. NULL,
  11334. LLM_NORM_RMS, cb, il);
  11335. cb(cur, "ffn_norm", il);
  11336. cur = llm_build_ffn(ctx0, lctx, cur,
  11337. model.layers[il].ffn_up, NULL, NULL,
  11338. NULL, NULL, NULL,
  11339. model.layers[il].ffn_down, NULL, NULL,
  11340. NULL,
  11341. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11342. cb(cur, "ffn_out", il);
  11343. }
  11344. inpL = ggml_add(ctx0, cur, ffn_inp);
  11345. cb(inpL, "l_out", il);
  11346. }
  11347. cur = llm_build_norm(ctx0, inpL, hparams,
  11348. model.output_norm,
  11349. NULL,
  11350. LLM_NORM_RMS, cb, -1);
  11351. cb(cur, "result_norm", -1);
  11352. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11353. cb(cur, "result_output", -1);
  11354. ggml_build_forward_expand(gf, cur);
  11355. return gf;
  11356. }
  11357. };
  11358. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  11359. llama_batch dummy;
  11360. dummy.n_tokens = 0;
  11361. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11362. struct llm_build_context llm(lctx, dummy, cb, false);
  11363. llm.init();
  11364. struct ggml_cgraph * result = llm.build_defrag(ids);
  11365. llm.free();
  11366. return result;
  11367. }
  11368. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  11369. llama_batch dummy;
  11370. dummy.n_tokens = 0;
  11371. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11372. struct llm_build_context llm(lctx, dummy, cb, false);
  11373. llm.init();
  11374. struct ggml_cgraph * result = llm.build_k_shift();
  11375. llm.free();
  11376. return result;
  11377. }
  11378. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  11379. llama_batch dummy;
  11380. dummy.n_tokens = 0;
  11381. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11382. struct llm_build_context llm(lctx, dummy, cb, false);
  11383. llm.init();
  11384. struct ggml_cgraph * result = llm.build_s_copy();
  11385. llm.free();
  11386. return result;
  11387. }
  11388. static struct ggml_cgraph * llama_build_graph(
  11389. llama_context & lctx,
  11390. const llama_batch & batch,
  11391. bool worst_case) {
  11392. const auto & model = lctx.model;
  11393. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  11394. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  11395. if (il >= 0) {
  11396. ggml_format_name(cur, "%s-%d", name, il);
  11397. } else {
  11398. ggml_set_name(cur, name);
  11399. }
  11400. if (!lctx.cparams.offload_kqv) {
  11401. if (strcmp(name, "kqv_merged_cont") == 0) {
  11402. // all nodes between the KV store and the attention output are run on the CPU
  11403. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  11404. }
  11405. }
  11406. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  11407. // FIXME: fix in ggml_backend_sched
  11408. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  11409. if (batch.n_tokens < 32 || full_offload) {
  11410. if (il != -1 && strcmp(name, "norm") == 0) {
  11411. for (auto * backend : lctx.backends) {
  11412. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  11413. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  11414. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  11415. break;
  11416. }
  11417. }
  11418. }
  11419. }
  11420. };
  11421. struct ggml_cgraph * result = NULL;
  11422. struct llm_build_context llm(lctx, batch, cb, worst_case);
  11423. llm.init();
  11424. switch (model.arch) {
  11425. case LLM_ARCH_LLAMA:
  11426. {
  11427. result = llm.build_llama();
  11428. } break;
  11429. case LLM_ARCH_BAICHUAN:
  11430. {
  11431. result = llm.build_baichuan();
  11432. } break;
  11433. case LLM_ARCH_FALCON:
  11434. {
  11435. result = llm.build_falcon();
  11436. } break;
  11437. case LLM_ARCH_GROK:
  11438. {
  11439. result = llm.build_grok();
  11440. } break;
  11441. case LLM_ARCH_STARCODER:
  11442. {
  11443. result = llm.build_starcoder();
  11444. } break;
  11445. case LLM_ARCH_REFACT:
  11446. {
  11447. result = llm.build_refact();
  11448. } break;
  11449. case LLM_ARCH_BERT:
  11450. case LLM_ARCH_JINA_BERT_V2:
  11451. case LLM_ARCH_NOMIC_BERT:
  11452. {
  11453. result = llm.build_bert();
  11454. } break;
  11455. case LLM_ARCH_BLOOM:
  11456. {
  11457. result = llm.build_bloom();
  11458. } break;
  11459. case LLM_ARCH_MPT:
  11460. {
  11461. result = llm.build_mpt();
  11462. } break;
  11463. case LLM_ARCH_STABLELM:
  11464. {
  11465. result = llm.build_stablelm();
  11466. } break;
  11467. case LLM_ARCH_QWEN:
  11468. {
  11469. result = llm.build_qwen();
  11470. } break;
  11471. case LLM_ARCH_QWEN2:
  11472. {
  11473. result = llm.build_qwen2();
  11474. } break;
  11475. case LLM_ARCH_QWEN2MOE:
  11476. {
  11477. result = llm.build_qwen2moe();
  11478. } break;
  11479. case LLM_ARCH_PHI2:
  11480. {
  11481. result = llm.build_phi2();
  11482. } break;
  11483. case LLM_ARCH_PHI3:
  11484. {
  11485. result = llm.build_phi3();
  11486. } break;
  11487. case LLM_ARCH_PLAMO:
  11488. {
  11489. result = llm.build_plamo();
  11490. } break;
  11491. case LLM_ARCH_GPT2:
  11492. {
  11493. result = llm.build_gpt2();
  11494. } break;
  11495. case LLM_ARCH_CODESHELL:
  11496. {
  11497. result = llm.build_codeshell();
  11498. } break;
  11499. case LLM_ARCH_ORION:
  11500. {
  11501. result = llm.build_orion();
  11502. } break;
  11503. case LLM_ARCH_INTERNLM2:
  11504. {
  11505. result = llm.build_internlm2();
  11506. } break;
  11507. case LLM_ARCH_MINICPM:
  11508. {
  11509. result = llm.build_minicpm();
  11510. } break;
  11511. case LLM_ARCH_GEMMA:
  11512. {
  11513. result = llm.build_gemma();
  11514. } break;
  11515. case LLM_ARCH_GEMMA2:
  11516. {
  11517. result = llm.build_gemma2();
  11518. } break;
  11519. case LLM_ARCH_STARCODER2:
  11520. {
  11521. result = llm.build_starcoder2();
  11522. } break;
  11523. case LLM_ARCH_MAMBA:
  11524. {
  11525. result = llm.build_mamba();
  11526. } break;
  11527. case LLM_ARCH_XVERSE:
  11528. {
  11529. result = llm.build_xverse();
  11530. } break;
  11531. case LLM_ARCH_COMMAND_R:
  11532. {
  11533. result = llm.build_command_r();
  11534. } break;
  11535. case LLM_ARCH_DBRX:
  11536. {
  11537. result = llm.build_dbrx();
  11538. } break;
  11539. case LLM_ARCH_OLMO:
  11540. {
  11541. result = llm.build_olmo();
  11542. } break;
  11543. case LLM_ARCH_OPENELM:
  11544. {
  11545. result = llm.build_openelm();
  11546. } break;
  11547. case LLM_ARCH_GPTNEOX:
  11548. {
  11549. result = llm.build_gptneox();
  11550. } break;
  11551. case LLM_ARCH_ARCTIC:
  11552. {
  11553. result = llm.build_arctic();
  11554. } break;
  11555. case LLM_ARCH_DEEPSEEK2:
  11556. {
  11557. result = llm.build_deepseek2();
  11558. } break;
  11559. case LLM_ARCH_CHATGLM:
  11560. {
  11561. result = llm.build_chatglm();
  11562. } break;
  11563. case LLM_ARCH_BITNET:
  11564. {
  11565. result = llm.build_bitnet();
  11566. } break;
  11567. case LLM_ARCH_T5:
  11568. {
  11569. result = llm.build_t5();
  11570. } break;
  11571. case LLM_ARCH_JAIS:
  11572. {
  11573. result = llm.build_jais();
  11574. } break;
  11575. default:
  11576. GGML_ABORT("fatal error");
  11577. }
  11578. // add on pooling layer
  11579. if (lctx.cparams.embeddings) {
  11580. result = llm.append_pooling(result);
  11581. }
  11582. llm.free();
  11583. return result;
  11584. }
  11585. static void llama_set_k_shift(llama_context & lctx) {
  11586. const int64_t kv_size = lctx.kv_self.size;
  11587. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  11588. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  11589. for (int i = 0; i < kv_size; ++i) {
  11590. data[i] = lctx.kv_self.cells[i].delta;
  11591. }
  11592. }
  11593. static void llama_set_s_copy(llama_context & lctx) {
  11594. const int64_t kv_size = lctx.kv_self.size;
  11595. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  11596. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  11597. for (int i = 0; i < kv_size; ++i) {
  11598. data[i] = lctx.kv_self.cells[i].src;
  11599. }
  11600. }
  11601. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  11602. // TODO move to hparams if a T5 variant appears that uses a different value
  11603. const int64_t max_distance = 128;
  11604. if (bidirectional) {
  11605. n_buckets >>= 1;
  11606. }
  11607. const int64_t max_exact = n_buckets >> 1;
  11608. int32_t relative_position = x - y;
  11609. int32_t relative_bucket = 0;
  11610. if (bidirectional) {
  11611. relative_bucket += (relative_position > 0) * n_buckets;
  11612. relative_position = abs(relative_position);
  11613. } else {
  11614. relative_position = -std::min<int32_t>(relative_position, 0);
  11615. }
  11616. 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));
  11617. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  11618. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  11619. return relative_bucket;
  11620. }
  11621. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  11622. //
  11623. // set input data
  11624. //
  11625. const auto & hparams = lctx.model.hparams;
  11626. const auto & cparams = lctx.cparams;
  11627. const auto & kv_self = lctx.kv_self;
  11628. if (batch.token) {
  11629. const int64_t n_tokens = batch.n_tokens;
  11630. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  11631. }
  11632. if (batch.embd) {
  11633. const int64_t n_embd = hparams.n_embd;
  11634. const int64_t n_tokens = batch.n_tokens;
  11635. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  11636. }
  11637. if (batch.pos && lctx.inp_pos) {
  11638. const int64_t n_tokens = batch.n_tokens;
  11639. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  11640. }
  11641. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  11642. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  11643. const int64_t n_tokens = batch.n_tokens;
  11644. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  11645. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  11646. if (lctx.n_outputs == n_tokens) {
  11647. for (int i = 0; i < n_tokens; ++i) {
  11648. data[i] = i;
  11649. }
  11650. } else if (batch.logits) {
  11651. int32_t n_outputs = 0;
  11652. for (int i = 0; i < n_tokens; ++i) {
  11653. if (batch.logits[i]) {
  11654. data[n_outputs++] = i;
  11655. }
  11656. }
  11657. // the graph needs to have been passed the correct number of outputs
  11658. GGML_ASSERT(lctx.n_outputs == n_outputs);
  11659. } else if (lctx.n_outputs == 1) {
  11660. // only keep last output
  11661. data[0] = n_tokens - 1;
  11662. } else {
  11663. GGML_ASSERT(lctx.n_outputs == 0);
  11664. }
  11665. }
  11666. GGML_ASSERT(
  11667. // (!a || b) is a logical implication (a -> b)
  11668. // !hparams.causal_attn -> !cparams.causal_attn
  11669. (hparams.causal_attn || !cparams.causal_attn) &&
  11670. "causal attention is not supported by this model"
  11671. );
  11672. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  11673. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  11674. if (cparams.causal_attn && !lctx.is_encoding) {
  11675. const int64_t n_kv = kv_self.n;
  11676. const int64_t n_tokens = batch.n_tokens;
  11677. float * data = nullptr;
  11678. float * data_swa = nullptr;
  11679. if (lctx.inp_KQ_mask) {
  11680. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11681. data = (float *) lctx.inp_KQ_mask->data;
  11682. }
  11683. if (lctx.inp_KQ_mask_swa) {
  11684. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  11685. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  11686. }
  11687. // For causal attention, use only the previous KV cells
  11688. // of the correct sequence for each token of the batch.
  11689. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  11690. for (int h = 0; h < 1; ++h) {
  11691. for (int j = 0; j < n_tokens; ++j) {
  11692. const llama_pos pos = batch.pos[j];
  11693. const llama_seq_id seq_id = batch.seq_id[j][0];
  11694. for (int i = 0; i < n_kv; ++i) {
  11695. float f;
  11696. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  11697. f = -INFINITY;
  11698. } else {
  11699. if (hparams.use_alibi) {
  11700. f = -std::abs(lctx.kv_self.cells[i].pos - pos);
  11701. } else {
  11702. f = 0.0f;
  11703. }
  11704. }
  11705. if (data) {
  11706. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11707. }
  11708. // may need to cut off old tokens for sliding window
  11709. if (data_swa) {
  11710. if (pos - lctx.kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  11711. f = -INFINITY;
  11712. }
  11713. data_swa[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11714. }
  11715. }
  11716. }
  11717. if (data) {
  11718. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11719. for (int j = 0; j < n_kv; ++j) {
  11720. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11721. }
  11722. }
  11723. }
  11724. if (data_swa) {
  11725. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11726. for (int j = 0; j < n_kv; ++j) {
  11727. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11728. }
  11729. }
  11730. }
  11731. }
  11732. } else {
  11733. // when using kv cache, the mask needs to match the kv cache size
  11734. const int64_t n_tokens = batch.n_tokens;
  11735. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  11736. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11737. float * data = (float *) lctx.inp_KQ_mask->data;
  11738. for (int h = 0; h < 1; ++h) {
  11739. for (int j = 0; j < n_tokens; ++j) {
  11740. const llama_seq_id seq_id = batch.seq_id[j][0];
  11741. for (int i = 0; i < n_tokens; ++i) {
  11742. float f = -INFINITY;
  11743. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  11744. if (batch.seq_id[i][s] == seq_id) {
  11745. if (hparams.use_alibi) {
  11746. f = -std::abs(batch.pos[i] - batch.pos[j]);
  11747. } else {
  11748. f = 0.0f;
  11749. }
  11750. break;
  11751. }
  11752. }
  11753. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  11754. }
  11755. for (int i = n_tokens; i < n_stride; ++i) {
  11756. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  11757. }
  11758. }
  11759. }
  11760. }
  11761. }
  11762. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  11763. const int64_t n_tokens = batch.n_tokens;
  11764. GGML_ASSERT(lctx.inp_mean);
  11765. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  11766. float * data = (float *) lctx.inp_mean->data;
  11767. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  11768. std::vector<uint64_t> sum(n_tokens, 0);
  11769. for (int i = 0; i < n_tokens; ++i) {
  11770. const llama_seq_id seq_id = batch.seq_id[i][0];
  11771. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  11772. sum[seq_id] += 1;
  11773. }
  11774. std::vector<float> div(n_tokens, 0.0f);
  11775. for (int i = 0; i < n_tokens; ++i) {
  11776. const uint64_t s = sum[i];
  11777. if (s > 0) {
  11778. div[i] = 1.0f/float(s);
  11779. }
  11780. }
  11781. for (int i = 0; i < n_tokens; ++i) {
  11782. const llama_seq_id seq_id = batch.seq_id[i][0];
  11783. data[seq_id*n_tokens + i] = div[seq_id];
  11784. }
  11785. }
  11786. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  11787. const int64_t n_tokens = batch.n_tokens;
  11788. GGML_ASSERT(lctx.inp_cls);
  11789. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11790. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11791. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11792. for (int i = 0; i < n_tokens; ++i) {
  11793. const llama_seq_id seq_id = batch.seq_id[i][0];
  11794. const llama_pos pos = batch.pos[i];
  11795. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  11796. if (pos == 0) {
  11797. data[seq_id] = i;
  11798. }
  11799. }
  11800. }
  11801. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  11802. const int64_t n_tokens = batch.n_tokens;
  11803. GGML_ASSERT(lctx.inp_cls);
  11804. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11805. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11806. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11807. std::vector<int> last_pos(n_tokens, -1);
  11808. std::vector<int> last_row(n_tokens, -1);
  11809. for (int i = 0; i < n_tokens; ++i) {
  11810. const llama_seq_id seq_id = batch.seq_id[i][0];
  11811. const llama_pos pos = batch.pos[i];
  11812. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  11813. if (pos >= last_pos[seq_id]) {
  11814. last_pos[seq_id] = pos;
  11815. last_row[seq_id] = i;
  11816. }
  11817. }
  11818. for (int i = 0; i < n_tokens; ++i) {
  11819. if (last_row[i] >= 0) {
  11820. data[i] = last_row[i];
  11821. }
  11822. }
  11823. }
  11824. if (kv_self.recurrent) {
  11825. const int64_t n_kv = kv_self.n;
  11826. if (lctx.inp_s_mask) {
  11827. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  11828. float * data = (float *) lctx.inp_s_mask->data;
  11829. // states which are not affected by the current batch are left untouched
  11830. for (int i = 0; i < n_kv; ++i) {
  11831. llama_seq_id seq_id = i + lctx.kv_self.head;
  11832. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  11833. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  11834. data[i] = (float) has_self_seq;
  11835. // ensure current sequences will be kept
  11836. if (!has_self_seq && kv_cell.pos >= 0) {
  11837. kv_cell.seq_id.insert(seq_id);
  11838. }
  11839. }
  11840. }
  11841. // For Mamba (and other recurrent architectures),
  11842. // update the correct state(s)/sequence(s) for each token of the batch.
  11843. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  11844. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  11845. if (lctx.inp_s_seq) {
  11846. const int64_t n_tokens = batch.n_tokens;
  11847. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  11848. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  11849. for (int j = 0; j < n_tokens; ++j) {
  11850. const int32_t n_seq = batch.n_seq_id[j];
  11851. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  11852. for (int i = 0; i < n_kv; ++i) {
  11853. if (i < n_seq) {
  11854. // for this type of model, the head is the minimum seq_id of the batch
  11855. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  11856. } else {
  11857. data[j*n_kv + i] = -1;
  11858. }
  11859. }
  11860. }
  11861. }
  11862. }
  11863. if (lctx.inp_pos_bucket) {
  11864. const int64_t n_tokens = batch.n_tokens;
  11865. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  11866. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  11867. if (!lctx.is_encoding) {
  11868. const int64_t n_kv = kv_self.n;
  11869. for (int h = 0; h < 1; ++h) {
  11870. for (int j = 0; j < n_tokens; ++j) {
  11871. for (int i = 0; i < n_kv; ++i) {
  11872. 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);
  11873. }
  11874. }
  11875. }
  11876. } else {
  11877. for (int h = 0; h < 1; ++h) {
  11878. for (int j = 0; j < n_tokens; ++j) {
  11879. for (int i = 0; i < n_tokens; ++i) {
  11880. 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);
  11881. }
  11882. }
  11883. }
  11884. }
  11885. }
  11886. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  11887. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  11888. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  11889. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  11890. }
  11891. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  11892. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  11893. const int64_t n_tokens = batch.n_tokens;
  11894. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  11895. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  11896. for (int h = 0; h < 1; ++h) {
  11897. for (int j = 0; j < n_tokens; ++j) {
  11898. for (int i = 0; i < n_output_enc; ++i) {
  11899. float f = -INFINITY;
  11900. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  11901. const llama_seq_id seq_id = batch.seq_id[j][s];
  11902. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  11903. f = 0.0f;
  11904. }
  11905. }
  11906. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  11907. }
  11908. }
  11909. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11910. for (int j = 0; j < n_output_enc; ++j) {
  11911. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  11912. }
  11913. }
  11914. }
  11915. }
  11916. }
  11917. // Make sure enough space is available for outputs.
  11918. // Returns max number of outputs for which space was reserved.
  11919. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  11920. const auto & cparams = lctx.cparams;
  11921. const auto & hparams = lctx.model.hparams;
  11922. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  11923. const auto n_batch = cparams.n_batch;
  11924. const auto n_vocab = hparams.n_vocab;
  11925. const auto n_embd = hparams.n_embd;
  11926. // TODO: use a per-batch flag for logits presence instead
  11927. const bool has_logits = cparams.causal_attn;
  11928. const bool has_embd = lctx.is_encoding || (cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE));
  11929. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  11930. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  11931. if (lctx.output_ids.empty()) {
  11932. // init, never resized afterwards
  11933. lctx.output_ids.resize(n_batch);
  11934. }
  11935. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  11936. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  11937. // alloc only when more than the current capacity is required
  11938. // TODO: also consider shrinking the buffer
  11939. if (!lctx.buf_output || prev_size < new_size) {
  11940. if (lctx.buf_output) {
  11941. #ifndef NDEBUG
  11942. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  11943. 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);
  11944. #endif
  11945. ggml_backend_buffer_free(lctx.buf_output);
  11946. lctx.buf_output = nullptr;
  11947. lctx.logits = nullptr;
  11948. lctx.embd = nullptr;
  11949. }
  11950. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  11951. if (lctx.buf_output == nullptr) {
  11952. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  11953. return 0;
  11954. }
  11955. }
  11956. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  11957. lctx.logits = has_logits ? output_base : nullptr;
  11958. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  11959. lctx.output_size = n_outputs_max;
  11960. lctx.logits_size = logits_size;
  11961. lctx.embd_size = embd_size;
  11962. // set all ids as invalid (negative)
  11963. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  11964. ggml_backend_buffer_clear(lctx.buf_output, 0);
  11965. lctx.n_outputs = 0;
  11966. return n_outputs_max;
  11967. }
  11968. static void llama_graph_compute(
  11969. llama_context & lctx,
  11970. ggml_cgraph * gf,
  11971. int n_threads) {
  11972. #ifdef GGML_USE_METAL
  11973. if (ggml_backend_is_metal(lctx.backend_metal)) {
  11974. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  11975. }
  11976. #endif
  11977. if (lctx.backend_cpu != nullptr) {
  11978. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  11979. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  11980. }
  11981. #ifdef GGML_USE_BLAS
  11982. if (lctx.backend_blas != nullptr) {
  11983. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  11984. }
  11985. #endif
  11986. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  11987. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  11988. }
  11989. // decode a batch of tokens by evaluating the transformer
  11990. //
  11991. // - lctx: llama context
  11992. // - batch: batch to evaluate
  11993. //
  11994. // return 0 on success
  11995. // return positive int on warning
  11996. // return negative int on error
  11997. //
  11998. static int llama_decode_internal(
  11999. llama_context & lctx,
  12000. llama_batch batch_all) { // TODO: rename back to batch
  12001. lctx.is_encoding = false;
  12002. const uint32_t n_tokens_all = batch_all.n_tokens;
  12003. if (n_tokens_all == 0) {
  12004. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  12005. return -1;
  12006. }
  12007. const auto & model = lctx.model;
  12008. const auto & hparams = model.hparams;
  12009. const auto & cparams = lctx.cparams;
  12010. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  12011. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  12012. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  12013. if (lctx.t_compute_start_us == 0) {
  12014. lctx.t_compute_start_us = ggml_time_us();
  12015. }
  12016. lctx.n_queued_tokens += n_tokens_all;
  12017. auto & kv_self = lctx.kv_self;
  12018. const int64_t n_embd = hparams.n_embd;
  12019. const int64_t n_vocab = hparams.n_vocab;
  12020. uint32_t n_outputs = 0;
  12021. uint32_t n_outputs_prev = 0;
  12022. const auto n_ubatch = cparams.n_ubatch;
  12023. // TODO: simplify or deprecate
  12024. std::vector<llama_pos> pos;
  12025. std::vector<int32_t> n_seq_id;
  12026. std::vector<llama_seq_id *> seq_id_arr;
  12027. std::vector<std::vector<llama_seq_id>> seq_id;
  12028. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  12029. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  12030. // count outputs
  12031. if (batch_all.logits && !embd_pooled) {
  12032. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12033. n_outputs += batch_all.logits[i] != 0;
  12034. }
  12035. } else if (lctx.logits_all || embd_pooled) {
  12036. n_outputs = n_tokens_all;
  12037. } else {
  12038. // keep last output only
  12039. n_outputs = 1;
  12040. }
  12041. // reserve output buffer
  12042. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  12043. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  12044. return -2;
  12045. };
  12046. // set output mappings
  12047. if (batch_all.logits) {
  12048. int32_t i_logits = 0;
  12049. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12050. if (batch_all.logits[i]) {
  12051. lctx.output_ids[i] = i_logits++;
  12052. }
  12053. }
  12054. } else {
  12055. for (uint32_t i = 0; i < n_outputs; ++i) {
  12056. lctx.output_ids[i] = i;
  12057. }
  12058. }
  12059. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  12060. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  12061. llama_batch u_batch = {
  12062. /* .n_tokens = */ (int32_t) n_tokens,
  12063. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  12064. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  12065. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  12066. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  12067. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  12068. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  12069. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  12070. /* .all_pos_1 = */ batch_all.all_pos_1,
  12071. /* .all_seq_id = */ batch_all.all_seq_id,
  12072. };
  12073. // count the outputs in this u_batch
  12074. {
  12075. int32_t n_outputs_new = 0;
  12076. if (u_batch.logits && !embd_pooled) {
  12077. for (uint32_t i = 0; i < n_tokens; i++) {
  12078. n_outputs_new += u_batch.logits[i] != 0;
  12079. }
  12080. } else if (n_outputs == n_tokens_all) {
  12081. n_outputs_new = n_tokens;
  12082. } else {
  12083. // keep last output only
  12084. if (cur_token + n_tokens >= n_tokens_all) {
  12085. n_outputs_new = 1;
  12086. }
  12087. }
  12088. // needs to happen before the graph is built
  12089. lctx.n_outputs = n_outputs_new;
  12090. }
  12091. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12092. GGML_ASSERT(n_threads > 0);
  12093. // helpers for smoother batch API transition
  12094. // after deprecating the llama_eval calls, these will be removed
  12095. if (u_batch.pos == nullptr) {
  12096. pos.resize(n_tokens);
  12097. for (uint32_t i = 0; i < n_tokens; i++) {
  12098. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  12099. }
  12100. u_batch.pos = pos.data();
  12101. }
  12102. if (u_batch.seq_id == nullptr) {
  12103. n_seq_id.resize(n_tokens);
  12104. seq_id.resize(n_tokens);
  12105. seq_id_arr.resize(n_tokens);
  12106. for (uint32_t i = 0; i < n_tokens; i++) {
  12107. n_seq_id[i] = 1;
  12108. seq_id[i].resize(1);
  12109. seq_id[i][0] = u_batch.all_seq_id;
  12110. seq_id_arr[i] = seq_id[i].data();
  12111. }
  12112. u_batch.n_seq_id = n_seq_id.data();
  12113. u_batch.seq_id = seq_id_arr.data();
  12114. }
  12115. // non-causal masks do not use the KV cache
  12116. if (hparams.causal_attn) {
  12117. llama_kv_cache_update(&lctx);
  12118. // if we have enough unused cells before the current head ->
  12119. // better to start searching from the beginning of the cache, hoping to fill it
  12120. if (kv_self.head > kv_self.used + 2*n_tokens) {
  12121. kv_self.head = 0;
  12122. }
  12123. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  12124. return 1;
  12125. }
  12126. if (!kv_self.recurrent) {
  12127. // a heuristic, to avoid attending the full cache if it is not yet utilized
  12128. // after enough generations, the benefit from this heuristic disappears
  12129. // if we start defragmenting the cache, the benefit from this will be more important
  12130. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  12131. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  12132. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  12133. }
  12134. }
  12135. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  12136. ggml_backend_sched_reset(lctx.sched);
  12137. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12138. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  12139. // the output is always the last tensor in the graph
  12140. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  12141. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  12142. if (lctx.n_outputs == 0) {
  12143. // no output
  12144. res = nullptr;
  12145. embd = nullptr;
  12146. }
  12147. if (cparams.embeddings) {
  12148. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  12149. embd = gf->nodes[i];
  12150. if (strcmp(embd->name, "result_embd_pooled") == 0) {
  12151. break;
  12152. }
  12153. }
  12154. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  12155. } else {
  12156. embd = nullptr; // do not extract embeddings when not needed
  12157. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  12158. }
  12159. if (!cparams.causal_attn) {
  12160. res = nullptr; // do not extract logits when not needed
  12161. }
  12162. // 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);
  12163. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12164. llama_set_inputs(lctx, u_batch);
  12165. llama_graph_compute(lctx, gf, n_threads);
  12166. // update the kv ring buffer
  12167. {
  12168. kv_self.head += n_tokens;
  12169. // Ensure kv cache head points to a valid index.
  12170. if (kv_self.head >= kv_self.size) {
  12171. kv_self.head = 0;
  12172. }
  12173. }
  12174. // plot the computation graph in dot format (for debugging purposes)
  12175. //if (n_past%100 == 0) {
  12176. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  12177. //}
  12178. // extract logits
  12179. if (res) {
  12180. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  12181. GGML_ASSERT(backend_res != nullptr);
  12182. GGML_ASSERT(lctx.logits != nullptr);
  12183. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  12184. const int32_t n_outputs_new = lctx.n_outputs;
  12185. if (n_outputs_new) {
  12186. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12187. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  12188. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  12189. }
  12190. }
  12191. // extract embeddings
  12192. if (embd) {
  12193. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12194. GGML_ASSERT(backend_embd != nullptr);
  12195. switch (cparams.pooling_type) {
  12196. case LLAMA_POOLING_TYPE_NONE:
  12197. {
  12198. // extract token embeddings
  12199. GGML_ASSERT(lctx.embd != nullptr);
  12200. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  12201. const int32_t n_outputs_new = lctx.n_outputs;
  12202. if (n_outputs_new) {
  12203. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12204. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  12205. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  12206. }
  12207. } break;
  12208. case LLAMA_POOLING_TYPE_MEAN:
  12209. case LLAMA_POOLING_TYPE_CLS:
  12210. case LLAMA_POOLING_TYPE_LAST:
  12211. {
  12212. // extract sequence embeddings
  12213. auto & embd_seq_out = lctx.embd_seq;
  12214. embd_seq_out.clear();
  12215. for (uint32_t i = 0; i < n_tokens; i++) {
  12216. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  12217. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  12218. continue;
  12219. }
  12220. embd_seq_out[seq_id].resize(n_embd);
  12221. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  12222. }
  12223. } break;
  12224. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  12225. {
  12226. GGML_ABORT("unknown pooling type");
  12227. }
  12228. }
  12229. }
  12230. n_outputs_prev += lctx.n_outputs;
  12231. }
  12232. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  12233. lctx.n_outputs = n_outputs;
  12234. // wait for the computation to finish (automatically done when obtaining the model output)
  12235. //llama_synchronize(&lctx);
  12236. // decide if we need to defrag the kv cache
  12237. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  12238. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  12239. // queue defragmentation for next llama_kv_cache_update
  12240. if (fragmentation > cparams.defrag_thold) {
  12241. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  12242. llama_kv_cache_defrag(kv_self);
  12243. }
  12244. }
  12245. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12246. // overlap with device computation.
  12247. ggml_backend_sched_reset(lctx.sched);
  12248. return 0;
  12249. }
  12250. // encode a batch of tokens by evaluating the encoder part of the transformer
  12251. //
  12252. // - lctx: llama context
  12253. // - batch: batch to evaluate
  12254. //
  12255. // return 0 on success
  12256. // return positive int on warning
  12257. // return negative int on error
  12258. //
  12259. static int llama_encode_internal(
  12260. llama_context & lctx,
  12261. llama_batch batch) {
  12262. lctx.is_encoding = true;
  12263. const uint32_t n_tokens = batch.n_tokens;
  12264. if (n_tokens == 0) {
  12265. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  12266. return -1;
  12267. }
  12268. const auto & model = lctx.model;
  12269. const auto & hparams = model.hparams;
  12270. const auto & cparams = lctx.cparams;
  12271. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  12272. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  12273. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  12274. if (lctx.t_compute_start_us == 0) {
  12275. lctx.t_compute_start_us = ggml_time_us();
  12276. }
  12277. lctx.n_queued_tokens += n_tokens;
  12278. const int64_t n_embd = hparams.n_embd;
  12279. // TODO: simplify or deprecate
  12280. std::vector<llama_pos> pos;
  12281. std::vector<int32_t> n_seq_id;
  12282. std::vector<llama_seq_id *> seq_id_arr;
  12283. std::vector<std::vector<llama_seq_id>> seq_id;
  12284. // reserve output buffer
  12285. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  12286. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  12287. return -2;
  12288. };
  12289. for (uint32_t i = 0; i < n_tokens; ++i) {
  12290. lctx.output_ids[i] = i;
  12291. }
  12292. lctx.inp_embd_enc = NULL;
  12293. lctx.n_outputs = n_tokens;
  12294. const int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12295. GGML_ASSERT(n_threads > 0);
  12296. // helpers for smoother batch API transition
  12297. // after deprecating the llama_eval calls, these will be removed
  12298. if (batch.pos == nullptr) {
  12299. pos.resize(n_tokens);
  12300. for (uint32_t i = 0; i < n_tokens; i++) {
  12301. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  12302. }
  12303. batch.pos = pos.data();
  12304. }
  12305. if (batch.seq_id == nullptr) {
  12306. n_seq_id.resize(n_tokens);
  12307. seq_id.resize(n_tokens);
  12308. seq_id_arr.resize(n_tokens);
  12309. for (uint32_t i = 0; i < n_tokens; i++) {
  12310. n_seq_id[i] = 1;
  12311. seq_id[i].resize(1);
  12312. seq_id[i][0] = batch.all_seq_id;
  12313. seq_id_arr[i] = seq_id[i].data();
  12314. }
  12315. batch.n_seq_id = n_seq_id.data();
  12316. batch.seq_id = seq_id_arr.data();
  12317. }
  12318. ggml_backend_sched_reset(lctx.sched);
  12319. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12320. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  12321. // the output embeddings after the final encoder normalization
  12322. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 1];
  12323. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  12324. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12325. llama_set_inputs(lctx, batch);
  12326. llama_graph_compute(lctx, gf, n_threads);
  12327. // extract embeddings
  12328. if (embd) {
  12329. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12330. GGML_ASSERT(backend_embd != nullptr);
  12331. // extract token embeddings
  12332. GGML_ASSERT(lctx.embd != nullptr);
  12333. lctx.embd_enc.resize(n_tokens*n_embd);
  12334. float * embd_out = lctx.embd_enc.data();
  12335. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  12336. // remember the sequence ids used during the encoding - needed for cross attention later
  12337. lctx.seq_ids_enc.resize(n_tokens);
  12338. for (uint32_t i = 0; i < n_tokens; i++) {
  12339. for (int s = 0; s < batch.n_seq_id[i]; s++) {
  12340. llama_seq_id seq_id = batch.seq_id[i][s];
  12341. lctx.seq_ids_enc[i].insert(seq_id);
  12342. }
  12343. }
  12344. }
  12345. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12346. // overlap with device computation.
  12347. ggml_backend_sched_reset(lctx.sched);
  12348. return 0;
  12349. }
  12350. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  12351. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  12352. auto & kv_self = lctx.kv_self;
  12353. const auto & hparams = lctx.model.hparams;
  12354. const uint32_t n_layer = hparams.n_layer;
  12355. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  12356. const uint32_t n_used = kv_self.used;
  12357. assert(n_used <= n_kv);
  12358. //const int64_t t_start = ggml_time_us();
  12359. // number of cells moved
  12360. uint32_t n_moves = 0;
  12361. // each move requires 6*n_layer tensors (see build_defrag)
  12362. // - source view, destination view, copy operation
  12363. // - x2 for keys and values
  12364. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  12365. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  12366. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  12367. // determine which KV cells to move where
  12368. //
  12369. // cell i moves to ids[i]
  12370. //
  12371. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  12372. //
  12373. std::vector<uint32_t> ids(n_kv, n_kv);
  12374. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  12375. const auto & cell0 = kv_self.cells[i0];
  12376. if (!cell0.is_empty()) {
  12377. ids[i0] = i0;
  12378. continue;
  12379. }
  12380. // found a hole - fill it with data from the end of the cache
  12381. uint32_t nh = 1;
  12382. // determine the size of the hole
  12383. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  12384. nh++;
  12385. }
  12386. uint32_t nf = 0;
  12387. uint32_t is = n_kv - 1;
  12388. // starting from the end, find nh non-empty cells
  12389. for (; is > i0; --is) {
  12390. const auto & cell1 = kv_self.cells[is];
  12391. if (cell1.is_empty() || ids[is] != n_kv) {
  12392. continue;
  12393. }
  12394. // non-empty cell which is not yet moved
  12395. nf++;
  12396. if (nf == nh) {
  12397. break;
  12398. }
  12399. }
  12400. // this can only happen if `n_used` is not accurate, which would be a bug
  12401. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  12402. nf = 0;
  12403. uint32_t i1 = is;
  12404. // are we moving a continuous block of memory?
  12405. bool cont = false;
  12406. // should we stop searching for the next move?
  12407. bool stop = false;
  12408. // go back and move the nf cells to the hole
  12409. for (; i1 < n_kv; ++i1) {
  12410. auto & cell1 = kv_self.cells[i1];
  12411. if (cell1.is_empty() || ids[i1] != n_kv) {
  12412. if (n_moves == max_moves) {
  12413. stop = true;
  12414. break;
  12415. }
  12416. cont = false;
  12417. continue;
  12418. }
  12419. // this cell goes to (i0 + nf)
  12420. ids[i1] = i0 + nf;
  12421. // move the cell meta data
  12422. kv_self.cells[i0 + nf] = cell1;
  12423. // clear the old cell and move the head there
  12424. cell1 = llama_kv_cell();
  12425. kv_self.head = n_used;
  12426. if (!cont) {
  12427. n_moves++;
  12428. cont = true;
  12429. }
  12430. nf++;
  12431. if (nf == nh) {
  12432. break;
  12433. }
  12434. }
  12435. if (stop || n_moves == max_moves) {
  12436. break;
  12437. }
  12438. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  12439. i0 += nh - 1;
  12440. }
  12441. if (n_moves == 0) {
  12442. return;
  12443. }
  12444. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  12445. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  12446. #if 0
  12447. // CPU defrag
  12448. //
  12449. // TODO: optimizations are possible:
  12450. // - multiple threads
  12451. // - avoid copying to the host memory when already there
  12452. //
  12453. // likely not worth the effort, as we have ggml_graph based defrag
  12454. //
  12455. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  12456. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  12457. const uint32_t kv_size = kv_self.size;
  12458. std::vector<uint8_t> buf_k;
  12459. std::vector<uint8_t> buf_v;
  12460. for (uint32_t il = 0; il < n_layer; ++il) {
  12461. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12462. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  12463. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12464. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  12465. buf_k.resize(k_size);
  12466. buf_v.resize(v_size);
  12467. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12468. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12469. // batch move [i, i+nm) to [id, id+nm)
  12470. // note: cells can move only to a lower index
  12471. for (uint32_t i = 0; i < n_kv; ++i) {
  12472. const uint32_t id = ids[i];
  12473. if (i == id || id == n_kv) {
  12474. continue;
  12475. }
  12476. uint32_t nm = 1;
  12477. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  12478. nm++;
  12479. }
  12480. // move keys
  12481. {
  12482. const int64_t os = i*k_size_row;
  12483. const int64_t od = id*k_size_row;
  12484. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  12485. }
  12486. // move values (note: they are transposed)
  12487. {
  12488. const int64_t os = i;
  12489. const int64_t od = id;
  12490. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  12491. 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);
  12492. }
  12493. }
  12494. i += nm - 1;
  12495. }
  12496. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12497. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12498. }
  12499. #else
  12500. // ggml_graph defrag
  12501. ggml_backend_sched_reset(lctx.sched);
  12502. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  12503. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12504. #endif
  12505. //const int64_t t_end = ggml_time_us();
  12506. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  12507. }
  12508. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  12509. bool need_reserve = false;
  12510. // apply K-shift if needed
  12511. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  12512. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  12513. GGML_ABORT("Deepseek2 does not support K-shift");
  12514. }
  12515. {
  12516. ggml_backend_sched_reset(lctx.sched);
  12517. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  12518. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12519. llama_set_k_shift(lctx);
  12520. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12521. need_reserve = true;
  12522. }
  12523. {
  12524. auto & kv_self = lctx.kv_self;
  12525. kv_self.has_shift = false;
  12526. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12527. kv_self.cells[i].delta = 0;
  12528. }
  12529. }
  12530. }
  12531. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  12532. {
  12533. ggml_backend_sched_reset(lctx.sched);
  12534. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  12535. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12536. llama_set_s_copy(lctx);
  12537. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12538. need_reserve = true;
  12539. }
  12540. {
  12541. auto & kv_self = lctx.kv_self;
  12542. kv_self.do_copy = false;
  12543. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12544. kv_self.cells[i].src = i;
  12545. }
  12546. }
  12547. }
  12548. // defragment the KV cache if needed
  12549. if (lctx.kv_self.do_defrag) {
  12550. llama_kv_cache_defrag_internal(lctx);
  12551. need_reserve = true;
  12552. lctx.kv_self.do_defrag = false;
  12553. }
  12554. // reserve a worst case graph again
  12555. if (need_reserve) {
  12556. // TODO: extract to a function
  12557. // build worst-case graph
  12558. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  12559. int n_past = lctx.cparams.n_ctx - n_tokens;
  12560. 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
  12561. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12562. // initialize scheduler with the worst-case graph
  12563. ggml_backend_sched_reset(lctx.sched);
  12564. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  12565. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12566. }
  12567. }
  12568. }
  12569. //
  12570. // quantization
  12571. //
  12572. struct quantize_state_internal {
  12573. const llama_model & model;
  12574. const llama_model_quantize_params * params;
  12575. int n_attention_wv = 0;
  12576. int n_ffn_down = 0;
  12577. int n_ffn_gate = 0;
  12578. int n_ffn_up = 0;
  12579. int i_attention_wv = 0;
  12580. int i_ffn_down = 0;
  12581. int i_ffn_gate = 0;
  12582. int i_ffn_up = 0;
  12583. int n_k_quantized = 0;
  12584. int n_fallback = 0;
  12585. bool has_imatrix = false;
  12586. // used to figure out if a model shares tok_embd with the output weight
  12587. bool has_output = false;
  12588. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  12589. : model(model)
  12590. , params(params)
  12591. {}
  12592. };
  12593. static void llama_tensor_dequantize_internal(
  12594. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  12595. const size_t nelements, const int nthread
  12596. ) {
  12597. if (output.size() < nelements) {
  12598. output.resize(nelements);
  12599. }
  12600. float * f32_output = (float *) output.data();
  12601. ggml_type_traits_t qtype;
  12602. if (ggml_is_quantized(tensor->type)) {
  12603. qtype = ggml_internal_get_type_traits(tensor->type);
  12604. if (qtype.to_float == NULL) {
  12605. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  12606. }
  12607. } else if (tensor->type != GGML_TYPE_F16 &&
  12608. tensor->type != GGML_TYPE_BF16) {
  12609. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  12610. }
  12611. if (nthread < 2) {
  12612. if (tensor->type == GGML_TYPE_F16) {
  12613. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  12614. } else if (tensor->type == GGML_TYPE_BF16) {
  12615. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  12616. } else if (ggml_is_quantized(tensor->type)) {
  12617. qtype.to_float(tensor->data, f32_output, nelements);
  12618. } else {
  12619. GGML_ABORT("fatal error"); // unreachable
  12620. }
  12621. return;
  12622. }
  12623. size_t block_size;
  12624. if (tensor->type == GGML_TYPE_F16 ||
  12625. tensor->type == GGML_TYPE_BF16) {
  12626. block_size = 1;
  12627. } else {
  12628. block_size = (size_t)ggml_blck_size(tensor->type);
  12629. }
  12630. size_t block_size_bytes = ggml_type_size(tensor->type);
  12631. GGML_ASSERT(nelements % block_size == 0);
  12632. size_t nblocks = nelements / block_size;
  12633. size_t blocks_per_thread = nblocks / nthread;
  12634. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  12635. size_t in_buff_offs = 0;
  12636. size_t out_buff_offs = 0;
  12637. for (int tnum = 0; tnum < nthread; tnum++) {
  12638. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  12639. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  12640. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  12641. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  12642. if (typ == GGML_TYPE_F16) {
  12643. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  12644. } else if (typ == GGML_TYPE_BF16) {
  12645. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  12646. } else {
  12647. qtype.to_float(inbuf, outbuf, nels);
  12648. }
  12649. };
  12650. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  12651. in_buff_offs += thr_block_bytes;
  12652. out_buff_offs += thr_elems;
  12653. }
  12654. for (auto & w : workers) { w.join(); }
  12655. workers.clear();
  12656. }
  12657. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  12658. const std::string name = ggml_get_name(tensor);
  12659. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12660. const llm_arch arch = qs.model.arch;
  12661. const auto tn = LLM_TN(arch);
  12662. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  12663. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  12664. };
  12665. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  12666. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  12667. if (n_expert > 1) {
  12668. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  12669. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  12670. // for getting the current layer as I initially thought, and we need to resort to parsing the
  12671. // tensor name.
  12672. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  12673. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  12674. }
  12675. if (i_layer < 0 || i_layer >= n_layer) {
  12676. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  12677. }
  12678. }
  12679. return std::make_pair(i_layer, n_layer);
  12680. };
  12681. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  12682. // with the quantization of the output tensor
  12683. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  12684. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  12685. new_type = qs.params->output_tensor_type;
  12686. } else {
  12687. int nx = tensor->ne[0];
  12688. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  12689. new_type = GGML_TYPE_Q8_0;
  12690. }
  12691. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12692. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  12693. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12694. new_type = GGML_TYPE_Q5_K;
  12695. }
  12696. else if (new_type != GGML_TYPE_Q8_0) {
  12697. new_type = GGML_TYPE_Q6_K;
  12698. }
  12699. }
  12700. } else if (name == "token_embd.weight") {
  12701. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  12702. new_type = qs.params->token_embedding_type;
  12703. } else {
  12704. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  12705. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12706. new_type = GGML_TYPE_Q2_K;
  12707. }
  12708. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  12709. new_type = GGML_TYPE_IQ3_S;
  12710. }
  12711. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12712. new_type = GGML_TYPE_IQ3_S;
  12713. }
  12714. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  12715. new_type == GGML_TYPE_Q4_0_8_8) {
  12716. new_type = GGML_TYPE_Q4_0;
  12717. }
  12718. }
  12719. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  12720. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12721. if (name.find("attn_v.weight") != std::string::npos) {
  12722. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  12723. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12724. ++qs.i_attention_wv;
  12725. }
  12726. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  12727. new_type = GGML_TYPE_Q4_K;
  12728. }
  12729. else if (name.find("ffn_down") != std::string::npos) {
  12730. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  12731. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12732. }
  12733. ++qs.i_ffn_down;
  12734. }
  12735. else if (name.find("attn_output.weight") != std::string::npos) {
  12736. if (qs.model.hparams.n_expert == 8) {
  12737. new_type = GGML_TYPE_Q5_K;
  12738. } else {
  12739. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  12740. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  12741. }
  12742. }
  12743. } else if (name.find("attn_v.weight") != std::string::npos) {
  12744. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  12745. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12746. }
  12747. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  12748. new_type = GGML_TYPE_Q4_K;
  12749. }
  12750. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12751. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  12752. }
  12753. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  12754. new_type = GGML_TYPE_Q4_K;
  12755. }
  12756. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12757. new_type = GGML_TYPE_Q4_K;
  12758. }
  12759. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12760. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12761. }
  12762. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  12763. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  12764. new_type = GGML_TYPE_Q5_K;
  12765. }
  12766. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  12767. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  12768. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  12769. if (qs.model.type == MODEL_70B) {
  12770. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  12771. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  12772. // nearly negligible increase in model size by quantizing this tensor with more bits:
  12773. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  12774. }
  12775. if (qs.model.hparams.n_expert == 8) {
  12776. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12777. // TODO: explore better strategies
  12778. new_type = GGML_TYPE_Q8_0;
  12779. }
  12780. ++qs.i_attention_wv;
  12781. } else if (name.find("attn_k.weight") != std::string::npos) {
  12782. if (qs.model.hparams.n_expert == 8) {
  12783. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12784. // TODO: explore better strategies
  12785. new_type = GGML_TYPE_Q8_0;
  12786. }
  12787. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12788. new_type = GGML_TYPE_IQ3_XXS;
  12789. }
  12790. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12791. new_type = GGML_TYPE_IQ2_S;
  12792. }
  12793. } else if (name.find("attn_q.weight") != std::string::npos) {
  12794. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12795. new_type = GGML_TYPE_IQ3_XXS;
  12796. }
  12797. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12798. new_type = GGML_TYPE_IQ2_S;
  12799. }
  12800. } else if (name.find("ffn_down") != std::string::npos) {
  12801. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  12802. int i_layer = info.first, n_layer = info.second;
  12803. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12804. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  12805. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  12806. }
  12807. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  12808. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12809. }
  12810. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12811. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  12812. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  12813. : GGML_TYPE_Q3_K;
  12814. }
  12815. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  12816. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  12817. new_type = GGML_TYPE_Q4_K;
  12818. }
  12819. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  12820. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  12821. }
  12822. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  12823. if (arch == LLM_ARCH_FALCON) {
  12824. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  12825. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12826. } else {
  12827. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12828. }
  12829. }
  12830. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  12831. new_type = GGML_TYPE_Q5_K;
  12832. }
  12833. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12834. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  12835. new_type = GGML_TYPE_Q5_K;
  12836. }
  12837. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  12838. && qs.has_imatrix && i_layer < n_layer/8) {
  12839. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  12840. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  12841. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  12842. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  12843. }
  12844. ++qs.i_ffn_down;
  12845. } else if (name.find("attn_output.weight") != std::string::npos) {
  12846. if (arch != LLM_ARCH_FALCON) {
  12847. if (qs.model.hparams.n_expert == 8) {
  12848. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12849. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  12850. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  12851. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  12852. new_type = GGML_TYPE_Q5_K;
  12853. }
  12854. } else {
  12855. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  12856. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  12857. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  12858. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  12859. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  12860. }
  12861. } else {
  12862. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  12863. }
  12864. }
  12865. else if (name.find("attn_qkv.weight") != std::string::npos) {
  12866. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12867. new_type = GGML_TYPE_Q4_K;
  12868. }
  12869. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  12870. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  12871. }
  12872. else if (name.find("ffn_gate") != std::string::npos) {
  12873. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  12874. int i_layer = info.first, n_layer = info.second;
  12875. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12876. new_type = GGML_TYPE_IQ3_XXS;
  12877. }
  12878. ++qs.i_ffn_gate;
  12879. }
  12880. else if (name.find("ffn_up") != std::string::npos) {
  12881. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  12882. int i_layer = info.first, n_layer = info.second;
  12883. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12884. new_type = GGML_TYPE_IQ3_XXS;
  12885. }
  12886. ++qs.i_ffn_up;
  12887. }
  12888. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12889. //}
  12890. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  12891. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  12892. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12893. //}
  12894. // This can be used to reduce the size of the Q5_K_S model.
  12895. // The associated PPL increase is fully in line with the size reduction
  12896. //else {
  12897. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  12898. //}
  12899. bool convert_incompatible_tensor = false;
  12900. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  12901. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  12902. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  12903. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  12904. new_type == GGML_TYPE_IQ1_M) {
  12905. int nx = tensor->ne[0];
  12906. int ny = tensor->ne[1];
  12907. if (nx % QK_K != 0) {
  12908. 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));
  12909. convert_incompatible_tensor = true;
  12910. } else {
  12911. ++qs.n_k_quantized;
  12912. }
  12913. }
  12914. if (convert_incompatible_tensor) {
  12915. switch (new_type) {
  12916. case GGML_TYPE_IQ2_XXS:
  12917. case GGML_TYPE_IQ2_XS:
  12918. case GGML_TYPE_IQ2_S:
  12919. case GGML_TYPE_IQ3_XXS:
  12920. case GGML_TYPE_IQ3_S:
  12921. case GGML_TYPE_IQ1_S:
  12922. case GGML_TYPE_IQ1_M:
  12923. case GGML_TYPE_Q2_K:
  12924. case GGML_TYPE_Q3_K:
  12925. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  12926. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  12927. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  12928. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  12929. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  12930. }
  12931. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  12932. ++qs.n_fallback;
  12933. }
  12934. return new_type;
  12935. }
  12936. 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) {
  12937. if (nthread < 2) {
  12938. // single-thread
  12939. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  12940. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  12941. throw std::runtime_error("quantized data validation failed");
  12942. }
  12943. return new_size;
  12944. }
  12945. std::mutex mutex;
  12946. int64_t counter = 0;
  12947. size_t new_size = 0;
  12948. bool valid = true;
  12949. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  12950. nrows, n_per_row, imatrix]() {
  12951. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  12952. size_t local_size = 0;
  12953. while (true) {
  12954. std::unique_lock<std::mutex> lock(mutex);
  12955. int64_t first_row = counter; counter += nrows_per_chunk;
  12956. if (first_row >= nrows) {
  12957. if (local_size > 0) {
  12958. new_size += local_size;
  12959. }
  12960. break;
  12961. }
  12962. lock.unlock();
  12963. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  12964. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  12965. local_size += this_size;
  12966. // validate the quantized data
  12967. const size_t row_size = ggml_row_size(new_type, n_per_row);
  12968. void * this_data = (char *) new_data + first_row * row_size;
  12969. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  12970. std::unique_lock<std::mutex> lock(mutex);
  12971. valid = false;
  12972. break;
  12973. }
  12974. }
  12975. };
  12976. for (int it = 0; it < nthread - 1; ++it) {
  12977. workers.emplace_back(compute);
  12978. }
  12979. compute();
  12980. for (auto & w : workers) { w.join(); }
  12981. workers.clear();
  12982. if (!valid) {
  12983. throw std::runtime_error("quantized data validation failed");
  12984. }
  12985. return new_size;
  12986. }
  12987. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  12988. ggml_type default_type;
  12989. llama_ftype ftype = params->ftype;
  12990. switch (params->ftype) {
  12991. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  12992. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  12993. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  12994. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  12995. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  12996. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  12997. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  12998. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  12999. // K-quants
  13000. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  13001. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  13002. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  13003. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  13004. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  13005. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  13006. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  13007. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  13008. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  13009. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  13010. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  13011. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  13012. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  13013. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  13014. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  13015. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  13016. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  13017. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  13018. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  13019. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  13020. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  13021. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  13022. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  13023. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  13024. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  13025. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  13026. }
  13027. int nthread = params->nthread;
  13028. if (nthread <= 0) {
  13029. nthread = std::thread::hardware_concurrency();
  13030. }
  13031. // mmap consistently increases speed Linux, and also increases speed on Windows with
  13032. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  13033. #if defined(__linux__) || defined(_WIN32)
  13034. constexpr bool use_mmap = true;
  13035. #else
  13036. constexpr bool use_mmap = false;
  13037. #endif
  13038. llama_model_kv_override * kv_overrides = nullptr;
  13039. if (params->kv_overrides) {
  13040. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  13041. kv_overrides = v->data();
  13042. }
  13043. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  13044. ml.init_mappings(false); // no prefetching
  13045. llama_model model;
  13046. llm_load_arch(ml, model);
  13047. llm_load_hparams(ml, model);
  13048. struct quantize_state_internal qs(model, params);
  13049. if (params->only_copy) {
  13050. ftype = model.ftype;
  13051. }
  13052. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  13053. if (params->imatrix) {
  13054. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  13055. if (imatrix_data) {
  13056. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  13057. qs.has_imatrix = true;
  13058. // check imatrix for nans or infs
  13059. for (const auto & kv : *imatrix_data) {
  13060. for (float f : kv.second) {
  13061. if (!std::isfinite(f)) {
  13062. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  13063. }
  13064. }
  13065. }
  13066. }
  13067. }
  13068. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  13069. struct gguf_context * ctx_out = gguf_init_empty();
  13070. // copy the KV pairs from the input file
  13071. gguf_set_kv (ctx_out, ml.meta);
  13072. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  13073. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  13074. // Remove split metadata
  13075. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  13076. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  13077. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  13078. if (params->kv_overrides) {
  13079. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  13080. for (auto & o : overrides) {
  13081. if (o.key[0] == 0) break;
  13082. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  13083. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  13084. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  13085. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  13086. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  13087. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  13088. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  13089. gguf_set_val_str(ctx_out, o.key, o.val_str);
  13090. } else {
  13091. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  13092. }
  13093. }
  13094. }
  13095. for (int i = 0; i < ml.n_tensors; ++i) {
  13096. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  13097. const std::string name = ggml_get_name(meta);
  13098. // TODO: avoid hardcoded tensor names - use the TN_* constants
  13099. if (name.find("attn_v.weight") != std::string::npos ||
  13100. name.find("attn_qkv.weight") != std::string::npos) {
  13101. ++qs.n_attention_wv;
  13102. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  13103. qs.has_output = true;
  13104. }
  13105. }
  13106. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  13107. // sanity checks
  13108. //
  13109. // - qs.n_attention_wv == 0 for Mamba models
  13110. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  13111. // - qs.n_attention_wv == 3 * model.hparams.n_layer for Encoder-Decoder models
  13112. //
  13113. 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");
  13114. size_t total_size_org = 0;
  13115. size_t total_size_new = 0;
  13116. std::vector<std::thread> workers;
  13117. workers.reserve(nthread);
  13118. int idx = 0;
  13119. std::vector<no_init<uint8_t>> read_data;
  13120. std::vector<no_init<uint8_t>> work;
  13121. std::vector<no_init<float>> f32_conv_buf;
  13122. uint16_t n_split = 1;
  13123. // Assume split index is continuous
  13124. if (params->keep_split) {
  13125. for (int i = 0; i < ml.n_tensors; ++i) {
  13126. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  13127. }
  13128. }
  13129. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  13130. ctx_outs[0] = ctx_out;
  13131. // populate the original tensors so we get an initial meta data
  13132. for (int i = 0; i < ml.n_tensors; ++i) {
  13133. auto weight = ml.get_weight(i);
  13134. uint16_t i_split = params->keep_split ? weight->idx : 0;
  13135. struct ggml_tensor * tensor = weight->tensor;
  13136. if (ctx_outs[i_split] == NULL) {
  13137. ctx_outs[i_split] = gguf_init_empty();
  13138. }
  13139. gguf_add_tensor(ctx_outs[i_split], tensor);
  13140. }
  13141. // Set split info if needed
  13142. if (n_split > 1) {
  13143. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  13144. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  13145. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  13146. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  13147. }
  13148. }
  13149. int cur_split = -1;
  13150. std::ofstream fout;
  13151. auto close_ofstream = [&]() {
  13152. // Write metadata and close file handler
  13153. if (fout.is_open()) {
  13154. fout.seekp(0);
  13155. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  13156. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  13157. fout.write((const char *) data.data(), data.size());
  13158. fout.close();
  13159. }
  13160. };
  13161. auto new_ofstream = [&](int index) {
  13162. cur_split = index;
  13163. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  13164. std::string fname = fname_out;
  13165. if (params->keep_split) {
  13166. char split_path[PATH_MAX] = {0};
  13167. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  13168. fname = std::string(split_path);
  13169. }
  13170. fout = std::ofstream(fname, std::ios::binary);
  13171. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  13172. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  13173. // placeholder for the meta data
  13174. ::zeros(fout, meta_size);
  13175. };
  13176. const auto tn = LLM_TN(model.arch);
  13177. new_ofstream(0);
  13178. for (int i = 0; i < ml.n_tensors; ++i) {
  13179. auto weight = ml.get_weight(i);
  13180. struct ggml_tensor * tensor = weight->tensor;
  13181. if (weight->idx != cur_split && params->keep_split) {
  13182. close_ofstream();
  13183. new_ofstream(weight->idx);
  13184. }
  13185. const std::string name = ggml_get_name(tensor);
  13186. if (!ml.use_mmap) {
  13187. if (read_data.size() < ggml_nbytes(tensor)) {
  13188. read_data.resize(ggml_nbytes(tensor));
  13189. }
  13190. tensor->data = read_data.data();
  13191. }
  13192. ml.load_data_for(tensor);
  13193. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  13194. ++idx, ml.n_tensors,
  13195. ggml_get_name(tensor),
  13196. llama_format_tensor_shape(tensor).c_str(),
  13197. ggml_type_name(tensor->type));
  13198. // This used to be a regex, but <regex> has an extreme cost to compile times.
  13199. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  13200. // quantize only 2D and 3D tensors (experts)
  13201. quantize &= (ggml_n_dims(tensor) >= 2);
  13202. // do not quantize norm tensors
  13203. quantize &= name.find("_norm.weight") == std::string::npos;
  13204. quantize &= params->quantize_output_tensor || name != "output.weight";
  13205. quantize &= !params->only_copy;
  13206. // do not quantize expert gating tensors
  13207. // NOTE: can't use LLM_TN here because the layer number is not known
  13208. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  13209. // do not quantize positional embeddings and token types (BERT)
  13210. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  13211. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  13212. // do not quantize Mamba's small yet 2D weights
  13213. // NOTE: can't use LLM_TN here because the layer number is not known
  13214. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  13215. quantize &= name.find("ssm_x.weight") == std::string::npos;
  13216. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  13217. // do not quantize relative position bias (T5)
  13218. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  13219. enum ggml_type new_type;
  13220. void * new_data;
  13221. size_t new_size;
  13222. if (quantize) {
  13223. new_type = default_type;
  13224. // get more optimal quantization type based on the tensor shape, layer, etc.
  13225. if (!params->pure && ggml_is_quantized(default_type)) {
  13226. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  13227. }
  13228. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  13229. new_type = params->token_embedding_type;
  13230. }
  13231. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  13232. new_type = params->output_tensor_type;
  13233. }
  13234. // If we've decided to quantize to the same type the tensor is already
  13235. // in then there's nothing to do.
  13236. quantize = tensor->type != new_type;
  13237. }
  13238. if (!quantize) {
  13239. new_type = tensor->type;
  13240. new_data = tensor->data;
  13241. new_size = ggml_nbytes(tensor);
  13242. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  13243. } else {
  13244. const int64_t nelements = ggml_nelements(tensor);
  13245. const float * imatrix = nullptr;
  13246. if (imatrix_data) {
  13247. auto it = imatrix_data->find(tensor->name);
  13248. if (it == imatrix_data->end()) {
  13249. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  13250. } else {
  13251. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  13252. imatrix = it->second.data();
  13253. } else {
  13254. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  13255. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  13256. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  13257. // this is a significant error and it may be good idea to abort the process if this happens,
  13258. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  13259. // tok_embd should be ignored in this case, since it always causes this warning
  13260. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  13261. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  13262. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  13263. }
  13264. }
  13265. }
  13266. }
  13267. if ((new_type == GGML_TYPE_IQ2_XXS ||
  13268. new_type == GGML_TYPE_IQ2_XS ||
  13269. new_type == GGML_TYPE_IQ2_S ||
  13270. new_type == GGML_TYPE_IQ1_S ||
  13271. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  13272. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  13273. LLAMA_LOG_ERROR("\n\n============================================================\n");
  13274. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  13275. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  13276. LLAMA_LOG_ERROR("============================================================\n\n");
  13277. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  13278. }
  13279. float * f32_data;
  13280. if (tensor->type == GGML_TYPE_F32) {
  13281. f32_data = (float *) tensor->data;
  13282. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  13283. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  13284. } else {
  13285. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  13286. f32_data = (float *) f32_conv_buf.data();
  13287. }
  13288. int chunk_size_multiplier = 1;
  13289. 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) {
  13290. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  13291. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  13292. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  13293. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  13294. }
  13295. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  13296. fflush(stdout);
  13297. if (work.size() < (size_t)nelements * 4) {
  13298. work.resize(nelements * 4); // upper bound on size
  13299. }
  13300. new_data = work.data();
  13301. const int64_t n_per_row = tensor->ne[0];
  13302. const int64_t nrows = tensor->ne[1];
  13303. static const int64_t min_chunk_size = 32 * 512;
  13304. 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)) *
  13305. chunk_size_multiplier;
  13306. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  13307. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  13308. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  13309. // quantize each expert separately since they have different importance matrices
  13310. new_size = 0;
  13311. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  13312. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  13313. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  13314. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  13315. 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);
  13316. }
  13317. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  13318. }
  13319. total_size_org += ggml_nbytes(tensor);
  13320. total_size_new += new_size;
  13321. // update the gguf meta data as we go
  13322. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  13323. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  13324. // write tensor data + padding
  13325. fout.write((const char *) new_data, new_size);
  13326. zeros(fout, GGML_PAD(new_size, align) - new_size);
  13327. }
  13328. close_ofstream();
  13329. for (auto & c:ctx_outs) {
  13330. gguf_free(c);
  13331. }
  13332. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  13333. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  13334. if (qs.n_fallback > 0) {
  13335. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  13336. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  13337. }
  13338. }
  13339. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  13340. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  13341. ggml_context * ctx = nullptr;
  13342. struct gguf_init_params meta_gguf_params = {
  13343. /* .no_alloc = */ true,
  13344. /* .ctx = */ &ctx,
  13345. };
  13346. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  13347. if (!ctx_gguf) {
  13348. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  13349. }
  13350. // check metadata
  13351. {
  13352. auto get_kv_str = [&](const std::string & key) -> std::string {
  13353. int id = gguf_find_key(ctx_gguf, key.c_str());
  13354. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  13355. };
  13356. auto get_kv_f32 = [&](const std::string & key) -> float {
  13357. int id = gguf_find_key(ctx_gguf, key.c_str());
  13358. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  13359. };
  13360. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  13361. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  13362. if (general_type != "adapter") {
  13363. gguf_free(ctx_gguf);
  13364. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  13365. }
  13366. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  13367. auto general_arch = llm_arch_from_string(general_arch_str);
  13368. if (general_arch != model->arch) {
  13369. gguf_free(ctx_gguf);
  13370. throw std::runtime_error("model arch and LoRA arch mismatch");
  13371. }
  13372. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  13373. if (adapter_type != "lora") {
  13374. gguf_free(ctx_gguf);
  13375. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  13376. }
  13377. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  13378. }
  13379. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  13380. // contexts for each buffer type
  13381. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  13382. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  13383. auto it = ctx_map.find(buft);
  13384. if (it == ctx_map.end()) {
  13385. // add a new context
  13386. struct ggml_init_params params = {
  13387. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  13388. /*.mem_buffer =*/ NULL,
  13389. /*.no_alloc =*/ true,
  13390. };
  13391. ggml_context * buft_ctx = ggml_init(params);
  13392. ctx_map[buft] = buft_ctx;
  13393. return buft_ctx;
  13394. };
  13395. return it->second;
  13396. };
  13397. // bundle lora_a and lora_b into pairs
  13398. std::map<std::string, llama_lora_weight> ab_map;
  13399. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  13400. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  13401. };
  13402. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  13403. std::string name(cur->name);
  13404. if (str_endswith(name, ".lora_a")) {
  13405. replace_all(name, ".lora_a", "");
  13406. if (ab_map.find(name) == ab_map.end()) {
  13407. ab_map[name] = llama_lora_weight(cur, nullptr);
  13408. } else {
  13409. ab_map[name].a = cur;
  13410. }
  13411. } else if (str_endswith(name, ".lora_b")) {
  13412. replace_all(name, ".lora_b", "");
  13413. if (ab_map.find(name) == ab_map.end()) {
  13414. ab_map[name] = llama_lora_weight(nullptr, cur);
  13415. } else {
  13416. ab_map[name].b = cur;
  13417. }
  13418. } else {
  13419. gguf_free(ctx_gguf);
  13420. ggml_free(ctx);
  13421. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  13422. }
  13423. }
  13424. // add tensors
  13425. for (auto & it : ab_map) {
  13426. const std::string & name = it.first;
  13427. llama_lora_weight & w = it.second;
  13428. if (!w.a || !w.b) {
  13429. gguf_free(ctx_gguf);
  13430. ggml_free(ctx);
  13431. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  13432. }
  13433. // device buft and device ctx
  13434. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  13435. if (!model_tensor) {
  13436. gguf_free(ctx_gguf);
  13437. ggml_free(ctx);
  13438. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  13439. }
  13440. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  13441. // validate tensor shape
  13442. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  13443. gguf_free(ctx_gguf);
  13444. ggml_free(ctx);
  13445. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  13446. }
  13447. if (w.a->ne[1] != w.b->ne[0]) {
  13448. gguf_free(ctx_gguf);
  13449. ggml_free(ctx);
  13450. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  13451. }
  13452. // save tensor to adapter
  13453. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  13454. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  13455. ggml_set_name(tensor_a, w.a->name);
  13456. ggml_set_name(tensor_b, w.b->name);
  13457. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  13458. }
  13459. // allocate tensors / buffers and zero
  13460. {
  13461. adapter.ctxs.reserve(ctx_map.size());
  13462. adapter.bufs.reserve(ctx_map.size());
  13463. for (auto it : ctx_map) {
  13464. ggml_backend_buffer_type_t buft = it.first;
  13465. ggml_context * ctx_dev = it.second;
  13466. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  13467. if (!buf) {
  13468. gguf_free(ctx_gguf);
  13469. ggml_free(ctx);
  13470. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  13471. }
  13472. 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);
  13473. adapter.ctxs.push_back(ctx_dev);
  13474. adapter.bufs.push_back(buf);
  13475. }
  13476. }
  13477. // set tensor data
  13478. {
  13479. llama_file gguf_file(path_lora, "rb");
  13480. std::vector<uint8_t> read_buf;
  13481. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  13482. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  13483. size_t size = ggml_nbytes(orig);
  13484. read_buf.resize(size);
  13485. gguf_file.seek(offs, SEEK_SET);
  13486. gguf_file.read_raw(read_buf.data(), size);
  13487. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  13488. };
  13489. for (auto & it : adapter.ab_map) {
  13490. auto orig = ab_map[it.first];
  13491. auto dev = it.second;
  13492. set_tensor(orig.a, dev.a);
  13493. set_tensor(orig.b, dev.b);
  13494. }
  13495. }
  13496. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  13497. // free ctx for reading gguf
  13498. gguf_free(ctx_gguf);
  13499. ggml_free(ctx);
  13500. }
  13501. int32_t llama_lora_adapter_set(
  13502. struct llama_context * ctx,
  13503. struct llama_lora_adapter * adapter,
  13504. float scale) {
  13505. if (ctx->cparams.flash_attn) {
  13506. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  13507. return -1;
  13508. }
  13509. ctx->lora_adapters[adapter] = scale;
  13510. return 0;
  13511. }
  13512. int32_t llama_lora_adapter_remove(
  13513. struct llama_context * ctx,
  13514. struct llama_lora_adapter * adapter) {
  13515. auto pos = ctx->lora_adapters.find(adapter);
  13516. if (pos != ctx->lora_adapters.end()) {
  13517. ctx->lora_adapters.erase(pos);
  13518. return 0;
  13519. }
  13520. return -1;
  13521. }
  13522. void llama_lora_adapter_clear(struct llama_context * ctx) {
  13523. ctx->lora_adapters.clear();
  13524. }
  13525. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  13526. delete adapter;
  13527. }
  13528. //
  13529. // interface implementation
  13530. //
  13531. struct llama_model_params llama_model_default_params() {
  13532. struct llama_model_params result = {
  13533. /*.n_gpu_layers =*/ 0,
  13534. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  13535. /*.main_gpu =*/ 0,
  13536. /*.tensor_split =*/ nullptr,
  13537. /*.rpc_servers =*/ nullptr,
  13538. /*.progress_callback =*/ nullptr,
  13539. /*.progress_callback_user_data =*/ nullptr,
  13540. /*.kv_overrides =*/ nullptr,
  13541. /*.vocab_only =*/ false,
  13542. /*.use_mmap =*/ true,
  13543. /*.use_mlock =*/ false,
  13544. /*.check_tensors =*/ false,
  13545. };
  13546. #ifdef GGML_USE_METAL
  13547. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  13548. result.n_gpu_layers = 999;
  13549. #endif
  13550. return result;
  13551. }
  13552. struct llama_context_params llama_context_default_params() {
  13553. struct llama_context_params result = {
  13554. /*.seed =*/ LLAMA_DEFAULT_SEED,
  13555. /*.n_ctx =*/ 512,
  13556. /*.n_batch =*/ 2048,
  13557. /*.n_ubatch =*/ 512,
  13558. /*.n_seq_max =*/ 1,
  13559. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  13560. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  13561. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  13562. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  13563. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  13564. /*.rope_freq_base =*/ 0.0f,
  13565. /*.rope_freq_scale =*/ 0.0f,
  13566. /*.yarn_ext_factor =*/ -1.0f,
  13567. /*.yarn_attn_factor =*/ 1.0f,
  13568. /*.yarn_beta_fast =*/ 32.0f,
  13569. /*.yarn_beta_slow =*/ 1.0f,
  13570. /*.yarn_orig_ctx =*/ 0,
  13571. /*.defrag_thold =*/ -1.0f,
  13572. /*.cb_eval =*/ nullptr,
  13573. /*.cb_eval_user_data =*/ nullptr,
  13574. /*.type_k =*/ GGML_TYPE_F16,
  13575. /*.type_v =*/ GGML_TYPE_F16,
  13576. /*.logits_all =*/ false,
  13577. /*.embeddings =*/ false,
  13578. /*.offload_kqv =*/ true,
  13579. /*.flash_attn =*/ false,
  13580. /*.abort_callback =*/ nullptr,
  13581. /*.abort_callback_data =*/ nullptr,
  13582. };
  13583. return result;
  13584. }
  13585. struct llama_model_quantize_params llama_model_quantize_default_params() {
  13586. struct llama_model_quantize_params result = {
  13587. /*.nthread =*/ 0,
  13588. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  13589. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  13590. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  13591. /*.allow_requantize =*/ false,
  13592. /*.quantize_output_tensor =*/ true,
  13593. /*.only_copy =*/ false,
  13594. /*.pure =*/ false,
  13595. /*.keep_split =*/ false,
  13596. /*.imatrix =*/ nullptr,
  13597. /*.kv_overrides =*/ nullptr,
  13598. };
  13599. return result;
  13600. }
  13601. size_t llama_max_devices(void) {
  13602. #if defined(GGML_USE_RPC)
  13603. return GGML_RPC_MAX_SERVERS;
  13604. #elif defined(GGML_USE_METAL)
  13605. return 1;
  13606. #elif defined(GGML_USE_CUDA)
  13607. return GGML_CUDA_MAX_DEVICES;
  13608. #elif defined(GGML_USE_SYCL)
  13609. return GGML_SYCL_MAX_DEVICES;
  13610. #elif defined(GGML_USE_VULKAN)
  13611. return GGML_VK_MAX_DEVICES;
  13612. #elif defined(GGML_USE_CANN)
  13613. return GGML_CANN_MAX_DEVICES;
  13614. #else
  13615. return 1;
  13616. #endif
  13617. }
  13618. bool llama_supports_mmap(void) {
  13619. return llama_mmap::SUPPORTED;
  13620. }
  13621. bool llama_supports_mlock(void) {
  13622. return llama_mlock::SUPPORTED;
  13623. }
  13624. bool llama_supports_gpu_offload(void) {
  13625. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  13626. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  13627. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  13628. return true;
  13629. #else
  13630. return false;
  13631. #endif
  13632. }
  13633. void llama_backend_init(void) {
  13634. ggml_time_init();
  13635. // needed to initialize f16 tables
  13636. {
  13637. struct ggml_init_params params = { 0, NULL, false };
  13638. struct ggml_context * ctx = ggml_init(params);
  13639. ggml_free(ctx);
  13640. }
  13641. }
  13642. void llama_numa_init(enum ggml_numa_strategy numa) {
  13643. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  13644. ggml_numa_init(numa);
  13645. }
  13646. }
  13647. void llama_backend_free(void) {
  13648. ggml_quantize_free();
  13649. }
  13650. int64_t llama_time_us(void) {
  13651. return ggml_time_us();
  13652. }
  13653. struct llama_model * llama_load_model_from_file(
  13654. const char * path_model,
  13655. struct llama_model_params params) {
  13656. ggml_time_init();
  13657. llama_model * model = new llama_model;
  13658. unsigned cur_percentage = 0;
  13659. if (params.progress_callback == NULL) {
  13660. params.progress_callback_user_data = &cur_percentage;
  13661. params.progress_callback = [](float progress, void * ctx) {
  13662. unsigned * cur_percentage_p = (unsigned *) ctx;
  13663. unsigned percentage = (unsigned) (100 * progress);
  13664. while (percentage > *cur_percentage_p) {
  13665. *cur_percentage_p = percentage;
  13666. LLAMA_LOG_INFO(".");
  13667. if (percentage >= 100) {
  13668. LLAMA_LOG_INFO("\n");
  13669. }
  13670. }
  13671. return true;
  13672. };
  13673. }
  13674. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  13675. // split the servers set them into model->rpc_servers
  13676. std::string servers(params.rpc_servers);
  13677. size_t pos = 0;
  13678. while ((pos = servers.find(",")) != std::string::npos) {
  13679. std::string server = servers.substr(0, pos);
  13680. model->rpc_servers.push_back(server);
  13681. servers.erase(0, pos + 1);
  13682. }
  13683. model->rpc_servers.push_back(servers);
  13684. }
  13685. int status = llama_model_load(path_model, *model, params);
  13686. GGML_ASSERT(status <= 0);
  13687. if (status < 0) {
  13688. if (status == -1) {
  13689. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  13690. } else if (status == -2) {
  13691. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  13692. }
  13693. delete model;
  13694. return nullptr;
  13695. }
  13696. return model;
  13697. }
  13698. void llama_free_model(struct llama_model * model) {
  13699. delete model;
  13700. }
  13701. struct llama_context * llama_new_context_with_model(
  13702. struct llama_model * model,
  13703. struct llama_context_params params) {
  13704. if (!model) {
  13705. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  13706. return nullptr;
  13707. }
  13708. if (params.n_batch == 0 && params.n_ubatch == 0) {
  13709. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  13710. return nullptr;
  13711. }
  13712. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  13713. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  13714. return nullptr;
  13715. }
  13716. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  13717. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  13718. params.flash_attn = false;
  13719. }
  13720. if (params.flash_attn && model->hparams.attn_soft_cap) {
  13721. LLAMA_LOG_WARN("%s: flash_attn is not compatible with attn_soft_cap - forcing off\n", __func__);
  13722. params.flash_attn = false;
  13723. }
  13724. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  13725. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  13726. params.flash_attn = false;
  13727. }
  13728. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  13729. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  13730. return nullptr;
  13731. }
  13732. llama_context * ctx = new llama_context(*model);
  13733. const auto & hparams = model->hparams;
  13734. auto & cparams = ctx->cparams;
  13735. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  13736. cparams.n_threads = params.n_threads;
  13737. cparams.n_threads_batch = params.n_threads_batch;
  13738. cparams.yarn_ext_factor = params.yarn_ext_factor;
  13739. cparams.yarn_attn_factor = params.yarn_attn_factor;
  13740. cparams.yarn_beta_fast = params.yarn_beta_fast;
  13741. cparams.yarn_beta_slow = params.yarn_beta_slow;
  13742. cparams.defrag_thold = params.defrag_thold;
  13743. cparams.embeddings = params.embeddings;
  13744. cparams.offload_kqv = params.offload_kqv;
  13745. cparams.flash_attn = params.flash_attn;
  13746. cparams.pooling_type = params.pooling_type;
  13747. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  13748. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  13749. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  13750. // this is necessary due to kv_self.n being padded later during inference
  13751. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  13752. // with causal attention, the batch size is limited by the context size
  13753. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  13754. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  13755. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  13756. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  13757. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  13758. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  13759. cparams.n_batch = GGML_KQ_MASK_PAD;
  13760. }
  13761. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  13762. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  13763. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  13764. hparams.n_ctx_train;
  13765. cparams.cb_eval = params.cb_eval;
  13766. cparams.cb_eval_user_data = params.cb_eval_user_data;
  13767. auto rope_scaling_type = params.rope_scaling_type;
  13768. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  13769. rope_scaling_type = hparams.rope_scaling_type_train;
  13770. }
  13771. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  13772. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  13773. }
  13774. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  13775. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  13776. }
  13777. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  13778. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13779. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13780. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  13781. } else {
  13782. cparams.pooling_type = hparams.pooling_type;
  13783. }
  13784. }
  13785. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  13786. cparams.causal_attn = hparams.causal_attn;
  13787. } else {
  13788. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  13789. }
  13790. if (params.seed == LLAMA_DEFAULT_SEED) {
  13791. params.seed = time(NULL);
  13792. }
  13793. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  13794. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  13795. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  13796. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  13797. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  13798. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  13799. ctx->abort_callback = params.abort_callback;
  13800. ctx->abort_callback_data = params.abort_callback_data;
  13801. ctx->sampling.rng = std::mt19937(params.seed);
  13802. ctx->logits_all = params.logits_all;
  13803. uint32_t kv_size = cparams.n_ctx;
  13804. ggml_type type_k = params.type_k;
  13805. ggml_type type_v = params.type_v;
  13806. // Mamba only needs a constant number of KV cache cells per sequence
  13807. if (model->arch == LLM_ARCH_MAMBA) {
  13808. // Mamba needs at least as many KV cells as there are sequences kept at any time
  13809. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  13810. // it's probably best to keep as much precision as possible for the states
  13811. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  13812. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  13813. }
  13814. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  13815. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  13816. if (!hparams.vocab_only) {
  13817. // initialize backends
  13818. #if defined(GGML_USE_METAL)
  13819. if (model->n_gpu_layers > 0) {
  13820. ctx->backend_metal = ggml_backend_metal_init();
  13821. if (ctx->backend_metal == nullptr) {
  13822. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  13823. llama_free(ctx);
  13824. return nullptr;
  13825. }
  13826. ctx->backends.push_back(ctx->backend_metal);
  13827. }
  13828. #elif defined(GGML_USE_CUDA)
  13829. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13830. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13831. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  13832. if (backend == nullptr) {
  13833. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  13834. llama_free(ctx);
  13835. return nullptr;
  13836. }
  13837. ctx->backends.push_back(backend);
  13838. } else {
  13839. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13840. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  13841. ggml_backend_t backend = ggml_backend_cuda_init(device);
  13842. if (backend == nullptr) {
  13843. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  13844. llama_free(ctx);
  13845. return nullptr;
  13846. }
  13847. ctx->backends.push_back(backend);
  13848. }
  13849. }
  13850. #elif defined(GGML_USE_VULKAN)
  13851. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13852. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  13853. llama_free(ctx);
  13854. return nullptr;
  13855. }
  13856. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  13857. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  13858. if (backend == nullptr) {
  13859. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  13860. llama_free(ctx);
  13861. return nullptr;
  13862. }
  13863. ctx->backends.push_back(backend);
  13864. } else {
  13865. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  13866. ggml_backend_t backend = ggml_backend_vk_init(device);
  13867. if (backend == nullptr) {
  13868. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  13869. llama_free(ctx);
  13870. return nullptr;
  13871. }
  13872. ctx->backends.push_back(backend);
  13873. }
  13874. }
  13875. #elif defined(GGML_USE_SYCL)
  13876. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13877. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13878. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  13879. if (backend == nullptr) {
  13880. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  13881. llama_free(ctx);
  13882. return nullptr;
  13883. }
  13884. ctx->backends.push_back(backend);
  13885. } else {
  13886. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  13887. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  13888. ggml_backend_t backend = ggml_backend_sycl_init(i);
  13889. if (backend == nullptr) {
  13890. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  13891. llama_free(ctx);
  13892. return nullptr;
  13893. }
  13894. ctx->backends.push_back(backend);
  13895. }
  13896. }
  13897. #elif defined(GGML_USE_KOMPUTE)
  13898. if (model->n_gpu_layers > 0) {
  13899. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  13900. if (backend == nullptr) {
  13901. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  13902. llama_free(ctx);
  13903. return nullptr;
  13904. }
  13905. ctx->backends.push_back(backend);
  13906. }
  13907. #elif defined(GGML_USE_CANN)
  13908. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13909. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  13910. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13911. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  13912. if (backend == nullptr) {
  13913. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  13914. llama_free(ctx);
  13915. return nullptr;
  13916. }
  13917. ctx->backends.push_back(backend);
  13918. } else {
  13919. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13920. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  13921. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  13922. ggml_backend_t backend = ggml_backend_cann_init(device);
  13923. if (backend == nullptr) {
  13924. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  13925. llama_free(ctx);
  13926. return nullptr;
  13927. }
  13928. ctx->backends.push_back(backend);
  13929. }
  13930. }
  13931. #endif
  13932. #ifdef GGML_USE_BLAS
  13933. ctx->backend_blas = ggml_backend_blas_init();
  13934. if (ctx->backend_blas == nullptr) {
  13935. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  13936. } else {
  13937. ctx->backends.push_back(ctx->backend_blas);
  13938. }
  13939. #endif
  13940. #if defined(GGML_USE_RPC)
  13941. if (model->n_gpu_layers > 0) {
  13942. for (const auto & endpoint : model->rpc_servers) {
  13943. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  13944. if (backend == nullptr) {
  13945. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  13946. llama_free(ctx);
  13947. return nullptr;
  13948. }
  13949. ctx->backends.push_back(backend);
  13950. }
  13951. }
  13952. #endif
  13953. ctx->backend_cpu = ggml_backend_cpu_init();
  13954. if (ctx->backend_cpu == nullptr) {
  13955. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  13956. llama_free(ctx);
  13957. return nullptr;
  13958. }
  13959. ctx->backends.push_back(ctx->backend_cpu);
  13960. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  13961. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  13962. llama_free(ctx);
  13963. return nullptr;
  13964. }
  13965. {
  13966. size_t memory_size_k = 0;
  13967. size_t memory_size_v = 0;
  13968. for (auto & k : ctx->kv_self.k_l) {
  13969. memory_size_k += ggml_nbytes(k);
  13970. }
  13971. for (auto & v : ctx->kv_self.v_l) {
  13972. memory_size_v += ggml_nbytes(v);
  13973. }
  13974. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  13975. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  13976. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  13977. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  13978. }
  13979. // graph outputs buffer
  13980. {
  13981. // resized during inference when a batch uses more outputs
  13982. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  13983. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  13984. llama_free(ctx);
  13985. return nullptr;
  13986. }
  13987. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  13988. ggml_backend_buffer_name(ctx->buf_output),
  13989. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  13990. }
  13991. // scheduler and compute buffers
  13992. {
  13993. // buffer types used for the compute buffer of each backend
  13994. std::vector<ggml_backend_buffer_type_t> backend_buft;
  13995. for (auto * backend : ctx->backends) {
  13996. if (ggml_backend_is_cpu(backend)) {
  13997. // use host buffers for the CPU backend compute buffer
  13998. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  13999. } else {
  14000. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  14001. }
  14002. }
  14003. const size_t max_nodes = llama_model_max_nodes(*model);
  14004. // buffer used to store the computation graph and the tensor meta data
  14005. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  14006. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  14007. bool pipeline_parallel =
  14008. llama_get_device_count(*model) > 1 &&
  14009. model->n_gpu_layers > (int)model->hparams.n_layer &&
  14010. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  14011. params.offload_kqv;
  14012. #ifndef GGML_USE_CUDA
  14013. // pipeline parallelism requires support for async compute and events
  14014. // currently this is only implemented in the CUDA backend
  14015. pipeline_parallel = false;
  14016. #endif
  14017. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  14018. if (pipeline_parallel) {
  14019. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  14020. }
  14021. // build worst-case graph
  14022. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  14023. int n_past = cparams.n_ctx - n_tokens;
  14024. 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
  14025. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  14026. // initialize scheduler with the worst-case graph
  14027. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  14028. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  14029. llama_free(ctx);
  14030. return nullptr;
  14031. }
  14032. for (size_t i = 0; i < ctx->backends.size(); i++) {
  14033. ggml_backend_t backend = ctx->backends[i];
  14034. ggml_backend_buffer_type_t buft = backend_buft[i];
  14035. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  14036. if (size > 1) {
  14037. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  14038. ggml_backend_buft_name(buft),
  14039. size / 1024.0 / 1024.0);
  14040. }
  14041. }
  14042. // note: the number of splits during measure is higher than during inference due to the kv shift
  14043. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  14044. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  14045. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  14046. }
  14047. }
  14048. return ctx;
  14049. }
  14050. void llama_free(struct llama_context * ctx) {
  14051. delete ctx;
  14052. }
  14053. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  14054. return &ctx->model;
  14055. }
  14056. const struct llama_vocab * llama_get_vocab(const struct llama_context * ctx) {
  14057. return &ctx->model.vocab;
  14058. }
  14059. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  14060. return ctx->cparams.n_ctx;
  14061. }
  14062. uint32_t llama_n_batch(const struct llama_context * ctx) {
  14063. return ctx->cparams.n_batch;
  14064. }
  14065. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  14066. return ctx->cparams.n_ubatch;
  14067. }
  14068. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  14069. return ctx->kv_self.size;
  14070. }
  14071. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  14072. return model->vocab.type;
  14073. }
  14074. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  14075. switch (model->arch) {
  14076. // these models do not use RoPE
  14077. case LLM_ARCH_GPT2:
  14078. case LLM_ARCH_GPTJ:
  14079. case LLM_ARCH_MPT:
  14080. case LLM_ARCH_REFACT:
  14081. case LLM_ARCH_BLOOM:
  14082. case LLM_ARCH_MAMBA:
  14083. case LLM_ARCH_JINA_BERT_V2:
  14084. case LLM_ARCH_T5:
  14085. case LLM_ARCH_JAIS:
  14086. return LLAMA_ROPE_TYPE_NONE;
  14087. // use what we call a normal RoPE, operating on pairs of consecutive head values
  14088. case LLM_ARCH_LLAMA:
  14089. case LLM_ARCH_BAICHUAN:
  14090. case LLM_ARCH_STARCODER:
  14091. case LLM_ARCH_PLAMO:
  14092. case LLM_ARCH_ORION:
  14093. case LLM_ARCH_INTERNLM2:
  14094. case LLM_ARCH_MINICPM:
  14095. case LLM_ARCH_XVERSE:
  14096. case LLM_ARCH_COMMAND_R:
  14097. case LLM_ARCH_OLMO:
  14098. case LLM_ARCH_ARCTIC:
  14099. case LLM_ARCH_DEEPSEEK2:
  14100. case LLM_ARCH_CHATGLM:
  14101. return LLAMA_ROPE_TYPE_NORM;
  14102. // the pairs of head values are offset by n_rot/2
  14103. case LLM_ARCH_FALCON:
  14104. case LLM_ARCH_GROK:
  14105. case LLM_ARCH_DBRX:
  14106. case LLM_ARCH_BERT:
  14107. case LLM_ARCH_NOMIC_BERT:
  14108. case LLM_ARCH_STABLELM:
  14109. case LLM_ARCH_BITNET:
  14110. case LLM_ARCH_QWEN:
  14111. case LLM_ARCH_QWEN2:
  14112. case LLM_ARCH_QWEN2MOE:
  14113. case LLM_ARCH_PHI2:
  14114. case LLM_ARCH_PHI3:
  14115. case LLM_ARCH_GEMMA:
  14116. case LLM_ARCH_GEMMA2:
  14117. case LLM_ARCH_STARCODER2:
  14118. case LLM_ARCH_OPENELM:
  14119. case LLM_ARCH_GPTNEOX:
  14120. case LLM_ARCH_CODESHELL:
  14121. return LLAMA_ROPE_TYPE_NEOX;
  14122. // all model arches should be listed explicitly here
  14123. case LLM_ARCH_UNKNOWN:
  14124. GGML_ABORT("unknown architecture");
  14125. }
  14126. return LLAMA_ROPE_TYPE_NONE;
  14127. }
  14128. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  14129. return ctx->cparams.pooling_type;
  14130. }
  14131. int32_t llama_n_vocab(const struct llama_model * model) {
  14132. return model->hparams.n_vocab;
  14133. }
  14134. int32_t llama_n_ctx_train(const struct llama_model * model) {
  14135. return model->hparams.n_ctx_train;
  14136. }
  14137. int32_t llama_n_embd(const struct llama_model * model) {
  14138. return model->hparams.n_embd;
  14139. }
  14140. int32_t llama_n_layer(const struct llama_model * model) {
  14141. return model->hparams.n_layer;
  14142. }
  14143. float llama_rope_freq_scale_train(const struct llama_model * model) {
  14144. return model->hparams.rope_freq_scale_train;
  14145. }
  14146. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  14147. const auto & it = model->gguf_kv.find(key);
  14148. if (it == model->gguf_kv.end()) {
  14149. if (buf_size > 0) {
  14150. buf[0] = '\0';
  14151. }
  14152. return -1;
  14153. }
  14154. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14155. }
  14156. int32_t llama_model_meta_count(const struct llama_model * model) {
  14157. return (int)model->gguf_kv.size();
  14158. }
  14159. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  14160. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14161. if (buf_size > 0) {
  14162. buf[0] = '\0';
  14163. }
  14164. return -1;
  14165. }
  14166. auto it = model->gguf_kv.begin();
  14167. std::advance(it, i);
  14168. return snprintf(buf, buf_size, "%s", it->first.c_str());
  14169. }
  14170. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  14171. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14172. if (buf_size > 0) {
  14173. buf[0] = '\0';
  14174. }
  14175. return -1;
  14176. }
  14177. auto it = model->gguf_kv.begin();
  14178. std::advance(it, i);
  14179. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14180. }
  14181. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  14182. return snprintf(buf, buf_size, "%s %s %s",
  14183. llama_model_arch_name(model->arch),
  14184. llama_model_type_name(model->type),
  14185. llama_model_ftype_name(model->ftype).c_str());
  14186. }
  14187. uint64_t llama_model_size(const struct llama_model * model) {
  14188. uint64_t size = 0;
  14189. for (const auto & it : model->tensors_by_name) {
  14190. size += ggml_nbytes(it.second);
  14191. }
  14192. return size;
  14193. }
  14194. uint64_t llama_model_n_params(const struct llama_model * model) {
  14195. uint64_t nparams = 0;
  14196. for (const auto & it : model->tensors_by_name) {
  14197. nparams += ggml_nelements(it.second);
  14198. }
  14199. return nparams;
  14200. }
  14201. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  14202. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  14203. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  14204. return it.first == name;
  14205. });
  14206. if (it == model->tensors_by_name.end()) {
  14207. return nullptr;
  14208. }
  14209. return it->second;
  14210. }
  14211. bool llama_model_has_encoder(const struct llama_model * model) {
  14212. switch (model->arch) {
  14213. case LLM_ARCH_T5: return true;
  14214. default: return false;
  14215. }
  14216. }
  14217. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  14218. return model->hparams.dec_start_token_id;
  14219. }
  14220. uint32_t llama_model_quantize(
  14221. const char * fname_inp,
  14222. const char * fname_out,
  14223. const llama_model_quantize_params * params) {
  14224. try {
  14225. llama_model_quantize_internal(fname_inp, fname_out, params);
  14226. return 0;
  14227. } catch (const std::exception & err) {
  14228. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  14229. return 1;
  14230. }
  14231. }
  14232. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  14233. try {
  14234. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  14235. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  14236. return adapter;
  14237. } catch (const std::exception & err) {
  14238. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  14239. return nullptr;
  14240. }
  14241. }
  14242. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  14243. GGML_ASSERT(cvec.tensors.empty());
  14244. GGML_ASSERT(cvec.ctxs.empty());
  14245. GGML_ASSERT(cvec.bufs.empty());
  14246. // count layer buffer types
  14247. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  14248. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  14249. buft_layer_count[model.buft_layer[i].buft]++;
  14250. }
  14251. // allocate contexts
  14252. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  14253. for (auto & it : buft_layer_count) {
  14254. int n_layers = it.second;
  14255. struct ggml_init_params params = {
  14256. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  14257. /*.mem_buffer =*/ NULL,
  14258. /*.no_alloc =*/ true,
  14259. };
  14260. ggml_context * ctx = ggml_init(params);
  14261. if (!ctx) {
  14262. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  14263. return 1;
  14264. }
  14265. ctx_map[it.first] = ctx;
  14266. }
  14267. // make tensors
  14268. cvec.tensors.reserve(model.hparams.n_layer);
  14269. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  14270. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14271. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  14272. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  14273. cvec.tensors.push_back(tensor);
  14274. }
  14275. // allocate tensors / buffers and zero
  14276. cvec.ctxs.reserve(ctx_map.size());
  14277. cvec.bufs.reserve(ctx_map.size());
  14278. for (auto it : ctx_map) {
  14279. ggml_backend_buffer_type_t buft = it.first;
  14280. ggml_context * ctx = it.second;
  14281. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  14282. if (!buf) {
  14283. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  14284. return false;
  14285. }
  14286. ggml_backend_buffer_clear(buf, 0);
  14287. cvec.ctxs.push_back(ctx);
  14288. cvec.bufs.push_back(buf);
  14289. }
  14290. return true;
  14291. }
  14292. 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) {
  14293. const llama_model & model = lctx->model;
  14294. llama_control_vector & cvec = lctx->cvec;
  14295. if (data == nullptr) {
  14296. // disable the current control vector (but leave allocated for later)
  14297. cvec.layer_start = -1;
  14298. cvec.layer_end = -1;
  14299. return 0;
  14300. }
  14301. if (n_embd != (int) model.hparams.n_embd) {
  14302. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  14303. return 1;
  14304. }
  14305. if (cvec.tensors.empty()) {
  14306. if (!llama_control_vector_init(cvec, model)) {
  14307. return 1;
  14308. }
  14309. }
  14310. cvec.layer_start = il_start;
  14311. cvec.layer_end = il_end;
  14312. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14313. assert(cvec.tensors[il] != nullptr);
  14314. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  14315. if (off + n_embd <= len) {
  14316. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  14317. }
  14318. }
  14319. return 0;
  14320. }
  14321. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  14322. struct llama_kv_cache_view result = {
  14323. /*.n_cells = */ 0,
  14324. /*.n_seq_max = */ n_seq_max,
  14325. /*.token_count = */ 0,
  14326. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  14327. /*.max_contiguous = */ 0,
  14328. /*.max_contiguous_idx = */ -1,
  14329. /*.cells = */ nullptr,
  14330. /*.cells_sequences = */ nullptr,
  14331. };
  14332. return result;
  14333. }
  14334. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  14335. if (view->cells != nullptr) {
  14336. free(view->cells);
  14337. view->cells = nullptr;
  14338. }
  14339. if (view->cells_sequences != nullptr) {
  14340. free(view->cells_sequences);
  14341. view->cells_sequences = nullptr;
  14342. }
  14343. }
  14344. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  14345. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  14346. view->n_cells = int32_t(ctx->kv_self.size);
  14347. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  14348. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  14349. view->cells = (struct llama_kv_cache_view_cell *)p;
  14350. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  14351. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  14352. view->cells_sequences = (llama_seq_id *)p;
  14353. }
  14354. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  14355. llama_kv_cache_view_cell * c_curr = view->cells;
  14356. llama_seq_id * cs_curr = view->cells_sequences;
  14357. int32_t used_cells = 0;
  14358. int32_t token_count = 0;
  14359. int32_t curr_contig_idx = -1;
  14360. uint32_t max_contig = 0;
  14361. int32_t max_contig_idx = -1;
  14362. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  14363. const size_t curr_size = kv_cells[i].seq_id.size();
  14364. token_count += curr_size;
  14365. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  14366. if (curr_size > 0) {
  14367. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  14368. max_contig = i - curr_contig_idx;
  14369. max_contig_idx = curr_contig_idx;
  14370. }
  14371. curr_contig_idx = -1;
  14372. } else if (curr_contig_idx < 0) {
  14373. curr_contig_idx = i;
  14374. }
  14375. int seq_idx = 0;
  14376. for (const llama_seq_id it : kv_cells[i].seq_id) {
  14377. if (seq_idx >= view->n_seq_max) {
  14378. break;
  14379. }
  14380. cs_curr[seq_idx] = it;
  14381. seq_idx++;
  14382. }
  14383. if (seq_idx != 0) {
  14384. used_cells++;
  14385. }
  14386. for (; seq_idx < view->n_seq_max; seq_idx++) {
  14387. cs_curr[seq_idx] = -1;
  14388. }
  14389. }
  14390. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  14391. max_contig_idx = curr_contig_idx;
  14392. max_contig = kv_cells.size() - curr_contig_idx;
  14393. }
  14394. view->max_contiguous = max_contig;
  14395. view->max_contiguous_idx = max_contig_idx;
  14396. view->token_count = token_count;
  14397. view->used_cells = used_cells;
  14398. if (uint32_t(used_cells) != ctx->kv_self.used) {
  14399. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  14400. __func__, ctx->kv_self.used, used_cells);
  14401. }
  14402. }
  14403. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  14404. int result = 0;
  14405. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  14406. result += ctx->kv_self.cells[i].seq_id.size();
  14407. }
  14408. return result;
  14409. }
  14410. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  14411. return ctx->kv_self.used;
  14412. }
  14413. void llama_kv_cache_clear(struct llama_context * ctx) {
  14414. llama_kv_cache_clear(ctx->kv_self);
  14415. }
  14416. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  14417. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  14418. }
  14419. 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) {
  14420. if (seq_id_src == seq_id_dst) {
  14421. return;
  14422. }
  14423. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  14424. }
  14425. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  14426. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  14427. }
  14428. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  14429. if (delta == 0) {
  14430. return;
  14431. }
  14432. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  14433. }
  14434. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  14435. if (d == 1) {
  14436. return;
  14437. }
  14438. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  14439. }
  14440. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  14441. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  14442. }
  14443. void llama_kv_cache_defrag(struct llama_context * ctx) {
  14444. llama_kv_cache_defrag(ctx->kv_self);
  14445. }
  14446. void llama_kv_cache_update(struct llama_context * ctx) {
  14447. llama_kv_cache_update_internal(*ctx);
  14448. }
  14449. // deprecated
  14450. size_t llama_get_state_size(struct llama_context * ctx) {
  14451. return llama_state_get_size(ctx);
  14452. }
  14453. // deprecated
  14454. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  14455. return llama_state_get_data(ctx, dst, -1);
  14456. }
  14457. // deprecated
  14458. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  14459. return llama_state_set_data(ctx, src, -1);
  14460. }
  14461. // deprecated
  14462. 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) {
  14463. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14464. }
  14465. // deprecated
  14466. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14467. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  14468. }
  14469. // TODO: replace all non-fatal assertions with returned errors or exceptions
  14470. struct llama_data_write {
  14471. virtual void write(const void * src, size_t size) = 0;
  14472. virtual size_t get_size_written() = 0;
  14473. virtual ~llama_data_write() = default;
  14474. void write_string(const std::string & str) {
  14475. uint32_t str_size = str.size();
  14476. write(&str_size, sizeof(str_size));
  14477. write(str.data(), str_size);
  14478. }
  14479. void write_model_info(const struct llama_context * ctx) {
  14480. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14481. write_string(arch_str);
  14482. // TODO: add more model-specific info which should prevent loading the session file if not identical
  14483. }
  14484. void write_rng(const std::mt19937 & rng) {
  14485. std::ostringstream rng_ss;
  14486. rng_ss << rng;
  14487. const std::string & rng_str = rng_ss.str();
  14488. write_string(rng_str);
  14489. }
  14490. void write_output_ids(const struct llama_context * ctx) {
  14491. const uint32_t n_outputs = ctx->n_outputs;
  14492. std::vector<int32_t> output_pos;
  14493. const size_t n_batch = ctx->cparams.n_batch;
  14494. const auto & output_ids = ctx->output_ids;
  14495. GGML_ASSERT(n_outputs <= ctx->output_size);
  14496. output_pos.resize(n_outputs);
  14497. // build a more compact representation of the output ids
  14498. for (size_t i = 0; i < n_batch; ++i) {
  14499. // map an output id to a position in the batch
  14500. int32_t pos = output_ids[i];
  14501. if (pos >= 0) {
  14502. GGML_ASSERT((uint32_t) pos < n_outputs);
  14503. output_pos[pos] = i;
  14504. }
  14505. }
  14506. write(&n_outputs, sizeof(n_outputs));
  14507. if (n_outputs) {
  14508. write(output_pos.data(), n_outputs * sizeof(int32_t));
  14509. }
  14510. }
  14511. void write_logits(const struct llama_context * ctx) {
  14512. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  14513. write(&logits_size, sizeof(logits_size));
  14514. if (logits_size) {
  14515. write(ctx->logits, logits_size * sizeof(float));
  14516. }
  14517. }
  14518. void write_embeddings(const struct llama_context * ctx) {
  14519. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  14520. write(&embeddings_size, sizeof(embeddings_size));
  14521. if (embeddings_size) {
  14522. write(ctx->embd, embeddings_size * sizeof(float));
  14523. }
  14524. }
  14525. 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) {
  14526. for (const auto & range : cell_ranges) {
  14527. for (uint32_t i = range.first; i < range.second; ++i) {
  14528. const auto & cell = kv_self.cells[i];
  14529. const llama_pos pos = cell.pos;
  14530. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  14531. write(&pos, sizeof(pos));
  14532. write(&n_seq_id, sizeof(n_seq_id));
  14533. if (n_seq_id) {
  14534. for (auto seq_id : cell.seq_id) {
  14535. write(&seq_id, sizeof(seq_id));
  14536. }
  14537. }
  14538. }
  14539. }
  14540. }
  14541. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  14542. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14543. const struct llama_hparams & hparams = ctx->model.hparams;
  14544. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  14545. const uint32_t n_layer = hparams.n_layer;
  14546. write(&v_trans, sizeof(v_trans));
  14547. write(&n_layer, sizeof(n_layer));
  14548. std::vector<uint8_t> tmp_buf;
  14549. // Iterate and write all the keys first, each row is a cell
  14550. // Get whole range at a time
  14551. for (uint32_t il = 0; il < n_layer; ++il) {
  14552. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14553. // Write key type
  14554. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14555. write(&k_type_i, sizeof(k_type_i));
  14556. // Write row size of key
  14557. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14558. write(&k_size_row, sizeof(k_size_row));
  14559. // Read each range of cells of k_size length each into tmp_buf and write out
  14560. for (const auto & range : cell_ranges) {
  14561. const size_t range_size = range.second - range.first;
  14562. tmp_buf.resize(range_size * k_size_row);
  14563. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  14564. write(tmp_buf.data(), tmp_buf.size());
  14565. }
  14566. }
  14567. if (!kv_self.v_trans) {
  14568. for (uint32_t il = 0; il < n_layer; ++il) {
  14569. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14570. // Write value type
  14571. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14572. write(&v_type_i, sizeof(v_type_i));
  14573. // Write row size of value
  14574. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14575. write(&v_size_row, sizeof(v_size_row));
  14576. // Read each range of cells of v_size length each into tmp_buf and write out
  14577. for (const auto & range : cell_ranges) {
  14578. const size_t range_size = range.second - range.first;
  14579. tmp_buf.resize(range_size * v_size_row);
  14580. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), range.first * v_size_row, range_size * v_size_row);
  14581. write(tmp_buf.data(), tmp_buf.size());
  14582. }
  14583. }
  14584. } else {
  14585. // When v is transposed, we also need the element size and get the element ranges from each row
  14586. const uint32_t kv_size = kv_self.size;
  14587. for (uint32_t il = 0; il < n_layer; ++il) {
  14588. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14589. // Write value type
  14590. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14591. write(&v_type_i, sizeof(v_type_i));
  14592. // Write element size
  14593. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14594. write(&v_size_el, sizeof(v_size_el));
  14595. // Write GQA embedding size
  14596. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  14597. // For each row, we get the element values of each cell
  14598. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14599. // Read each range of cells of v_size_el length each into tmp_buf and write out
  14600. for (const auto & range : cell_ranges) {
  14601. const size_t range_size = range.second - range.first;
  14602. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  14603. tmp_buf.resize(range_size * v_size_el);
  14604. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  14605. write(tmp_buf.data(), tmp_buf.size());
  14606. }
  14607. }
  14608. }
  14609. }
  14610. }
  14611. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14612. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14613. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  14614. uint32_t cell_count = 0;
  14615. // Count the number of cells with the specified seq_id
  14616. // Find all the ranges of cells with this seq id (or all, when -1)
  14617. uint32_t cell_range_begin = kv_self.size;
  14618. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14619. const auto & cell = kv_self.cells[i];
  14620. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  14621. ++cell_count;
  14622. if (cell_range_begin == kv_self.size) {
  14623. cell_range_begin = i;
  14624. }
  14625. } else {
  14626. if (cell_range_begin != kv_self.size) {
  14627. cell_ranges.emplace_back(cell_range_begin, i);
  14628. cell_range_begin = kv_self.size;
  14629. }
  14630. }
  14631. }
  14632. if (cell_range_begin != kv_self.size) {
  14633. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  14634. }
  14635. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  14636. uint32_t cell_count_check = 0;
  14637. for (const auto & range : cell_ranges) {
  14638. cell_count_check += range.second - range.first;
  14639. }
  14640. GGML_ASSERT(cell_count == cell_count_check);
  14641. write(&cell_count, sizeof(cell_count));
  14642. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  14643. write_kv_cache_data(ctx, cell_ranges);
  14644. }
  14645. };
  14646. struct llama_data_read {
  14647. virtual const uint8_t * read(size_t size) = 0;
  14648. virtual void read_to(void * dst, size_t size) = 0;
  14649. virtual size_t get_size_read() = 0;
  14650. virtual ~llama_data_read() = default;
  14651. void read_string(std::string & str) {
  14652. uint32_t str_size;
  14653. read_to(&str_size, sizeof(str_size));
  14654. str.assign((const char *) read(str_size), str_size);
  14655. }
  14656. // validate model information
  14657. void read_model_info(const struct llama_context * ctx) {
  14658. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14659. std::string arch_str;
  14660. read_string(arch_str);
  14661. if (cur_arch_str != arch_str) {
  14662. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  14663. }
  14664. // TODO: add more info which needs to be identical but which is not verified otherwise
  14665. }
  14666. void read_rng(std::mt19937 & rng) {
  14667. std::string rng_str;
  14668. read_string(rng_str);
  14669. std::istringstream rng_ss(rng_str);
  14670. rng_ss >> rng;
  14671. if (rng_ss.fail()) {
  14672. throw std::runtime_error("failed to load RNG state");
  14673. }
  14674. }
  14675. void read_output_ids(struct llama_context * ctx) {
  14676. std::vector<int32_t> output_pos;
  14677. uint32_t n_outputs;
  14678. read_to(&n_outputs, sizeof(n_outputs));
  14679. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  14680. throw std::runtime_error("could not reserve outputs");
  14681. }
  14682. if (n_outputs) {
  14683. output_pos.resize(n_outputs);
  14684. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  14685. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  14686. int32_t id = output_pos[i];
  14687. if ((uint32_t) id >= ctx->cparams.n_batch) {
  14688. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  14689. }
  14690. ctx->output_ids[id] = i;
  14691. }
  14692. ctx->n_outputs = n_outputs;
  14693. }
  14694. }
  14695. void read_logits(struct llama_context * ctx) {
  14696. uint64_t logits_size;
  14697. read_to(&logits_size, sizeof(logits_size));
  14698. if (ctx->logits_size < logits_size) {
  14699. throw std::runtime_error("logits buffer too small");
  14700. }
  14701. if (logits_size) {
  14702. read_to(ctx->logits, logits_size * sizeof(float));
  14703. }
  14704. }
  14705. void read_embeddings(struct llama_context * ctx) {
  14706. uint64_t embeddings_size;
  14707. read_to(&embeddings_size, sizeof(embeddings_size));
  14708. if (ctx->embd_size < embeddings_size) {
  14709. throw std::runtime_error("embeddings buffer too small");
  14710. }
  14711. if (embeddings_size) {
  14712. read_to(ctx->embd, embeddings_size * sizeof(float));
  14713. }
  14714. }
  14715. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  14716. struct llama_kv_cache & kv_self = ctx->kv_self;
  14717. if (dest_seq_id != -1) {
  14718. // single sequence
  14719. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14720. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  14721. batch.n_tokens = cell_count;
  14722. for (uint32_t i = 0; i < cell_count; ++i) {
  14723. llama_pos pos;
  14724. uint32_t n_seq_id;
  14725. read_to(&pos, sizeof(pos));
  14726. read_to(&n_seq_id, sizeof(n_seq_id));
  14727. if (n_seq_id != 0) {
  14728. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  14729. return false;
  14730. }
  14731. batch.pos[i] = pos;
  14732. batch.n_seq_id[i] = 1;
  14733. batch.seq_id[i][0] = dest_seq_id;
  14734. }
  14735. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  14736. llama_batch_free(batch);
  14737. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  14738. return false;
  14739. }
  14740. // 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)
  14741. // Assume that this is one contiguous block of cells
  14742. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  14743. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  14744. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  14745. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  14746. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  14747. // Cleanup
  14748. llama_batch_free(batch);
  14749. } else {
  14750. // whole KV cache restore
  14751. if (cell_count > kv_self.size) {
  14752. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  14753. return false;
  14754. }
  14755. llama_kv_cache_clear(kv_self);
  14756. for (uint32_t i = 0; i < cell_count; ++i) {
  14757. llama_kv_cell & cell = kv_self.cells[i];
  14758. llama_pos pos;
  14759. uint32_t n_seq_id;
  14760. read_to(&pos, sizeof(pos));
  14761. read_to(&n_seq_id, sizeof(n_seq_id));
  14762. cell.pos = pos;
  14763. for (uint32_t j = 0; j < n_seq_id; ++j) {
  14764. llama_seq_id seq_id;
  14765. read_to(&seq_id, sizeof(seq_id));
  14766. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  14767. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  14768. return false;
  14769. }
  14770. cell.seq_id.insert(seq_id);
  14771. }
  14772. }
  14773. kv_self.head = 0;
  14774. kv_self.used = cell_count;
  14775. }
  14776. return true;
  14777. }
  14778. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  14779. const struct llama_hparams & hparams = ctx->model.hparams;
  14780. struct llama_kv_cache & kv_self = ctx->kv_self;
  14781. uint32_t v_trans;
  14782. uint32_t n_layer;
  14783. read_to(&v_trans, sizeof(v_trans));
  14784. read_to(&n_layer, sizeof(n_layer));
  14785. if (n_layer != hparams.n_layer) {
  14786. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  14787. return false;
  14788. }
  14789. if (cell_count > kv_self.size) {
  14790. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  14791. return false;
  14792. }
  14793. if (kv_self.v_trans != (bool) v_trans) {
  14794. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  14795. return false;
  14796. }
  14797. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  14798. for (uint32_t il = 0; il < n_layer; ++il) {
  14799. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14800. // Read type of key
  14801. int32_t k_type_i_ref;
  14802. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  14803. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14804. if (k_type_i != k_type_i_ref) {
  14805. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  14806. return false;
  14807. }
  14808. // Read row size of key
  14809. uint64_t k_size_row_ref;
  14810. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  14811. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14812. if (k_size_row != k_size_row_ref) {
  14813. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  14814. return false;
  14815. }
  14816. if (cell_count) {
  14817. // Read and set the keys for the whole cell range
  14818. 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);
  14819. }
  14820. }
  14821. if (!kv_self.v_trans) {
  14822. for (uint32_t il = 0; il < n_layer; ++il) {
  14823. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14824. // Read type of value
  14825. int32_t v_type_i_ref;
  14826. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14827. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14828. if (v_type_i != v_type_i_ref) {
  14829. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14830. return false;
  14831. }
  14832. // Read row size of value
  14833. uint64_t v_size_row_ref;
  14834. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  14835. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14836. if (v_size_row != v_size_row_ref) {
  14837. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  14838. return false;
  14839. }
  14840. if (cell_count) {
  14841. // Read and set the values for the whole cell range
  14842. 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);
  14843. }
  14844. }
  14845. } else {
  14846. // For each layer, read the values for each cell (transposed)
  14847. for (uint32_t il = 0; il < n_layer; ++il) {
  14848. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14849. // Read type of value
  14850. int32_t v_type_i_ref;
  14851. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14852. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14853. if (v_type_i != v_type_i_ref) {
  14854. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14855. return false;
  14856. }
  14857. // Read element size of value
  14858. uint32_t v_size_el_ref;
  14859. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  14860. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14861. if (v_size_el != v_size_el_ref) {
  14862. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  14863. return false;
  14864. }
  14865. // Read GQA embedding size
  14866. uint32_t n_embd_v_gqa_ref;
  14867. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  14868. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  14869. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  14870. return false;
  14871. }
  14872. if (cell_count) {
  14873. // For each row in the transposed matrix, read the values for the whole cell range
  14874. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14875. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  14876. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  14877. }
  14878. }
  14879. }
  14880. }
  14881. return true;
  14882. }
  14883. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14884. uint32_t cell_count;
  14885. read_to(&cell_count, sizeof(cell_count));
  14886. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  14887. if (!res) {
  14888. if (seq_id == -1) {
  14889. llama_kv_cache_clear(ctx);
  14890. } else {
  14891. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  14892. }
  14893. throw std::runtime_error("failed to restore kv cache");
  14894. }
  14895. }
  14896. };
  14897. struct llama_data_write_dummy : llama_data_write {
  14898. size_t size_written = 0;
  14899. llama_data_write_dummy() {}
  14900. // TODO: avoid unnecessary calls to ggml_backend_tensor_get in a dummy context
  14901. void write(const void * /* src */, size_t size) override {
  14902. size_written += size;
  14903. }
  14904. size_t get_size_written() override {
  14905. return size_written;
  14906. }
  14907. };
  14908. struct llama_data_write_buffer : llama_data_write {
  14909. uint8_t * ptr;
  14910. size_t buf_size = 0;
  14911. size_t size_written = 0;
  14912. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14913. void write(const void * src, size_t size) override {
  14914. if (size > buf_size) {
  14915. throw std::runtime_error("unexpectedly reached end of buffer");
  14916. }
  14917. memcpy(ptr, src, size);
  14918. ptr += size;
  14919. size_written += size;
  14920. buf_size -= size;
  14921. }
  14922. size_t get_size_written() override {
  14923. return size_written;
  14924. }
  14925. };
  14926. struct llama_data_read_buffer : llama_data_read {
  14927. const uint8_t * ptr;
  14928. size_t buf_size = 0;
  14929. size_t size_read = 0;
  14930. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14931. const uint8_t * read(size_t size) override {
  14932. const uint8_t * base_ptr = ptr;
  14933. if (size > buf_size) {
  14934. throw std::runtime_error("unexpectedly reached end of buffer");
  14935. }
  14936. ptr += size;
  14937. size_read += size;
  14938. buf_size -= size;
  14939. return base_ptr;
  14940. }
  14941. void read_to(void * dst, size_t size) override {
  14942. memcpy(dst, read(size), size);
  14943. }
  14944. size_t get_size_read() override {
  14945. return size_read;
  14946. }
  14947. };
  14948. struct llama_data_write_file : llama_data_write {
  14949. llama_file * file;
  14950. size_t size_written = 0;
  14951. llama_data_write_file(llama_file * f) : file(f) {}
  14952. void write(const void * src, size_t size) override {
  14953. file->write_raw(src, size);
  14954. size_written += size;
  14955. }
  14956. size_t get_size_written() override {
  14957. return size_written;
  14958. }
  14959. };
  14960. struct llama_data_read_file : llama_data_read {
  14961. llama_file * file;
  14962. size_t size_read = 0;
  14963. std::vector<uint8_t> temp_buffer;
  14964. llama_data_read_file(llama_file * f) : file(f) {}
  14965. void read_to(void * dst, size_t size) override {
  14966. file->read_raw(dst, size);
  14967. size_read += size;
  14968. }
  14969. const uint8_t * read(size_t size) override {
  14970. temp_buffer.resize(size);
  14971. read_to(temp_buffer.data(), size);
  14972. return temp_buffer.data();
  14973. }
  14974. size_t get_size_read() override {
  14975. return size_read;
  14976. }
  14977. };
  14978. /** copy state data into either a buffer or file depending on the passed in context
  14979. *
  14980. * file context:
  14981. * llama_file file("/path", "wb");
  14982. * llama_data_write_file data_ctx(&file);
  14983. * llama_state_get_data_internal(ctx, data_ctx);
  14984. *
  14985. * buffer context:
  14986. * std::vector<uint8_t> buf(max_size, 0);
  14987. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  14988. * llama_state_get_data_internal(ctx, data_ctx);
  14989. *
  14990. */
  14991. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  14992. llama_synchronize(ctx);
  14993. data_ctx.write_model_info(ctx);
  14994. data_ctx.write_rng(ctx->sampling.rng);
  14995. // copy outputs
  14996. data_ctx.write_output_ids(ctx);
  14997. data_ctx.write_logits(ctx);
  14998. data_ctx.write_embeddings(ctx);
  14999. data_ctx.write_kv_cache(ctx);
  15000. return data_ctx.get_size_written();
  15001. }
  15002. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  15003. llama_data_write_buffer data_ctx(dst, size);
  15004. try {
  15005. return llama_state_get_data_internal(ctx, data_ctx);
  15006. } catch (const std::exception & err) {
  15007. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  15008. return 0;
  15009. }
  15010. }
  15011. // Returns the *actual* size of the state.
  15012. // Intended to be used when saving to state to a buffer.
  15013. size_t llama_state_get_size(struct llama_context * ctx) {
  15014. llama_data_write_dummy data_ctx;
  15015. try {
  15016. return llama_state_get_data_internal(ctx, data_ctx);
  15017. } catch (const std::exception & err) {
  15018. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  15019. return 0;
  15020. }
  15021. }
  15022. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  15023. llama_synchronize(ctx);
  15024. data_ctx.read_model_info(ctx);
  15025. // set rng
  15026. data_ctx.read_rng(ctx->sampling.rng);
  15027. // set outputs
  15028. data_ctx.read_output_ids(ctx);
  15029. data_ctx.read_logits(ctx);
  15030. data_ctx.read_embeddings(ctx);
  15031. data_ctx.read_kv_cache(ctx);
  15032. return data_ctx.get_size_read();
  15033. }
  15034. // Sets the state reading from the specified source address
  15035. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  15036. llama_data_read_buffer data_ctx(src, size);
  15037. try {
  15038. return llama_state_set_data_internal(ctx, data_ctx);
  15039. } catch (const std::exception & err) {
  15040. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  15041. return 0;
  15042. }
  15043. }
  15044. 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) {
  15045. llama_file file(path_session, "rb");
  15046. // sanity checks
  15047. {
  15048. const uint32_t magic = file.read_u32();
  15049. const uint32_t version = file.read_u32();
  15050. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  15051. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  15052. return false;
  15053. }
  15054. }
  15055. // load the prompt
  15056. {
  15057. const uint32_t n_token_count = file.read_u32();
  15058. if (n_token_count > n_token_capacity) {
  15059. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15060. return false;
  15061. }
  15062. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15063. *n_token_count_out = n_token_count;
  15064. }
  15065. // restore the context state
  15066. {
  15067. const size_t n_state_size_cur = file.size - file.tell();
  15068. llama_data_read_file data_ctx(&file);
  15069. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  15070. if (n_read != n_state_size_cur) {
  15071. 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);
  15072. return false;
  15073. }
  15074. }
  15075. return true;
  15076. }
  15077. 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) {
  15078. try {
  15079. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  15080. } catch (const std::exception & err) {
  15081. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  15082. return false;
  15083. }
  15084. }
  15085. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15086. llama_file file(path_session, "wb");
  15087. file.write_u32(LLAMA_SESSION_MAGIC);
  15088. file.write_u32(LLAMA_SESSION_VERSION);
  15089. // save the prompt
  15090. file.write_u32((uint32_t) n_token_count);
  15091. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15092. // save the context state using stream saving
  15093. llama_data_write_file data_ctx(&file);
  15094. llama_state_get_data_internal(ctx, data_ctx);
  15095. return true;
  15096. }
  15097. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15098. try {
  15099. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  15100. } catch (const std::exception & err) {
  15101. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  15102. return false;
  15103. }
  15104. }
  15105. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  15106. llama_synchronize(ctx);
  15107. data_ctx.write_kv_cache(ctx, seq_id);
  15108. return data_ctx.get_size_written();
  15109. }
  15110. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  15111. llama_data_write_dummy data_ctx;
  15112. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15113. }
  15114. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  15115. llama_data_write_buffer data_ctx(dst, size);
  15116. try {
  15117. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15118. } catch (const std::exception & err) {
  15119. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  15120. return 0;
  15121. }
  15122. }
  15123. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  15124. llama_synchronize(ctx);
  15125. data_ctx.read_kv_cache(ctx, dest_seq_id);
  15126. return data_ctx.get_size_read();
  15127. }
  15128. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  15129. llama_data_read_buffer data_ctx(src, size);
  15130. try {
  15131. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15132. } catch (const std::exception & err) {
  15133. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  15134. return 0;
  15135. }
  15136. }
  15137. 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) {
  15138. llama_file file(filepath, "wb");
  15139. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  15140. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  15141. // save the prompt
  15142. file.write_u32((uint32_t) n_token_count);
  15143. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15144. // save the context state using stream saving
  15145. llama_data_write_file data_ctx(&file);
  15146. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15147. const size_t res = file.tell();
  15148. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  15149. return res;
  15150. }
  15151. 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) {
  15152. llama_file file(filepath, "rb");
  15153. // version checks
  15154. {
  15155. const uint32_t magic = file.read_u32();
  15156. const uint32_t version = file.read_u32();
  15157. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  15158. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  15159. return 0;
  15160. }
  15161. }
  15162. // load the prompt
  15163. {
  15164. const uint32_t n_token_count = file.read_u32();
  15165. if (n_token_count > n_token_capacity) {
  15166. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15167. return 0;
  15168. }
  15169. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15170. *n_token_count_out = n_token_count;
  15171. }
  15172. // restore the context state
  15173. {
  15174. const size_t state_size = file.size - file.tell();
  15175. llama_data_read_file data_ctx(&file);
  15176. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15177. if (!nread) {
  15178. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  15179. return 0;
  15180. }
  15181. GGML_ASSERT(nread <= state_size);
  15182. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  15183. }
  15184. return file.tell();
  15185. }
  15186. 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) {
  15187. try {
  15188. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  15189. } catch (const std::exception & err) {
  15190. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  15191. return 0;
  15192. }
  15193. }
  15194. 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) {
  15195. try {
  15196. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  15197. } catch (const std::exception & err) {
  15198. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  15199. return 0;
  15200. }
  15201. }
  15202. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  15203. ctx->cparams.n_threads = n_threads;
  15204. ctx->cparams.n_threads_batch = n_threads_batch;
  15205. }
  15206. uint32_t llama_n_threads(struct llama_context * ctx) {
  15207. return ctx->cparams.n_threads;
  15208. }
  15209. uint32_t llama_n_threads_batch(struct llama_context * ctx) {
  15210. return ctx->cparams.n_threads_batch;
  15211. }
  15212. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  15213. ctx->abort_callback = abort_callback;
  15214. ctx->abort_callback_data = abort_callback_data;
  15215. }
  15216. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  15217. ctx->cparams.embeddings = embeddings;
  15218. }
  15219. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  15220. ctx->cparams.causal_attn = causal_attn;
  15221. }
  15222. struct llama_batch llama_batch_get_one(
  15223. llama_token * tokens,
  15224. int32_t n_tokens,
  15225. llama_pos pos_0,
  15226. llama_seq_id seq_id) {
  15227. return {
  15228. /*n_tokens =*/ n_tokens,
  15229. /*tokens =*/ tokens,
  15230. /*embd =*/ nullptr,
  15231. /*pos =*/ nullptr,
  15232. /*n_seq_id =*/ nullptr,
  15233. /*seq_id =*/ nullptr,
  15234. /*logits =*/ nullptr,
  15235. /*all_pos_0 =*/ pos_0,
  15236. /*all_pos_1 =*/ 1,
  15237. /*all_seq_id =*/ seq_id,
  15238. };
  15239. }
  15240. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  15241. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  15242. if (embd) {
  15243. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  15244. } else {
  15245. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  15246. }
  15247. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  15248. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  15249. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  15250. for (int i = 0; i < n_tokens_alloc; ++i) {
  15251. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  15252. }
  15253. batch.seq_id[n_tokens_alloc] = nullptr;
  15254. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  15255. return batch;
  15256. }
  15257. void llama_batch_free(struct llama_batch batch) {
  15258. if (batch.token) free(batch.token);
  15259. if (batch.embd) free(batch.embd);
  15260. if (batch.pos) free(batch.pos);
  15261. if (batch.n_seq_id) free(batch.n_seq_id);
  15262. if (batch.seq_id) {
  15263. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  15264. free(batch.seq_id[i]);
  15265. }
  15266. free(batch.seq_id);
  15267. }
  15268. if (batch.logits) free(batch.logits);
  15269. }
  15270. int32_t llama_encode(
  15271. struct llama_context * ctx,
  15272. struct llama_batch batch) {
  15273. const int ret = llama_encode_internal(*ctx, batch);
  15274. if (ret < 0) {
  15275. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  15276. }
  15277. return ret;
  15278. }
  15279. int32_t llama_decode(
  15280. struct llama_context * ctx,
  15281. struct llama_batch batch) {
  15282. const int ret = llama_decode_internal(*ctx, batch);
  15283. if (ret < 0) {
  15284. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  15285. }
  15286. return ret;
  15287. }
  15288. void llama_synchronize(struct llama_context * ctx) {
  15289. ggml_backend_sched_synchronize(ctx->sched);
  15290. // FIXME: if multiple single tokens are evaluated without a synchronization,
  15291. // the stats will be added to the prompt evaluation stats
  15292. // this should only happen when using batch size 1 to evaluate a batch
  15293. // add the evaluation to the stats
  15294. if (ctx->n_queued_tokens == 1) {
  15295. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15296. ctx->n_eval++;
  15297. } else if (ctx->n_queued_tokens > 1) {
  15298. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15299. ctx->n_p_eval += ctx->n_queued_tokens;
  15300. }
  15301. // get a more accurate load time, upon first eval
  15302. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  15303. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  15304. ctx->has_evaluated_once = true;
  15305. }
  15306. ctx->n_queued_tokens = 0;
  15307. ctx->t_compute_start_us = 0;
  15308. }
  15309. float * llama_get_logits(struct llama_context * ctx) {
  15310. llama_synchronize(ctx);
  15311. return ctx->logits;
  15312. }
  15313. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  15314. int32_t j = -1;
  15315. llama_synchronize(ctx);
  15316. try {
  15317. if (ctx->logits == nullptr) {
  15318. throw std::runtime_error("no logits");
  15319. }
  15320. if (i < 0) {
  15321. j = ctx->n_outputs + i;
  15322. if (j < 0) {
  15323. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15324. }
  15325. } else if ((size_t) i >= ctx->output_ids.size()) {
  15326. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15327. } else {
  15328. j = ctx->output_ids[i];
  15329. }
  15330. if (j < 0) {
  15331. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15332. }
  15333. if (j >= ctx->n_outputs) {
  15334. // This should not happen
  15335. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15336. }
  15337. return ctx->logits + j*ctx->model.hparams.n_vocab;
  15338. } catch (const std::exception & err) {
  15339. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  15340. #ifndef NDEBUG
  15341. GGML_ABORT("fatal error");
  15342. #endif
  15343. return nullptr;
  15344. }
  15345. }
  15346. float * llama_get_embeddings(struct llama_context * ctx) {
  15347. llama_synchronize(ctx);
  15348. return ctx->embd;
  15349. }
  15350. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  15351. int32_t j = -1;
  15352. llama_synchronize(ctx);
  15353. try {
  15354. if (ctx->embd == nullptr) {
  15355. throw std::runtime_error("no embeddings");
  15356. }
  15357. if (i < 0) {
  15358. j = ctx->n_outputs + i;
  15359. if (j < 0) {
  15360. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15361. }
  15362. } else if ((size_t) i >= ctx->output_ids.size()) {
  15363. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15364. } else {
  15365. j = ctx->output_ids[i];
  15366. }
  15367. if (j < 0) {
  15368. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15369. }
  15370. if (j >= ctx->n_outputs) {
  15371. // This should not happen
  15372. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15373. }
  15374. return ctx->embd + j*ctx->model.hparams.n_embd;
  15375. } catch (const std::exception & err) {
  15376. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  15377. #ifndef NDEBUG
  15378. GGML_ABORT("fatal error");
  15379. #endif
  15380. return nullptr;
  15381. }
  15382. }
  15383. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  15384. llama_synchronize(ctx);
  15385. auto it = ctx->embd_seq.find(seq_id);
  15386. if (it == ctx->embd_seq.end()) {
  15387. return nullptr;
  15388. }
  15389. return it->second.data();
  15390. }
  15391. //
  15392. // vocab
  15393. //
  15394. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  15395. return llama_token_get_text_impl(model->vocab, token);
  15396. }
  15397. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  15398. return llama_token_get_score_impl(model->vocab, token);
  15399. }
  15400. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  15401. return llama_token_get_attr_impl(model->vocab, token);
  15402. }
  15403. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  15404. return llama_token_is_eog_impl(model->vocab, token);
  15405. }
  15406. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  15407. return llama_token_is_control_impl(model->vocab, token);
  15408. }
  15409. llama_token llama_token_bos(const struct llama_model * model) {
  15410. return llama_token_bos_impl(model->vocab);
  15411. }
  15412. llama_token llama_token_eos(const struct llama_model * model) {
  15413. return llama_token_eos_impl(model->vocab);
  15414. }
  15415. llama_token llama_token_cls(const struct llama_model * model) {
  15416. return llama_token_cls_impl(model->vocab);
  15417. }
  15418. llama_token llama_token_sep(const struct llama_model * model) {
  15419. return llama_token_sep_impl(model->vocab);
  15420. }
  15421. llama_token llama_token_nl (const struct llama_model * model) {
  15422. return llama_token_nl_impl(model->vocab);
  15423. }
  15424. llama_token llama_token_pad(const struct llama_model * model) {
  15425. return llama_token_pad_impl(model->vocab);
  15426. }
  15427. int32_t llama_add_bos_token(const struct llama_model * model) {
  15428. return llama_add_bos_token_impl(model->vocab);
  15429. }
  15430. int32_t llama_add_eos_token(const struct llama_model * model) {
  15431. return llama_add_eos_token_impl(model->vocab);
  15432. }
  15433. llama_token llama_token_prefix(const struct llama_model * model) {
  15434. return llama_token_prefix_impl(model->vocab);
  15435. }
  15436. llama_token llama_token_middle(const struct llama_model * model) {
  15437. return llama_token_middle_impl(model->vocab);
  15438. }
  15439. llama_token llama_token_suffix(const struct llama_model * model) {
  15440. return llama_token_suffix_impl(model->vocab);
  15441. }
  15442. llama_token llama_token_eot(const struct llama_model * model) {
  15443. return llama_token_eot_impl(model->vocab);
  15444. }
  15445. //
  15446. // tokenization
  15447. //
  15448. int32_t llama_tokenize(
  15449. const struct llama_model * model,
  15450. const char * text,
  15451. int32_t text_len,
  15452. llama_token * tokens,
  15453. int32_t n_tokens_max,
  15454. bool add_special,
  15455. bool parse_special) {
  15456. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  15457. }
  15458. int32_t llama_token_to_piece(
  15459. const struct llama_model * model,
  15460. llama_token token,
  15461. char * buf,
  15462. int32_t length,
  15463. int32_t lstrip,
  15464. bool special) {
  15465. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  15466. }
  15467. int32_t llama_detokenize(
  15468. const struct llama_model * model,
  15469. const llama_token * tokens,
  15470. int32_t n_tokens,
  15471. char * text,
  15472. int32_t text_len_max,
  15473. bool remove_special,
  15474. bool unparse_special) {
  15475. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  15476. }
  15477. //
  15478. // chat templates
  15479. //
  15480. // Simple version of "llama_apply_chat_template" that only works with strings
  15481. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  15482. static int32_t llama_chat_apply_template_internal(
  15483. const std::string & tmpl,
  15484. const std::vector<const llama_chat_message *> & chat,
  15485. std::string & dest, bool add_ass) {
  15486. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  15487. std::stringstream ss;
  15488. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  15489. return tmpl.find(haystack) != std::string::npos;
  15490. };
  15491. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  15492. // chatml template
  15493. for (auto message : chat) {
  15494. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  15495. }
  15496. if (add_ass) {
  15497. ss << "<|im_start|>assistant\n";
  15498. }
  15499. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  15500. // llama2 template and its variants
  15501. // [variant] support system message
  15502. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  15503. // [variant] space before + after response
  15504. bool space_around_response = tmpl_contains("' ' + eos_token");
  15505. // [variant] add BOS inside history
  15506. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  15507. // [variant] trim spaces from the input message
  15508. bool strip_message = tmpl_contains("content.strip()");
  15509. // construct the prompt
  15510. bool is_inside_turn = true; // skip BOS at the beginning
  15511. ss << "[INST] ";
  15512. for (auto message : chat) {
  15513. std::string content = strip_message ? trim(message->content) : message->content;
  15514. std::string role(message->role);
  15515. if (!is_inside_turn) {
  15516. is_inside_turn = true;
  15517. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  15518. }
  15519. if (role == "system") {
  15520. if (support_system_message) {
  15521. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  15522. } else {
  15523. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  15524. ss << content << "\n";
  15525. }
  15526. } else if (role == "user") {
  15527. ss << content << " [/INST]";
  15528. } else {
  15529. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  15530. is_inside_turn = false;
  15531. }
  15532. }
  15533. // llama2 templates seem to not care about "add_generation_prompt"
  15534. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  15535. // Phi 3
  15536. for (auto message : chat) {
  15537. std::string role(message->role);
  15538. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  15539. }
  15540. if (add_ass) {
  15541. ss << "<|assistant|>\n";
  15542. }
  15543. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  15544. // zephyr template
  15545. for (auto message : chat) {
  15546. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  15547. }
  15548. if (add_ass) {
  15549. ss << "<|assistant|>\n";
  15550. }
  15551. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  15552. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  15553. for (auto message : chat) {
  15554. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  15555. ss << bos << message->role << "\n" << message->content << "</s>\n";
  15556. }
  15557. if (add_ass) {
  15558. ss << "<s>assistant\n";
  15559. }
  15560. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  15561. // google/gemma-7b-it
  15562. std::string system_prompt = "";
  15563. for (auto message : chat) {
  15564. std::string role(message->role);
  15565. if (role == "system") {
  15566. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  15567. system_prompt = trim(message->content);
  15568. continue;
  15569. }
  15570. // in gemma, "assistant" is "model"
  15571. role = role == "assistant" ? "model" : message->role;
  15572. ss << "<start_of_turn>" << role << "\n";
  15573. if (!system_prompt.empty() && role != "model") {
  15574. ss << system_prompt << "\n\n";
  15575. system_prompt = "";
  15576. }
  15577. ss << trim(message->content) << "<end_of_turn>\n";
  15578. }
  15579. if (add_ass) {
  15580. ss << "<start_of_turn>model\n";
  15581. }
  15582. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  15583. // OrionStarAI/Orion-14B-Chat
  15584. std::string system_prompt = "";
  15585. for (auto message : chat) {
  15586. std::string role(message->role);
  15587. if (role == "system") {
  15588. // there is no system message support, we will merge it with user prompt
  15589. system_prompt = message->content;
  15590. continue;
  15591. } else if (role == "user") {
  15592. ss << "Human: ";
  15593. if (!system_prompt.empty()) {
  15594. ss << system_prompt << "\n\n";
  15595. system_prompt = "";
  15596. }
  15597. ss << message->content << "\n\nAssistant: </s>";
  15598. } else {
  15599. ss << message->content << "</s>";
  15600. }
  15601. }
  15602. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  15603. // openchat/openchat-3.5-0106,
  15604. for (auto message : chat) {
  15605. std::string role(message->role);
  15606. if (role == "system") {
  15607. ss << message->content << "<|end_of_turn|>";
  15608. } else {
  15609. role[0] = toupper(role[0]);
  15610. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  15611. }
  15612. }
  15613. if (add_ass) {
  15614. ss << "GPT4 Correct Assistant:";
  15615. }
  15616. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  15617. // eachadea/vicuna-13b-1.1 (and Orca variant)
  15618. for (auto message : chat) {
  15619. std::string role(message->role);
  15620. if (role == "system") {
  15621. // Orca-Vicuna variant uses a system prefix
  15622. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  15623. ss << "SYSTEM: " << message->content << "\n";
  15624. } else {
  15625. ss << message->content << "\n\n";
  15626. }
  15627. } else if (role == "user") {
  15628. ss << "USER: " << message->content << "\n";
  15629. } else if (role == "assistant") {
  15630. ss << "ASSISTANT: " << message->content << "</s>\n";
  15631. }
  15632. }
  15633. if (add_ass) {
  15634. ss << "ASSISTANT:";
  15635. }
  15636. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  15637. // deepseek-ai/deepseek-coder-33b-instruct
  15638. for (auto message : chat) {
  15639. std::string role(message->role);
  15640. if (role == "system") {
  15641. ss << message->content;
  15642. } else if (role == "user") {
  15643. ss << "### Instruction:\n" << message->content << "\n";
  15644. } else if (role == "assistant") {
  15645. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  15646. }
  15647. }
  15648. if (add_ass) {
  15649. ss << "### Response:\n";
  15650. }
  15651. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  15652. // CohereForAI/c4ai-command-r-plus
  15653. for (auto message : chat) {
  15654. std::string role(message->role);
  15655. if (role == "system") {
  15656. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15657. } else if (role == "user") {
  15658. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15659. } else if (role == "assistant") {
  15660. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15661. }
  15662. }
  15663. if (add_ass) {
  15664. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  15665. }
  15666. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  15667. // Llama 3
  15668. for (auto message : chat) {
  15669. std::string role(message->role);
  15670. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  15671. }
  15672. if (add_ass) {
  15673. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  15674. }
  15675. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  15676. // chatglm3-6b
  15677. ss << "[gMASK]" << "sop";
  15678. for (auto message : chat) {
  15679. std::string role(message->role);
  15680. ss << "<|" << role << "|>" << "\n " << message->content;
  15681. }
  15682. if (add_ass) {
  15683. ss << "<|assistant|>";
  15684. }
  15685. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  15686. ss << "[gMASK]" << "<sop>";
  15687. for (auto message : chat) {
  15688. std::string role(message->role);
  15689. ss << "<|" << role << "|>" << "\n" << message->content;
  15690. }
  15691. if (add_ass) {
  15692. ss << "<|assistant|>";
  15693. }
  15694. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  15695. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  15696. for (auto message : chat) {
  15697. std::string role(message->role);
  15698. if (role == "user") {
  15699. ss << LU8("<用户>");
  15700. ss << trim(message->content);
  15701. ss << "<AI>";
  15702. } else {
  15703. ss << trim(message->content);
  15704. }
  15705. }
  15706. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  15707. // DeepSeek-V2
  15708. for (auto message : chat) {
  15709. std::string role(message->role);
  15710. if (role == "system") {
  15711. ss << message->content << "\n\n";
  15712. } else if (role == "user") {
  15713. ss << "User: " << message->content << "\n\n";
  15714. } else if (role == "assistant") {
  15715. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  15716. }
  15717. }
  15718. if (add_ass) {
  15719. ss << "Assistant:";
  15720. }
  15721. } else {
  15722. // template not supported
  15723. return -1;
  15724. }
  15725. dest = ss.str();
  15726. return dest.size();
  15727. }
  15728. int32_t llama_chat_apply_template(
  15729. const struct llama_model * model,
  15730. const char * tmpl,
  15731. const struct llama_chat_message * chat,
  15732. size_t n_msg,
  15733. bool add_ass,
  15734. char * buf,
  15735. int32_t length) {
  15736. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  15737. if (tmpl == nullptr) {
  15738. GGML_ASSERT(model != nullptr);
  15739. // load template from model
  15740. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  15741. std::string template_key = "tokenizer.chat_template";
  15742. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  15743. if (res < 0) {
  15744. // worst case: there is no information about template, we will use chatml by default
  15745. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  15746. } else {
  15747. curr_tmpl = std::string(model_template.data(), model_template.size());
  15748. }
  15749. }
  15750. // format the chat to string
  15751. std::vector<const llama_chat_message *> chat_vec;
  15752. chat_vec.resize(n_msg);
  15753. for (size_t i = 0; i < n_msg; i++) {
  15754. chat_vec[i] = &chat[i];
  15755. }
  15756. std::string formatted_chat;
  15757. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  15758. if (res < 0) {
  15759. return res;
  15760. }
  15761. if (buf && length > 0) {
  15762. strncpy(buf, formatted_chat.c_str(), length);
  15763. }
  15764. return res;
  15765. }
  15766. //
  15767. // grammar
  15768. //
  15769. struct llama_grammar * llama_grammar_init(
  15770. const llama_grammar_element ** rules,
  15771. size_t n_rules,
  15772. size_t start_rule_index) {
  15773. return llama_grammar_init_impl(rules, n_rules, start_rule_index);
  15774. }
  15775. void llama_grammar_free(struct llama_grammar * grammar) {
  15776. llama_grammar_free_impl(grammar);
  15777. }
  15778. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  15779. return llama_grammar_copy_impl(grammar);
  15780. }
  15781. void llama_grammar_sample(
  15782. const struct llama_grammar * grammar,
  15783. const struct llama_context * ctx,
  15784. llama_token_data_array * candidates) {
  15785. llama_grammar_sample_impl(grammar, &ctx->model.vocab, &ctx->sampling, candidates);
  15786. }
  15787. void llama_sample_grammar(
  15788. struct llama_context * ctx,
  15789. llama_token_data_array * candidates,
  15790. const struct llama_grammar * grammar) {
  15791. llama_grammar_sample(grammar, ctx, candidates);
  15792. }
  15793. void llama_grammar_accept_token(
  15794. struct llama_grammar * grammar,
  15795. struct llama_context * ctx,
  15796. llama_token token) {
  15797. llama_grammar_accept_token_impl(grammar, &ctx->model.vocab, &ctx->sampling, token);
  15798. }
  15799. //
  15800. // sampling
  15801. //
  15802. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  15803. llama_set_rng_seed_impl(&ctx->sampling, seed);
  15804. }
  15805. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  15806. llama_sample_softmax_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15807. }
  15808. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  15809. llama_sample_top_k_impl(ctx ? &ctx->sampling : nullptr, candidates, k, min_keep);
  15810. }
  15811. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15812. llama_sample_top_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15813. }
  15814. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15815. llama_sample_min_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15816. }
  15817. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  15818. llama_sample_tail_free_impl(ctx ? &ctx->sampling : nullptr, candidates, z, min_keep);
  15819. }
  15820. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15821. llama_sample_typical_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15822. }
  15823. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  15824. llama_sample_entropy_impl(ctx ? &ctx->sampling : nullptr, candidates_p, min_temp, max_temp, exponent_val);
  15825. }
  15826. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  15827. llama_sample_temp_impl(ctx ? &ctx->sampling : nullptr, candidates_p, temp);
  15828. }
  15829. void llama_sample_repetition_penalties(
  15830. struct llama_context * ctx,
  15831. llama_token_data_array * candidates,
  15832. const llama_token * last_tokens,
  15833. size_t penalty_last_n,
  15834. float penalty_repeat,
  15835. float penalty_freq,
  15836. float penalty_present) {
  15837. llama_sample_repetition_penalties_impl(ctx ? &ctx->sampling : nullptr, candidates, last_tokens, penalty_last_n, penalty_repeat, penalty_freq, penalty_present);
  15838. }
  15839. void llama_sample_apply_guidance(
  15840. struct llama_context * ctx,
  15841. float * logits,
  15842. float * logits_guidance,
  15843. float scale) {
  15844. llama_sample_apply_guidance_impl(&ctx->sampling, logits, logits_guidance, scale);
  15845. }
  15846. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  15847. return llama_sample_token_mirostat_impl(&ctx->sampling, candidates, tau, eta, m, mu);
  15848. }
  15849. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  15850. return llama_sample_token_mirostat_v2_impl(ctx ? &ctx->sampling : nullptr, candidates, tau, eta, mu);
  15851. }
  15852. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  15853. return llama_sample_token_greedy_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15854. }
  15855. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  15856. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, rng);
  15857. }
  15858. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  15859. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, ctx->sampling.rng);
  15860. }
  15861. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  15862. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  15863. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  15864. return strlen(split_path);
  15865. }
  15866. return 0;
  15867. }
  15868. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  15869. std::string str_split_path(split_path);
  15870. char postfix[32];
  15871. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  15872. std::string str_postfix(postfix);
  15873. // check if dest ends with postfix
  15874. int size_prefix = str_split_path.size() - str_postfix.size();
  15875. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  15876. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  15877. return size_prefix;
  15878. }
  15879. return 0;
  15880. }
  15881. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  15882. struct llama_timings result = {
  15883. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  15884. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  15885. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  15886. /*.t_sample_ms =*/ 1e-3 * ctx->sampling.t_sample_us,
  15887. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  15888. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  15889. /*.n_sample =*/ std::max(1, ctx->sampling.n_sample),
  15890. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  15891. /*.n_eval =*/ std::max(1, ctx->n_eval),
  15892. };
  15893. return result;
  15894. }
  15895. void llama_print_timings(struct llama_context * ctx) {
  15896. const llama_timings timings = llama_get_timings(ctx);
  15897. LLAMA_LOG_INFO("\n");
  15898. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  15899. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15900. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  15901. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  15902. __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);
  15903. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15904. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  15905. 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));
  15906. }
  15907. void llama_reset_timings(struct llama_context * ctx) {
  15908. ctx->t_start_us = ggml_time_us();
  15909. ctx->t_eval_us = ctx->n_eval = 0;
  15910. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  15911. ctx->sampling.reset_timings();
  15912. }
  15913. const char * llama_print_system_info(void) {
  15914. static std::string s;
  15915. s = "";
  15916. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  15917. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  15918. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  15919. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  15920. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  15921. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  15922. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  15923. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  15924. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  15925. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  15926. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  15927. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  15928. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  15929. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  15930. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  15931. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  15932. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  15933. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  15934. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  15935. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  15936. return s.c_str();
  15937. }
  15938. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  15939. fprintf(stream, "\n");
  15940. fprintf(stream, "###########\n");
  15941. fprintf(stream, "# Timings #\n");
  15942. fprintf(stream, "###########\n");
  15943. fprintf(stream, "\n");
  15944. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  15945. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  15946. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  15947. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  15948. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  15949. 1.0e-3 * ctx->sampling.t_sample_us / ctx->sampling.n_sample);
  15950. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  15951. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  15952. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->sampling.n_sample);
  15953. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  15954. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  15955. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  15956. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->sampling.t_sample_us);
  15957. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  15958. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  15959. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  15960. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  15961. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  15962. 1.0e6 * ctx->sampling.n_sample / ctx->sampling.t_sample_us);
  15963. }
  15964. // For internal test use
  15965. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  15966. struct llama_context * ctx
  15967. ) {
  15968. return ctx->model.tensors_by_name;
  15969. }
  15970. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  15971. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  15972. g_state.log_callback_user_data = user_data;
  15973. #ifdef GGML_USE_METAL
  15974. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15975. #elif defined(GGML_USE_CUDA)
  15976. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15977. #elif defined(GGML_USE_CANN)
  15978. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15979. #endif
  15980. }
  15981. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  15982. va_list args_copy;
  15983. va_copy(args_copy, args);
  15984. char buffer[128];
  15985. int len = vsnprintf(buffer, 128, format, args);
  15986. if (len < 128) {
  15987. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  15988. } else {
  15989. char* buffer2 = new char[len+1];
  15990. vsnprintf(buffer2, len+1, format, args_copy);
  15991. buffer2[len] = 0;
  15992. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  15993. delete[] buffer2;
  15994. }
  15995. va_end(args_copy);
  15996. }
  15997. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  15998. va_list args;
  15999. va_start(args, format);
  16000. llama_log_internal_v(level, format, args);
  16001. va_end(args);
  16002. }
  16003. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  16004. (void) level;
  16005. (void) user_data;
  16006. fputs(text, stderr);
  16007. fflush(stderr);
  16008. }