llama.cpp 838 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321
  1. #include "llama-impl.h"
  2. #include "llama-vocab.h"
  3. #include "llama-grammar.h"
  4. #include "llama-sampling.h"
  5. #include "unicode.h"
  6. #include "ggml.h"
  7. #include "ggml-alloc.h"
  8. #include "ggml-backend.h"
  9. #ifdef GGML_USE_RPC
  10. # include "ggml-rpc.h"
  11. #endif
  12. #ifdef GGML_USE_CUDA
  13. # include "ggml-cuda.h"
  14. #elif defined(GGML_USE_VULKAN)
  15. # include "ggml-vulkan.h"
  16. #elif defined(GGML_USE_SYCL)
  17. # include "ggml-sycl.h"
  18. #elif defined(GGML_USE_KOMPUTE)
  19. # include "ggml-kompute.h"
  20. #elif defined(GGML_USE_CANN)
  21. # include "ggml-cann.h"
  22. #endif
  23. #ifdef GGML_USE_BLAS
  24. # include "ggml-blas.h"
  25. #endif
  26. #ifdef GGML_USE_METAL
  27. # include "ggml-metal.h"
  28. #endif
  29. // TODO: replace with ggml API call
  30. #define QK_K 256
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #if __cplusplus >= 202000L
  55. #define LU8(x) (const char*)(u8##x)
  56. #else
  57. #define LU8(x) u8##x
  58. #endif
  59. #include <algorithm>
  60. #include <array>
  61. #include <cassert>
  62. #include <cctype>
  63. #include <cfloat>
  64. #include <cinttypes>
  65. #include <climits>
  66. #include <cmath>
  67. #include <cstdarg>
  68. #include <cstddef>
  69. #include <cstdint>
  70. #include <cstdio>
  71. #include <cstring>
  72. #include <ctime>
  73. #include <fstream>
  74. #include <functional>
  75. #include <future>
  76. #include <initializer_list>
  77. #include <locale>
  78. #include <map>
  79. #include <memory>
  80. #include <mutex>
  81. #include <numeric>
  82. #include <set>
  83. #include <sstream>
  84. #include <thread>
  85. #include <type_traits>
  86. #include <unordered_map>
  87. #if defined(_MSC_VER)
  88. #pragma warning(disable: 4244 4267) // possible loss of data
  89. #endif
  90. // bump if necessary
  91. #define LLAMA_MAX_LAYERS 512
  92. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  93. //
  94. // helpers
  95. //
  96. // trim whitespace from the beginning and end of a string
  97. static std::string trim(const std::string & str) {
  98. size_t start = 0;
  99. size_t end = str.size();
  100. while (start < end && isspace(str[start])) {
  101. start += 1;
  102. }
  103. while (end > start && isspace(str[end - 1])) {
  104. end -= 1;
  105. }
  106. return str.substr(start, end - start);
  107. }
  108. static bool is_float_close(float a, float b, float abs_tol) {
  109. // Check for non-negative tolerance
  110. if (abs_tol < 0.0) {
  111. throw std::invalid_argument("Tolerance must be non-negative");
  112. }
  113. // Exact equality check
  114. if (a == b) {
  115. return true;
  116. }
  117. // Check for infinities
  118. if (std::isinf(a) || std::isinf(b)) {
  119. return false;
  120. }
  121. // Regular comparison using the provided absolute tolerance
  122. return std::fabs(b - a) <= abs_tol;
  123. }
  124. static void zeros(std::ofstream & file, size_t n) {
  125. char zero = 0;
  126. for (size_t i = 0; i < n; ++i) {
  127. file.write(&zero, 1);
  128. }
  129. }
  130. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  131. static std::string format(const char * fmt, ...) {
  132. va_list ap;
  133. va_list ap2;
  134. va_start(ap, fmt);
  135. va_copy(ap2, ap);
  136. int size = vsnprintf(NULL, 0, fmt, ap);
  137. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  138. std::vector<char> buf(size + 1);
  139. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  140. GGML_ASSERT(size2 == size);
  141. va_end(ap2);
  142. va_end(ap);
  143. return std::string(buf.data(), size);
  144. }
  145. //
  146. // gguf constants (sync with gguf.py)
  147. //
  148. enum llm_arch {
  149. LLM_ARCH_LLAMA,
  150. LLM_ARCH_FALCON,
  151. LLM_ARCH_BAICHUAN,
  152. LLM_ARCH_GROK,
  153. LLM_ARCH_GPT2,
  154. LLM_ARCH_GPTJ,
  155. LLM_ARCH_GPTNEOX,
  156. LLM_ARCH_MPT,
  157. LLM_ARCH_STARCODER,
  158. LLM_ARCH_REFACT,
  159. LLM_ARCH_BERT,
  160. LLM_ARCH_NOMIC_BERT,
  161. LLM_ARCH_JINA_BERT_V2,
  162. LLM_ARCH_BLOOM,
  163. LLM_ARCH_STABLELM,
  164. LLM_ARCH_QWEN,
  165. LLM_ARCH_QWEN2,
  166. LLM_ARCH_QWEN2MOE,
  167. LLM_ARCH_PHI2,
  168. LLM_ARCH_PHI3,
  169. LLM_ARCH_PLAMO,
  170. LLM_ARCH_CODESHELL,
  171. LLM_ARCH_ORION,
  172. LLM_ARCH_INTERNLM2,
  173. LLM_ARCH_MINICPM,
  174. LLM_ARCH_GEMMA,
  175. LLM_ARCH_GEMMA2,
  176. LLM_ARCH_STARCODER2,
  177. LLM_ARCH_MAMBA,
  178. LLM_ARCH_XVERSE,
  179. LLM_ARCH_COMMAND_R,
  180. LLM_ARCH_DBRX,
  181. LLM_ARCH_OLMO,
  182. LLM_ARCH_OPENELM,
  183. LLM_ARCH_ARCTIC,
  184. LLM_ARCH_DEEPSEEK2,
  185. LLM_ARCH_CHATGLM,
  186. LLM_ARCH_BITNET,
  187. LLM_ARCH_T5,
  188. LLM_ARCH_T5ENCODER,
  189. LLM_ARCH_JAIS,
  190. LLM_ARCH_NEMOTRON,
  191. LLM_ARCH_EXAONE,
  192. LLM_ARCH_UNKNOWN,
  193. };
  194. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  195. { LLM_ARCH_LLAMA, "llama" },
  196. { LLM_ARCH_FALCON, "falcon" },
  197. { LLM_ARCH_GROK, "grok" },
  198. { LLM_ARCH_GPT2, "gpt2" },
  199. { LLM_ARCH_GPTJ, "gptj" },
  200. { LLM_ARCH_GPTNEOX, "gptneox" },
  201. { LLM_ARCH_MPT, "mpt" },
  202. { LLM_ARCH_BAICHUAN, "baichuan" },
  203. { LLM_ARCH_STARCODER, "starcoder" },
  204. { LLM_ARCH_REFACT, "refact" },
  205. { LLM_ARCH_BERT, "bert" },
  206. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  207. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  208. { LLM_ARCH_BLOOM, "bloom" },
  209. { LLM_ARCH_STABLELM, "stablelm" },
  210. { LLM_ARCH_QWEN, "qwen" },
  211. { LLM_ARCH_QWEN2, "qwen2" },
  212. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  213. { LLM_ARCH_PHI2, "phi2" },
  214. { LLM_ARCH_PHI3, "phi3" },
  215. { LLM_ARCH_PLAMO, "plamo" },
  216. { LLM_ARCH_CODESHELL, "codeshell" },
  217. { LLM_ARCH_ORION, "orion" },
  218. { LLM_ARCH_INTERNLM2, "internlm2" },
  219. { LLM_ARCH_MINICPM, "minicpm" },
  220. { LLM_ARCH_GEMMA, "gemma" },
  221. { LLM_ARCH_GEMMA2, "gemma2" },
  222. { LLM_ARCH_STARCODER2, "starcoder2" },
  223. { LLM_ARCH_MAMBA, "mamba" },
  224. { LLM_ARCH_XVERSE, "xverse" },
  225. { LLM_ARCH_COMMAND_R, "command-r" },
  226. { LLM_ARCH_DBRX, "dbrx" },
  227. { LLM_ARCH_OLMO, "olmo" },
  228. { LLM_ARCH_OPENELM, "openelm" },
  229. { LLM_ARCH_ARCTIC, "arctic" },
  230. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  231. { LLM_ARCH_CHATGLM, "chatglm" },
  232. { LLM_ARCH_BITNET, "bitnet" },
  233. { LLM_ARCH_T5, "t5" },
  234. { LLM_ARCH_T5ENCODER, "t5encoder" },
  235. { LLM_ARCH_JAIS, "jais" },
  236. { LLM_ARCH_NEMOTRON, "nemotron" },
  237. { LLM_ARCH_EXAONE, "exaone" },
  238. { LLM_ARCH_UNKNOWN, "(unknown)" },
  239. };
  240. enum llm_kv {
  241. LLM_KV_GENERAL_TYPE,
  242. LLM_KV_GENERAL_ARCHITECTURE,
  243. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  244. LLM_KV_GENERAL_ALIGNMENT,
  245. LLM_KV_GENERAL_NAME,
  246. LLM_KV_GENERAL_AUTHOR,
  247. LLM_KV_GENERAL_VERSION,
  248. LLM_KV_GENERAL_URL,
  249. LLM_KV_GENERAL_DESCRIPTION,
  250. LLM_KV_GENERAL_LICENSE,
  251. LLM_KV_GENERAL_SOURCE_URL,
  252. LLM_KV_GENERAL_SOURCE_HF_REPO,
  253. LLM_KV_VOCAB_SIZE,
  254. LLM_KV_CONTEXT_LENGTH,
  255. LLM_KV_EMBEDDING_LENGTH,
  256. LLM_KV_BLOCK_COUNT,
  257. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  258. LLM_KV_FEED_FORWARD_LENGTH,
  259. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  260. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  261. LLM_KV_USE_PARALLEL_RESIDUAL,
  262. LLM_KV_TENSOR_DATA_LAYOUT,
  263. LLM_KV_EXPERT_COUNT,
  264. LLM_KV_EXPERT_USED_COUNT,
  265. LLM_KV_EXPERT_SHARED_COUNT,
  266. LLM_KV_EXPERT_WEIGHTS_SCALE,
  267. LLM_KV_POOLING_TYPE,
  268. LLM_KV_LOGIT_SCALE,
  269. LLM_KV_DECODER_START_TOKEN_ID,
  270. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  271. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  272. LLM_KV_ATTENTION_HEAD_COUNT,
  273. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  274. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  275. LLM_KV_ATTENTION_CLAMP_KQV,
  276. LLM_KV_ATTENTION_KEY_LENGTH,
  277. LLM_KV_ATTENTION_VALUE_LENGTH,
  278. LLM_KV_ATTENTION_LAYERNORM_EPS,
  279. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  280. LLM_KV_ATTENTION_CAUSAL,
  281. LLM_KV_ATTENTION_Q_LORA_RANK,
  282. LLM_KV_ATTENTION_KV_LORA_RANK,
  283. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  284. LLM_KV_ATTENTION_SLIDING_WINDOW,
  285. LLM_KV_ROPE_DIMENSION_COUNT,
  286. LLM_KV_ROPE_FREQ_BASE,
  287. LLM_KV_ROPE_SCALE_LINEAR,
  288. LLM_KV_ROPE_SCALING_TYPE,
  289. LLM_KV_ROPE_SCALING_FACTOR,
  290. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  291. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  292. LLM_KV_ROPE_SCALING_FINETUNED,
  293. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  294. LLM_KV_SPLIT_NO,
  295. LLM_KV_SPLIT_COUNT,
  296. LLM_KV_SPLIT_TENSORS_COUNT,
  297. LLM_KV_SSM_INNER_SIZE,
  298. LLM_KV_SSM_CONV_KERNEL,
  299. LLM_KV_SSM_STATE_SIZE,
  300. LLM_KV_SSM_TIME_STEP_RANK,
  301. LLM_KV_SSM_DT_B_C_RMS,
  302. LLM_KV_TOKENIZER_MODEL,
  303. LLM_KV_TOKENIZER_PRE,
  304. LLM_KV_TOKENIZER_LIST,
  305. LLM_KV_TOKENIZER_TOKEN_TYPE,
  306. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  307. LLM_KV_TOKENIZER_SCORES,
  308. LLM_KV_TOKENIZER_MERGES,
  309. LLM_KV_TOKENIZER_BOS_ID,
  310. LLM_KV_TOKENIZER_EOS_ID,
  311. LLM_KV_TOKENIZER_UNK_ID,
  312. LLM_KV_TOKENIZER_SEP_ID,
  313. LLM_KV_TOKENIZER_PAD_ID,
  314. LLM_KV_TOKENIZER_CLS_ID,
  315. LLM_KV_TOKENIZER_MASK_ID,
  316. LLM_KV_TOKENIZER_ADD_BOS,
  317. LLM_KV_TOKENIZER_ADD_EOS,
  318. LLM_KV_TOKENIZER_ADD_PREFIX,
  319. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  320. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  321. LLM_KV_TOKENIZER_HF_JSON,
  322. LLM_KV_TOKENIZER_RWKV,
  323. LLM_KV_TOKENIZER_PREFIX_ID,
  324. LLM_KV_TOKENIZER_SUFFIX_ID,
  325. LLM_KV_TOKENIZER_MIDDLE_ID,
  326. LLM_KV_TOKENIZER_EOT_ID,
  327. LLM_KV_TOKENIZER_EOM_ID,
  328. LLM_KV_ADAPTER_TYPE,
  329. LLM_KV_ADAPTER_LORA_ALPHA,
  330. };
  331. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  332. { LLM_KV_GENERAL_TYPE, "general.type" },
  333. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  334. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  335. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  336. { LLM_KV_GENERAL_NAME, "general.name" },
  337. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  338. { LLM_KV_GENERAL_VERSION, "general.version" },
  339. { LLM_KV_GENERAL_URL, "general.url" },
  340. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  341. { LLM_KV_GENERAL_LICENSE, "general.license" },
  342. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  343. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  344. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  345. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  346. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  347. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  348. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  349. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  350. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  351. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  352. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  353. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  354. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  355. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  356. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  357. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  358. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  359. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  360. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  361. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  362. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  363. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  364. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  365. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  366. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  367. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  368. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  369. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  370. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  371. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  372. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  373. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  374. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  375. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  376. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  377. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  378. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  379. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  380. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  381. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  382. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  383. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  384. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  385. { LLM_KV_SPLIT_NO, "split.no" },
  386. { LLM_KV_SPLIT_COUNT, "split.count" },
  387. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  388. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  389. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  390. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  391. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  392. { LLM_KV_SSM_DT_B_C_RMS, "%s.ssm.dt_b_c_rms" },
  393. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  394. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  395. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  396. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  397. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  398. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  399. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  400. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  401. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  402. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  403. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  404. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  405. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  406. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  407. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  408. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  409. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  410. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  411. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  412. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  413. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  414. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  415. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  416. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  417. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  418. { LLM_KV_TOKENIZER_EOM_ID, "tokenizer.ggml.eom_token_id" },
  419. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  420. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  421. };
  422. struct LLM_KV {
  423. LLM_KV(llm_arch arch) : arch(arch) {}
  424. llm_arch arch;
  425. std::string operator()(llm_kv kv) const {
  426. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  427. }
  428. };
  429. enum llm_tensor {
  430. LLM_TENSOR_TOKEN_EMBD,
  431. LLM_TENSOR_TOKEN_EMBD_NORM,
  432. LLM_TENSOR_TOKEN_TYPES,
  433. LLM_TENSOR_POS_EMBD,
  434. LLM_TENSOR_OUTPUT,
  435. LLM_TENSOR_OUTPUT_NORM,
  436. LLM_TENSOR_ROPE_FREQS,
  437. LLM_TENSOR_ROPE_FACTORS_LONG,
  438. LLM_TENSOR_ROPE_FACTORS_SHORT,
  439. LLM_TENSOR_ATTN_Q,
  440. LLM_TENSOR_ATTN_K,
  441. LLM_TENSOR_ATTN_V,
  442. LLM_TENSOR_ATTN_QKV,
  443. LLM_TENSOR_ATTN_OUT,
  444. LLM_TENSOR_ATTN_NORM,
  445. LLM_TENSOR_ATTN_NORM_2,
  446. LLM_TENSOR_ATTN_OUT_NORM,
  447. LLM_TENSOR_ATTN_POST_NORM,
  448. LLM_TENSOR_ATTN_ROT_EMBD,
  449. LLM_TENSOR_FFN_GATE_INP,
  450. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  451. LLM_TENSOR_FFN_NORM,
  452. LLM_TENSOR_FFN_POST_NORM,
  453. LLM_TENSOR_FFN_GATE,
  454. LLM_TENSOR_FFN_DOWN,
  455. LLM_TENSOR_FFN_UP,
  456. LLM_TENSOR_FFN_ACT,
  457. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  458. LLM_TENSOR_FFN_GATE_EXP,
  459. LLM_TENSOR_FFN_UP_EXP,
  460. LLM_TENSOR_FFN_NORM_EXPS,
  461. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  462. LLM_TENSOR_FFN_GATE_EXPS,
  463. LLM_TENSOR_FFN_UP_EXPS,
  464. LLM_TENSOR_FFN_DOWN_SHEXP,
  465. LLM_TENSOR_FFN_GATE_SHEXP,
  466. LLM_TENSOR_FFN_UP_SHEXP,
  467. LLM_TENSOR_ATTN_Q_NORM,
  468. LLM_TENSOR_ATTN_K_NORM,
  469. LLM_TENSOR_LAYER_OUT_NORM,
  470. LLM_TENSOR_SSM_IN,
  471. LLM_TENSOR_SSM_CONV1D,
  472. LLM_TENSOR_SSM_X,
  473. LLM_TENSOR_SSM_DT,
  474. LLM_TENSOR_SSM_A,
  475. LLM_TENSOR_SSM_D,
  476. LLM_TENSOR_SSM_OUT,
  477. LLM_TENSOR_ATTN_Q_A,
  478. LLM_TENSOR_ATTN_Q_B,
  479. LLM_TENSOR_ATTN_KV_A_MQA,
  480. LLM_TENSOR_ATTN_KV_B,
  481. LLM_TENSOR_ATTN_Q_A_NORM,
  482. LLM_TENSOR_ATTN_KV_A_NORM,
  483. LLM_TENSOR_ATTN_SUB_NORM,
  484. LLM_TENSOR_FFN_SUB_NORM,
  485. LLM_TENSOR_DEC_ATTN_NORM,
  486. LLM_TENSOR_DEC_ATTN_Q,
  487. LLM_TENSOR_DEC_ATTN_K,
  488. LLM_TENSOR_DEC_ATTN_V,
  489. LLM_TENSOR_DEC_ATTN_OUT,
  490. LLM_TENSOR_DEC_ATTN_REL_B,
  491. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  492. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  493. LLM_TENSOR_DEC_CROSS_ATTN_K,
  494. LLM_TENSOR_DEC_CROSS_ATTN_V,
  495. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  496. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  497. LLM_TENSOR_DEC_FFN_NORM,
  498. LLM_TENSOR_DEC_FFN_GATE,
  499. LLM_TENSOR_DEC_FFN_DOWN,
  500. LLM_TENSOR_DEC_FFN_UP,
  501. LLM_TENSOR_DEC_OUTPUT_NORM,
  502. LLM_TENSOR_ENC_ATTN_NORM,
  503. LLM_TENSOR_ENC_ATTN_Q,
  504. LLM_TENSOR_ENC_ATTN_K,
  505. LLM_TENSOR_ENC_ATTN_V,
  506. LLM_TENSOR_ENC_ATTN_OUT,
  507. LLM_TENSOR_ENC_ATTN_REL_B,
  508. LLM_TENSOR_ENC_FFN_NORM,
  509. LLM_TENSOR_ENC_FFN_GATE,
  510. LLM_TENSOR_ENC_FFN_DOWN,
  511. LLM_TENSOR_ENC_FFN_UP,
  512. LLM_TENSOR_ENC_OUTPUT_NORM,
  513. };
  514. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  515. {
  516. LLM_ARCH_LLAMA,
  517. {
  518. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  519. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  520. { LLM_TENSOR_OUTPUT, "output" },
  521. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  522. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  523. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  524. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  525. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  528. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  529. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  530. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  531. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  532. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  533. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  534. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  535. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  536. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  537. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  538. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  539. },
  540. },
  541. {
  542. LLM_ARCH_BAICHUAN,
  543. {
  544. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  545. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  546. { LLM_TENSOR_OUTPUT, "output" },
  547. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  548. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  549. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  550. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  551. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  552. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  553. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  554. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  555. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  556. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  557. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  558. },
  559. },
  560. {
  561. LLM_ARCH_FALCON,
  562. {
  563. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  564. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  565. { LLM_TENSOR_OUTPUT, "output" },
  566. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  567. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  568. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  569. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  570. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  571. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  572. },
  573. },
  574. {
  575. LLM_ARCH_GROK,
  576. {
  577. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  578. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  579. { LLM_TENSOR_OUTPUT, "output" },
  580. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  581. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  582. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  583. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  584. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  585. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  586. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  587. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  588. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  589. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  590. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  591. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  592. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  593. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  594. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  595. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  596. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  597. },
  598. },
  599. {
  600. LLM_ARCH_GPT2,
  601. {
  602. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  603. { LLM_TENSOR_POS_EMBD, "position_embd" },
  604. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  605. { LLM_TENSOR_OUTPUT, "output" },
  606. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  607. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  608. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  609. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  610. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  611. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  612. },
  613. },
  614. {
  615. LLM_ARCH_GPTJ,
  616. {
  617. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  618. },
  619. },
  620. {
  621. LLM_ARCH_GPTNEOX,
  622. {
  623. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  624. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  625. { LLM_TENSOR_OUTPUT, "output" },
  626. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  627. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  628. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  629. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  630. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  631. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  632. },
  633. },
  634. {
  635. LLM_ARCH_MPT,
  636. {
  637. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  638. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  639. { LLM_TENSOR_OUTPUT, "output"},
  640. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  641. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  642. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  643. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  644. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  645. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  646. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  647. { LLM_TENSOR_POS_EMBD, "position_embd" },
  648. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  649. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  650. },
  651. },
  652. {
  653. LLM_ARCH_STARCODER,
  654. {
  655. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  656. { LLM_TENSOR_POS_EMBD, "position_embd" },
  657. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  658. { LLM_TENSOR_OUTPUT, "output" },
  659. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  660. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  661. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  662. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  663. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  664. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  665. },
  666. },
  667. {
  668. LLM_ARCH_REFACT,
  669. {
  670. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  671. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  672. { LLM_TENSOR_OUTPUT, "output" },
  673. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  674. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  675. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  676. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  677. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  678. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  679. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  680. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  681. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  682. },
  683. },
  684. {
  685. LLM_ARCH_BERT,
  686. {
  687. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  688. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  689. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  690. { LLM_TENSOR_POS_EMBD, "position_embd" },
  691. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  692. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  693. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  694. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  695. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  696. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  697. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  698. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  699. },
  700. },
  701. {
  702. LLM_ARCH_NOMIC_BERT,
  703. {
  704. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  705. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  706. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  707. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  708. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  709. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  710. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  711. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  712. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  713. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  714. },
  715. },
  716. {
  717. LLM_ARCH_JINA_BERT_V2,
  718. {
  719. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  720. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  721. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  722. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  723. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  724. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  725. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  726. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  727. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  728. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  729. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  730. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  731. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  732. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  733. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  734. },
  735. },
  736. {
  737. LLM_ARCH_BLOOM,
  738. {
  739. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  740. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  741. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  742. { LLM_TENSOR_OUTPUT, "output" },
  743. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  744. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  745. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  746. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  747. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  748. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  749. },
  750. },
  751. {
  752. LLM_ARCH_STABLELM,
  753. {
  754. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  755. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  756. { LLM_TENSOR_OUTPUT, "output" },
  757. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  758. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  759. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  760. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  761. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  762. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  763. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  764. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  765. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  766. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  767. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  768. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  769. },
  770. },
  771. {
  772. LLM_ARCH_QWEN,
  773. {
  774. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  775. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  776. { LLM_TENSOR_OUTPUT, "output" },
  777. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  778. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  779. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  780. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  781. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  782. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  783. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  784. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  785. },
  786. },
  787. {
  788. LLM_ARCH_QWEN2,
  789. {
  790. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  791. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  792. { LLM_TENSOR_OUTPUT, "output" },
  793. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  794. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  795. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  796. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  797. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  798. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  799. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  800. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  801. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  802. },
  803. },
  804. {
  805. LLM_ARCH_QWEN2MOE,
  806. {
  807. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  808. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  809. { LLM_TENSOR_OUTPUT, "output" },
  810. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  811. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  812. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  813. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  814. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  815. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  816. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  817. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  818. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  819. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  820. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  821. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  822. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  823. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  824. },
  825. },
  826. {
  827. LLM_ARCH_PHI2,
  828. {
  829. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  830. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  831. { LLM_TENSOR_OUTPUT, "output" },
  832. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  833. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  834. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  835. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  836. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  837. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  838. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  839. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  840. },
  841. },
  842. {
  843. LLM_ARCH_PHI3,
  844. {
  845. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  846. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  847. { LLM_TENSOR_OUTPUT, "output" },
  848. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  849. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  850. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  851. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  852. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  853. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  854. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  855. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  856. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  857. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  858. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  859. },
  860. },
  861. {
  862. LLM_ARCH_PLAMO,
  863. {
  864. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  865. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  866. { LLM_TENSOR_OUTPUT, "output" },
  867. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  868. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  869. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  870. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  871. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  872. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  873. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  874. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  875. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  876. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  877. },
  878. },
  879. {
  880. LLM_ARCH_CODESHELL,
  881. {
  882. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  883. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  884. { LLM_TENSOR_OUTPUT, "output" },
  885. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  886. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  887. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  888. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  889. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  890. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  891. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  892. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  893. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  894. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  895. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  896. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  897. },
  898. },
  899. {
  900. LLM_ARCH_ORION,
  901. {
  902. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  903. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  904. { LLM_TENSOR_OUTPUT, "output" },
  905. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  906. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  907. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  908. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  909. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  910. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  911. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  912. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  913. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  914. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  915. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  916. },
  917. },
  918. {
  919. LLM_ARCH_INTERNLM2,
  920. {
  921. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  922. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  923. { LLM_TENSOR_OUTPUT, "output" },
  924. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  925. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  926. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  927. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  928. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  929. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  930. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  931. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  932. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  933. },
  934. },
  935. {
  936. LLM_ARCH_MINICPM,
  937. {
  938. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  939. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  940. { LLM_TENSOR_OUTPUT, "output" },
  941. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  942. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  943. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  944. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  945. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  946. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  947. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  948. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  949. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  950. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  951. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  952. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  953. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  954. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  955. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  956. },
  957. },
  958. {
  959. LLM_ARCH_GEMMA,
  960. {
  961. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  962. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  963. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  964. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  965. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  966. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  967. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  968. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  969. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  970. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  971. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  972. },
  973. },
  974. {
  975. LLM_ARCH_GEMMA2,
  976. {
  977. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  978. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  979. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  980. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  981. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  982. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  983. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  984. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  985. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  986. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  987. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  988. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  989. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  990. },
  991. },
  992. {
  993. LLM_ARCH_STARCODER2,
  994. {
  995. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  996. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  997. { LLM_TENSOR_OUTPUT, "output" },
  998. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  999. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1000. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1001. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1002. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1003. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1004. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1005. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1006. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1007. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1008. },
  1009. },
  1010. {
  1011. LLM_ARCH_MAMBA,
  1012. {
  1013. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1014. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1015. { LLM_TENSOR_OUTPUT, "output" },
  1016. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1017. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1018. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1019. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1020. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1021. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1022. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1023. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1024. },
  1025. },
  1026. {
  1027. LLM_ARCH_XVERSE,
  1028. {
  1029. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1030. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1031. { LLM_TENSOR_OUTPUT, "output" },
  1032. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1033. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1034. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1035. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1036. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1037. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1038. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1039. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1040. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1041. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1042. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1043. },
  1044. },
  1045. {
  1046. LLM_ARCH_COMMAND_R,
  1047. {
  1048. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1049. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1050. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1051. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1052. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1053. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1054. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1055. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1056. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1057. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1058. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1059. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1060. },
  1061. },
  1062. {
  1063. LLM_ARCH_DBRX,
  1064. {
  1065. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1066. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1067. { LLM_TENSOR_OUTPUT, "output" },
  1068. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1069. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1070. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1071. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1072. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1073. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1074. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1075. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1076. },
  1077. },
  1078. {
  1079. LLM_ARCH_OLMO,
  1080. {
  1081. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1082. { LLM_TENSOR_OUTPUT, "output" },
  1083. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1084. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1085. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1086. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1087. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1088. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1089. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1090. },
  1091. },
  1092. {
  1093. LLM_ARCH_OPENELM,
  1094. {
  1095. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1096. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1097. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1098. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1099. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1100. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1101. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1102. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1103. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1104. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1105. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1106. },
  1107. },
  1108. {
  1109. LLM_ARCH_ARCTIC,
  1110. {
  1111. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1112. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1113. { LLM_TENSOR_OUTPUT, "output" },
  1114. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1115. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1116. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1117. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1118. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1119. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1120. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1121. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1122. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1123. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1124. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1125. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1126. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1127. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1128. },
  1129. },
  1130. {
  1131. LLM_ARCH_DEEPSEEK2,
  1132. {
  1133. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1134. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1135. { LLM_TENSOR_OUTPUT, "output" },
  1136. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1137. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1138. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1139. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1140. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1141. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1142. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1143. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1144. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1145. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1146. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1147. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1148. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1149. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1150. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1151. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1152. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1153. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1154. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1155. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1156. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1157. },
  1158. },
  1159. {
  1160. LLM_ARCH_CHATGLM,
  1161. {
  1162. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1163. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1164. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1165. { LLM_TENSOR_OUTPUT, "output" },
  1166. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1167. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1168. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1169. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1170. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1171. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1172. },
  1173. },
  1174. {
  1175. LLM_ARCH_BITNET,
  1176. {
  1177. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1178. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1179. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1180. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1181. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1182. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1183. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1184. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1185. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1186. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1187. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1188. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1189. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1190. },
  1191. },
  1192. {
  1193. LLM_ARCH_T5,
  1194. {
  1195. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1196. { LLM_TENSOR_OUTPUT, "output" },
  1197. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1198. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1199. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1200. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1201. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1202. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1203. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1204. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1205. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1206. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1207. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1208. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1209. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1210. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1211. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1212. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1213. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1214. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1215. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1216. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1217. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1218. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1219. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1220. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1221. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1222. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1223. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1224. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1225. },
  1226. },
  1227. {
  1228. LLM_ARCH_T5ENCODER,
  1229. {
  1230. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1231. { LLM_TENSOR_OUTPUT, "output" },
  1232. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1233. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1234. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1235. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1236. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1237. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1238. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1239. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1240. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1241. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1242. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1243. },
  1244. },
  1245. {
  1246. LLM_ARCH_JAIS,
  1247. {
  1248. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1249. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1250. { LLM_TENSOR_OUTPUT, "output" },
  1251. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1252. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1253. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1254. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1255. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1256. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1257. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1258. },
  1259. },
  1260. {
  1261. LLM_ARCH_NEMOTRON,
  1262. {
  1263. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1264. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1265. { LLM_TENSOR_OUTPUT, "output" },
  1266. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1267. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1268. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1269. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1270. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1271. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1272. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1273. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1274. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1275. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1276. },
  1277. },
  1278. {
  1279. LLM_ARCH_EXAONE,
  1280. {
  1281. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1282. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1283. { LLM_TENSOR_OUTPUT, "output" },
  1284. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1285. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1286. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1287. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1288. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1289. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1290. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1291. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1292. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1293. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1294. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1295. },
  1296. },
  1297. {
  1298. LLM_ARCH_UNKNOWN,
  1299. {
  1300. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1301. },
  1302. },
  1303. };
  1304. static llm_arch llm_arch_from_string(const std::string & name) {
  1305. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1306. if (kv.second == name) {
  1307. return kv.first;
  1308. }
  1309. }
  1310. return LLM_ARCH_UNKNOWN;
  1311. }
  1312. // helper to handle gguf constants
  1313. // usage:
  1314. //
  1315. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1316. //
  1317. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1318. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1319. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1320. //
  1321. struct LLM_TN {
  1322. LLM_TN(llm_arch arch) : arch(arch) {}
  1323. llm_arch arch;
  1324. std::string operator()(llm_tensor tensor) const {
  1325. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1326. return "__missing__";
  1327. }
  1328. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1329. }
  1330. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1331. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1332. return "__missing__";
  1333. }
  1334. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1335. }
  1336. std::string operator()(llm_tensor tensor, int bid) const {
  1337. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1338. return "__missing__";
  1339. }
  1340. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1341. }
  1342. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1343. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1344. return "__missing__";
  1345. }
  1346. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1347. }
  1348. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1349. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1350. return "__missing__";
  1351. }
  1352. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1353. }
  1354. };
  1355. //
  1356. // gguf helpers
  1357. //
  1358. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1359. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1360. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1361. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1362. };
  1363. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1364. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1365. if (kv.second == name) {
  1366. return (llama_rope_scaling_type) kv.first;
  1367. }
  1368. }
  1369. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1370. }
  1371. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1372. switch (type) {
  1373. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1374. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1375. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1376. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1377. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1378. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1379. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1380. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1381. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1382. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1383. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1384. default: return format("unknown type %d", type);
  1385. }
  1386. }
  1387. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1388. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1389. switch (type) {
  1390. case GGUF_TYPE_STRING:
  1391. return gguf_get_val_str(ctx_gguf, i);
  1392. case GGUF_TYPE_ARRAY:
  1393. {
  1394. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1395. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1396. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1397. std::stringstream ss;
  1398. ss << "[";
  1399. for (int j = 0; j < arr_n; j++) {
  1400. if (arr_type == GGUF_TYPE_STRING) {
  1401. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1402. // escape quotes
  1403. replace_all(val, "\\", "\\\\");
  1404. replace_all(val, "\"", "\\\"");
  1405. ss << '"' << val << '"';
  1406. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1407. ss << "???";
  1408. } else {
  1409. ss << gguf_data_to_str(arr_type, data, j);
  1410. }
  1411. if (j < arr_n - 1) {
  1412. ss << ", ";
  1413. }
  1414. }
  1415. ss << "]";
  1416. return ss.str();
  1417. }
  1418. default:
  1419. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1420. }
  1421. }
  1422. //
  1423. // llama helpers
  1424. //
  1425. #if defined(_WIN32)
  1426. static std::string llama_format_win_err(DWORD err) {
  1427. LPSTR buf;
  1428. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1429. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1430. if (!size) {
  1431. return "FormatMessageA failed";
  1432. }
  1433. std::string ret(buf, size);
  1434. LocalFree(buf);
  1435. return ret;
  1436. }
  1437. #endif
  1438. template <typename T>
  1439. struct no_init {
  1440. T value;
  1441. no_init() { /* do nothing */ }
  1442. };
  1443. struct llama_file {
  1444. #if defined(_WIN32)
  1445. // use FILE * so we don't have to re-open the file to mmap
  1446. FILE * fp;
  1447. HANDLE fp_win32;
  1448. size_t size;
  1449. private:
  1450. std::string GetErrorMessageWin32(DWORD error_code) const {
  1451. std::string ret;
  1452. LPSTR lpMsgBuf = NULL;
  1453. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1454. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1455. if (!bufLen) {
  1456. ret = format("Win32 error code: %s", error_code);
  1457. } else {
  1458. ret = lpMsgBuf;
  1459. LocalFree(lpMsgBuf);
  1460. }
  1461. return ret;
  1462. }
  1463. public:
  1464. llama_file(const char * fname, const char * mode) {
  1465. fp = ggml_fopen(fname, mode);
  1466. if (fp == NULL) {
  1467. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1468. }
  1469. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1470. seek(0, SEEK_END);
  1471. size = tell();
  1472. seek(0, SEEK_SET);
  1473. }
  1474. size_t tell() const {
  1475. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1476. LARGE_INTEGER li;
  1477. li.QuadPart = 0;
  1478. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1479. if (!ret) {
  1480. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1481. }
  1482. return li.QuadPart;
  1483. }
  1484. void seek(size_t offset, int whence) const {
  1485. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1486. // Still, keep static asserts to avoid failures in the future.
  1487. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1488. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1489. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1490. LARGE_INTEGER li;
  1491. li.QuadPart = offset;
  1492. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1493. if (!ret) {
  1494. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1495. }
  1496. }
  1497. void read_raw(void * ptr, size_t len) const {
  1498. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1499. // use the Win32 API to do file io instead of the C/C++ library functions.
  1500. // There are conditions under which ReadFile cannot read chunks >64MB.
  1501. // Thus split the operation into smaller chunks if len exceeds this limit.
  1502. size_t bytes_read = 0;
  1503. while (bytes_read < len) {
  1504. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1505. DWORD chunk_read = 0;
  1506. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1507. if (!result) {
  1508. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1509. }
  1510. if (chunk_read < chunk_size || chunk_read == 0) {
  1511. throw std::runtime_error("unexpectedly reached end of file");
  1512. }
  1513. bytes_read += chunk_read;
  1514. } ;
  1515. }
  1516. uint32_t read_u32() const {
  1517. uint32_t val;
  1518. read_raw(&val, sizeof(val));
  1519. return val;
  1520. }
  1521. void write_raw(const void * ptr, size_t len) const {
  1522. // There are conditions under which WriteFile cannot write chunks >64MB.
  1523. // Thus split the operation into smaller chunks if len exceeds this limit.
  1524. size_t bytes_written = 0;
  1525. while (bytes_written < len) {
  1526. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1527. DWORD chunk_written = 0;
  1528. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1529. if (!result) {
  1530. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1531. }
  1532. if (chunk_written < chunk_size || chunk_written == 0) {
  1533. throw std::runtime_error("unexpectedly failed to write bytes");
  1534. }
  1535. bytes_written += chunk_written;
  1536. }
  1537. }
  1538. void write_u32(std::uint32_t val) const {
  1539. write_raw(&val, sizeof(val));
  1540. }
  1541. ~llama_file() {
  1542. if (fp) {
  1543. std::fclose(fp);
  1544. }
  1545. }
  1546. #else
  1547. // use FILE * so we don't have to re-open the file to mmap
  1548. FILE * fp;
  1549. size_t size;
  1550. llama_file(const char * fname, const char * mode) {
  1551. fp = ggml_fopen(fname, mode);
  1552. if (fp == NULL) {
  1553. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1554. }
  1555. seek(0, SEEK_END);
  1556. size = tell();
  1557. seek(0, SEEK_SET);
  1558. }
  1559. size_t tell() const {
  1560. #ifdef _WIN32
  1561. __int64 ret = _ftelli64(fp);
  1562. #else
  1563. long ret = std::ftell(fp);
  1564. #endif
  1565. if (ret == -1) {
  1566. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1567. }
  1568. return (size_t) ret;
  1569. }
  1570. void seek(size_t offset, int whence) const {
  1571. #ifdef _WIN32
  1572. int ret = _fseeki64(fp, (__int64) offset, whence);
  1573. #else
  1574. int ret = std::fseek(fp, (long) offset, whence);
  1575. #endif
  1576. if (ret != 0) {
  1577. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1578. }
  1579. }
  1580. void read_raw(void * ptr, size_t len) const {
  1581. if (len == 0) {
  1582. return;
  1583. }
  1584. errno = 0;
  1585. std::size_t ret = std::fread(ptr, len, 1, fp);
  1586. if (ferror(fp)) {
  1587. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1588. }
  1589. if (ret != 1) {
  1590. throw std::runtime_error("unexpectedly reached end of file");
  1591. }
  1592. }
  1593. uint32_t read_u32() const {
  1594. uint32_t ret;
  1595. read_raw(&ret, sizeof(ret));
  1596. return ret;
  1597. }
  1598. void write_raw(const void * ptr, size_t len) const {
  1599. if (len == 0) {
  1600. return;
  1601. }
  1602. errno = 0;
  1603. size_t ret = std::fwrite(ptr, len, 1, fp);
  1604. if (ret != 1) {
  1605. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1606. }
  1607. }
  1608. void write_u32(std::uint32_t val) const {
  1609. write_raw(&val, sizeof(val));
  1610. }
  1611. ~llama_file() {
  1612. if (fp) {
  1613. std::fclose(fp);
  1614. }
  1615. }
  1616. #endif
  1617. };
  1618. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1619. struct llama_mmap {
  1620. void * addr;
  1621. size_t size;
  1622. llama_mmap(const llama_mmap &) = delete;
  1623. #ifdef _POSIX_MAPPED_FILES
  1624. static constexpr bool SUPPORTED = true;
  1625. // list of mapped fragments (first_offset, last_offset)
  1626. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1627. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1628. size = file->size;
  1629. int fd = fileno(file->fp);
  1630. int flags = MAP_SHARED;
  1631. // prefetch/readahead impairs performance on NUMA systems
  1632. if (numa) { prefetch = 0; }
  1633. #ifdef __linux__
  1634. // advise the kernel to read the file sequentially (increases readahead)
  1635. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1636. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1637. strerror(errno));
  1638. }
  1639. if (prefetch) { flags |= MAP_POPULATE; }
  1640. #endif
  1641. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1642. if (addr == MAP_FAILED) { // NOLINT
  1643. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1644. }
  1645. if (prefetch > 0) {
  1646. // advise the kernel to preload the mapped memory
  1647. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1648. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1649. strerror(errno));
  1650. }
  1651. }
  1652. if (numa) {
  1653. // advise the kernel not to use readahead
  1654. // (because the next page might not belong on the same node)
  1655. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1656. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1657. strerror(errno));
  1658. }
  1659. }
  1660. // initialize list of mapped_fragments
  1661. mapped_fragments.emplace_back(0, file->size);
  1662. }
  1663. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1664. // align first to the next page
  1665. size_t offset_in_page = *first & (page_size - 1);
  1666. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1667. *first += offset_to_page;
  1668. // align last to the previous page
  1669. *last = *last & ~(page_size - 1);
  1670. if (*last <= *first) {
  1671. *last = *first;
  1672. }
  1673. }
  1674. // partially unmap the file in the range [first, last)
  1675. void unmap_fragment(size_t first, size_t last) {
  1676. // note: this function must not be called multiple times with overlapping ranges
  1677. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1678. int page_size = sysconf(_SC_PAGESIZE);
  1679. align_range(&first, &last, page_size);
  1680. size_t len = last - first;
  1681. if (len == 0) {
  1682. return;
  1683. }
  1684. GGML_ASSERT(first % page_size == 0);
  1685. GGML_ASSERT(last % page_size == 0);
  1686. GGML_ASSERT(last > first);
  1687. void * next_page_start = (uint8_t *) addr + first;
  1688. // unmap the range
  1689. if (munmap(next_page_start, len)) {
  1690. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1691. }
  1692. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1693. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1694. for (const auto & frag : mapped_fragments) {
  1695. if (frag.first < first && frag.second > last) {
  1696. // the range is in the middle of the fragment, split it
  1697. new_mapped_fragments.emplace_back(frag.first, first);
  1698. new_mapped_fragments.emplace_back(last, frag.second);
  1699. } else if (frag.first < first && frag.second > first) {
  1700. // the range starts in the middle of the fragment
  1701. new_mapped_fragments.emplace_back(frag.first, first);
  1702. } else if (frag.first < last && frag.second > last) {
  1703. // the range ends in the middle of the fragment
  1704. new_mapped_fragments.emplace_back(last, frag.second);
  1705. } else if (frag.first >= first && frag.second <= last) {
  1706. // the range covers the entire fragment
  1707. } else {
  1708. // the range is outside the fragment
  1709. new_mapped_fragments.push_back(frag);
  1710. }
  1711. }
  1712. mapped_fragments = std::move(new_mapped_fragments);
  1713. }
  1714. ~llama_mmap() {
  1715. for (const auto & frag : mapped_fragments) {
  1716. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1717. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1718. }
  1719. }
  1720. }
  1721. #elif defined(_WIN32)
  1722. static constexpr bool SUPPORTED = true;
  1723. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1724. GGML_UNUSED(numa);
  1725. size = file->size;
  1726. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1727. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1728. if (hMapping == NULL) {
  1729. DWORD error = GetLastError();
  1730. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1731. }
  1732. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1733. DWORD error = GetLastError();
  1734. CloseHandle(hMapping);
  1735. if (addr == NULL) {
  1736. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1737. }
  1738. if (prefetch > 0) {
  1739. #if _WIN32_WINNT >= 0x602
  1740. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1741. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1742. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1743. // may fail on pre-Windows 8 systems
  1744. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1745. if (pPrefetchVirtualMemory) {
  1746. // advise the kernel to preload the mapped memory
  1747. WIN32_MEMORY_RANGE_ENTRY range;
  1748. range.VirtualAddress = addr;
  1749. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1750. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1751. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1752. llama_format_win_err(GetLastError()).c_str());
  1753. }
  1754. }
  1755. #else
  1756. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1757. #endif
  1758. }
  1759. }
  1760. void unmap_fragment(size_t first, size_t last) {
  1761. // not supported
  1762. GGML_UNUSED(first);
  1763. GGML_UNUSED(last);
  1764. }
  1765. ~llama_mmap() {
  1766. if (!UnmapViewOfFile(addr)) {
  1767. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1768. llama_format_win_err(GetLastError()).c_str());
  1769. }
  1770. }
  1771. #else
  1772. static constexpr bool SUPPORTED = false;
  1773. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1774. GGML_UNUSED(file);
  1775. GGML_UNUSED(prefetch);
  1776. GGML_UNUSED(numa);
  1777. throw std::runtime_error("mmap not supported");
  1778. }
  1779. void unmap_fragment(size_t first, size_t last) {
  1780. GGML_UNUSED(first);
  1781. GGML_UNUSED(last);
  1782. throw std::runtime_error("mmap not supported");
  1783. }
  1784. #endif
  1785. };
  1786. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1787. // Represents some region of memory being locked using mlock or VirtualLock;
  1788. // will automatically unlock on destruction.
  1789. struct llama_mlock {
  1790. void * addr = NULL;
  1791. size_t size = 0;
  1792. bool failed_already = false;
  1793. llama_mlock() {}
  1794. llama_mlock(const llama_mlock &) = delete;
  1795. ~llama_mlock() {
  1796. if (size) {
  1797. raw_unlock(addr, size);
  1798. }
  1799. }
  1800. void init(void * ptr) {
  1801. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1802. addr = ptr;
  1803. }
  1804. void grow_to(size_t target_size) {
  1805. GGML_ASSERT(addr);
  1806. if (failed_already) {
  1807. return;
  1808. }
  1809. size_t granularity = lock_granularity();
  1810. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1811. if (target_size > size) {
  1812. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1813. size = target_size;
  1814. } else {
  1815. failed_already = true;
  1816. }
  1817. }
  1818. }
  1819. #ifdef _POSIX_MEMLOCK_RANGE
  1820. static constexpr bool SUPPORTED = true;
  1821. static size_t lock_granularity() {
  1822. return (size_t) sysconf(_SC_PAGESIZE);
  1823. }
  1824. #ifdef __APPLE__
  1825. #define MLOCK_SUGGESTION \
  1826. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1827. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1828. #else
  1829. #define MLOCK_SUGGESTION \
  1830. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1831. #endif
  1832. bool raw_lock(const void * addr, size_t size) const {
  1833. if (!mlock(addr, size)) {
  1834. return true;
  1835. }
  1836. char* errmsg = std::strerror(errno);
  1837. bool suggest = (errno == ENOMEM);
  1838. // Check if the resource limit is fine after all
  1839. struct rlimit lock_limit;
  1840. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1841. suggest = false;
  1842. }
  1843. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1844. suggest = false;
  1845. }
  1846. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1847. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1848. return false;
  1849. }
  1850. #undef MLOCK_SUGGESTION
  1851. static void raw_unlock(void * addr, size_t size) {
  1852. if (munlock(addr, size)) {
  1853. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1854. }
  1855. }
  1856. #elif defined(_WIN32)
  1857. static constexpr bool SUPPORTED = true;
  1858. static size_t lock_granularity() {
  1859. SYSTEM_INFO si;
  1860. GetSystemInfo(&si);
  1861. return (size_t) si.dwPageSize;
  1862. }
  1863. bool raw_lock(void * ptr, size_t len) const {
  1864. for (int tries = 1; ; tries++) {
  1865. if (VirtualLock(ptr, len)) {
  1866. return true;
  1867. }
  1868. if (tries == 2) {
  1869. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1870. len, size, llama_format_win_err(GetLastError()).c_str());
  1871. return false;
  1872. }
  1873. // It failed but this was only the first try; increase the working
  1874. // set size and try again.
  1875. SIZE_T min_ws_size, max_ws_size;
  1876. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1877. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1878. llama_format_win_err(GetLastError()).c_str());
  1879. return false;
  1880. }
  1881. // Per MSDN: "The maximum number of pages that a process can lock
  1882. // is equal to the number of pages in its minimum working set minus
  1883. // a small overhead."
  1884. // Hopefully a megabyte is enough overhead:
  1885. size_t increment = len + 1048576;
  1886. // The minimum must be <= the maximum, so we need to increase both:
  1887. min_ws_size += increment;
  1888. max_ws_size += increment;
  1889. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1890. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1891. llama_format_win_err(GetLastError()).c_str());
  1892. return false;
  1893. }
  1894. }
  1895. }
  1896. static void raw_unlock(void * ptr, size_t len) {
  1897. if (!VirtualUnlock(ptr, len)) {
  1898. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1899. llama_format_win_err(GetLastError()).c_str());
  1900. }
  1901. }
  1902. #else
  1903. static constexpr bool SUPPORTED = false;
  1904. static size_t lock_granularity() {
  1905. return (size_t) 65536;
  1906. }
  1907. bool raw_lock(const void * addr, size_t len) const {
  1908. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1909. return false;
  1910. }
  1911. static void raw_unlock(const void * addr, size_t len) {}
  1912. #endif
  1913. };
  1914. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1915. // NOTE: avoid ever using this except for building the token_to_piece caches
  1916. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  1917. std::string piece;
  1918. piece.resize(piece.capacity()); // using string internal cache
  1919. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1920. if (n_chars < 0) {
  1921. piece.resize(-n_chars);
  1922. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1923. GGML_ASSERT(check == -n_chars);
  1924. }
  1925. else {
  1926. piece.resize(n_chars);
  1927. }
  1928. return piece;
  1929. }
  1930. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1931. ggml_backend_buffer_type_t buft = nullptr;
  1932. #if defined(GGML_USE_CUDA)
  1933. // host buffers should only be used when data is expected to be copied to/from the GPU
  1934. if (host_buffer) {
  1935. buft = ggml_backend_cuda_host_buffer_type();
  1936. }
  1937. #elif defined(GGML_USE_SYCL)
  1938. if (host_buffer) {
  1939. buft = ggml_backend_sycl_host_buffer_type();
  1940. }
  1941. #elif defined(GGML_USE_CPU_HBM)
  1942. buft = ggml_backend_cpu_hbm_buffer_type();
  1943. #elif defined(GGML_USE_VULKAN)
  1944. if (host_buffer) {
  1945. buft = ggml_backend_vk_host_buffer_type();
  1946. }
  1947. #endif
  1948. if (buft == nullptr) {
  1949. buft = ggml_backend_cpu_buffer_type();
  1950. }
  1951. return buft;
  1952. GGML_UNUSED(host_buffer);
  1953. }
  1954. //
  1955. // globals
  1956. //
  1957. struct llama_state {
  1958. llama_state() {
  1959. #ifdef GGML_USE_METAL
  1960. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1961. #elif defined(GGML_USE_CUDA)
  1962. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1963. #elif defined(GGML_USE_CANN)
  1964. ggml_backend_cann_log_set_callback(log_callback, log_callback_user_data);
  1965. #endif
  1966. }
  1967. // We save the log callback globally
  1968. ggml_log_callback log_callback = llama_log_callback_default;
  1969. void * log_callback_user_data = nullptr;
  1970. };
  1971. static llama_state g_state;
  1972. // available llama models
  1973. enum e_model {
  1974. MODEL_UNKNOWN,
  1975. MODEL_14M,
  1976. MODEL_17M,
  1977. MODEL_22M,
  1978. MODEL_33M,
  1979. MODEL_60M,
  1980. MODEL_70M,
  1981. MODEL_80M,
  1982. MODEL_109M,
  1983. MODEL_137M,
  1984. MODEL_160M,
  1985. MODEL_220M,
  1986. MODEL_250M,
  1987. MODEL_270M,
  1988. MODEL_335M,
  1989. MODEL_410M,
  1990. MODEL_450M,
  1991. MODEL_770M,
  1992. MODEL_780M,
  1993. MODEL_0_5B,
  1994. MODEL_1B,
  1995. MODEL_1_3B,
  1996. MODEL_1_4B,
  1997. MODEL_2B,
  1998. MODEL_2_8B,
  1999. MODEL_3B,
  2000. MODEL_4B,
  2001. MODEL_6B,
  2002. MODEL_6_9B,
  2003. MODEL_7B,
  2004. MODEL_8B,
  2005. MODEL_9B,
  2006. MODEL_11B,
  2007. MODEL_12B,
  2008. MODEL_13B,
  2009. MODEL_14B,
  2010. MODEL_15B,
  2011. MODEL_16B,
  2012. MODEL_20B,
  2013. MODEL_30B,
  2014. MODEL_34B,
  2015. MODEL_35B,
  2016. MODEL_40B,
  2017. MODEL_65B,
  2018. MODEL_70B,
  2019. MODEL_236B,
  2020. MODEL_314B,
  2021. MODEL_SMALL,
  2022. MODEL_MEDIUM,
  2023. MODEL_LARGE,
  2024. MODEL_XL,
  2025. MODEL_A2_7B,
  2026. MODEL_8x7B,
  2027. MODEL_8x22B,
  2028. MODEL_16x12B,
  2029. MODEL_10B_128x3_66B,
  2030. MODEL_57B_A14B,
  2031. MODEL_27B,
  2032. };
  2033. static const size_t kiB = 1024;
  2034. static const size_t MiB = 1024*kiB;
  2035. static const size_t GiB = 1024*MiB;
  2036. struct llama_hparams {
  2037. bool vocab_only;
  2038. bool rope_finetuned;
  2039. bool use_par_res;
  2040. uint32_t n_vocab;
  2041. uint32_t n_ctx_train; // context size the model was trained on
  2042. uint32_t n_embd;
  2043. uint32_t n_layer;
  2044. uint32_t n_rot;
  2045. uint32_t n_swa = 0; // sliding window attention (SWA)
  2046. 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
  2047. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2048. uint32_t n_expert = 0;
  2049. uint32_t n_expert_used = 0;
  2050. uint32_t n_vocab_type = 0; // for BERT-style token types
  2051. uint32_t n_rel_attn_bkts = 0;
  2052. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2053. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2054. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2055. uint32_t n_layer_dense_lead = 0;
  2056. uint32_t n_lora_q = 0;
  2057. uint32_t n_lora_kv = 0;
  2058. uint32_t n_ff_exp = 0;
  2059. uint32_t n_ff_shexp = 0;
  2060. uint32_t n_expert_shared = 0;
  2061. float expert_weights_scale = 0.0;
  2062. float f_norm_eps;
  2063. float f_norm_rms_eps;
  2064. float f_attn_logit_softcapping = 50.0f;
  2065. float f_final_logit_softcapping = 30.0f;
  2066. float rope_attn_factor = 1.0f;
  2067. float rope_freq_base_train;
  2068. float rope_freq_scale_train;
  2069. uint32_t n_ctx_orig_yarn;
  2070. float rope_yarn_log_mul;
  2071. // for State Space Models
  2072. uint32_t ssm_d_conv = 0;
  2073. uint32_t ssm_d_inner = 0;
  2074. uint32_t ssm_d_state = 0;
  2075. uint32_t ssm_dt_rank = 0;
  2076. bool ssm_dt_b_c_rms = false;
  2077. float f_clamp_kqv = 0.0f;
  2078. float f_max_alibi_bias = 0.0f;
  2079. float f_logit_scale = 0.0f;
  2080. bool causal_attn = true;
  2081. bool use_alibi = false;
  2082. bool attn_soft_cap = false;
  2083. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2084. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2085. llama_token dec_start_token_id = -1;
  2086. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2087. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2088. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2089. bool operator!=(const llama_hparams & other) const {
  2090. if (this->vocab_only != other.vocab_only) return true;
  2091. if (this->n_vocab != other.n_vocab) return true;
  2092. if (this->n_ctx_train != other.n_ctx_train) return true;
  2093. if (this->n_embd != other.n_embd) return true;
  2094. if (this->n_layer != other.n_layer) return true;
  2095. if (this->n_rot != other.n_rot) return true;
  2096. if (this->n_swa != other.n_swa) return true;
  2097. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2098. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2099. if (this->n_expert != other.n_expert) return true;
  2100. if (this->n_expert_used != other.n_expert_used) return true;
  2101. if (this->n_head_arr != other.n_head_arr) return true;
  2102. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2103. if (this->n_ff_arr != other.n_ff_arr) return true;
  2104. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2105. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2106. if (this->n_lora_q != other.n_lora_q) return true;
  2107. if (this->n_lora_kv != other.n_lora_kv) return true;
  2108. if (this->n_ff_exp != other.n_ff_exp) return true;
  2109. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2110. if (this->n_expert_shared != other.n_expert_shared) return true;
  2111. if (this->rope_finetuned != other.rope_finetuned) return true;
  2112. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2113. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2114. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2115. if (this->ssm_d_state != other.ssm_d_state) return true;
  2116. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2117. if (this->ssm_dt_b_c_rms != other.ssm_dt_b_c_rms) return true;
  2118. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2119. const float EPSILON = 1e-9f;
  2120. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2121. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2122. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2123. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2124. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2125. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2126. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2127. return false;
  2128. }
  2129. uint32_t n_head(uint32_t il = 0) const {
  2130. if (il < n_layer) {
  2131. return n_head_arr[il];
  2132. }
  2133. GGML_ABORT("fatal error");
  2134. }
  2135. uint32_t n_head_kv(uint32_t il = 0) const {
  2136. if (il < n_layer) {
  2137. return n_head_kv_arr[il];
  2138. }
  2139. GGML_ABORT("fatal error");
  2140. }
  2141. uint32_t n_ff(uint32_t il = 0) const {
  2142. if (il < n_layer) {
  2143. return n_ff_arr[il];
  2144. }
  2145. GGML_ABORT("fatal error");
  2146. }
  2147. uint32_t n_gqa(uint32_t il = 0) const {
  2148. const uint32_t n_head = this->n_head(il);
  2149. const uint32_t n_head_kv = this->n_head_kv(il);
  2150. if (n_head_kv == 0) {
  2151. return 0;
  2152. }
  2153. return n_head/n_head_kv;
  2154. }
  2155. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2156. const uint32_t n_head_kv = this->n_head_kv(il);
  2157. return n_embd_head_k * n_head_kv;
  2158. }
  2159. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2160. const uint32_t n_head_kv = this->n_head_kv(il);
  2161. return n_embd_head_v * n_head_kv;
  2162. }
  2163. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2164. // corresponds to Mamba's conv_states size
  2165. // TODO: maybe support other convolution strides than 1
  2166. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2167. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2168. }
  2169. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2170. // corresponds to Mamba's ssm_states size
  2171. return ssm_d_state * ssm_d_inner;
  2172. }
  2173. };
  2174. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2175. struct llama_cparams {
  2176. uint32_t n_ctx; // context size used during inference
  2177. uint32_t n_batch;
  2178. uint32_t n_ubatch;
  2179. uint32_t n_seq_max;
  2180. uint32_t n_threads; // number of threads to use for generation
  2181. uint32_t n_threads_batch; // number of threads to use for batch processing
  2182. float rope_freq_base;
  2183. float rope_freq_scale;
  2184. uint32_t n_ctx_orig_yarn;
  2185. // These hyperparameters are not exposed in GGUF, because all
  2186. // existing YaRN models use the same values for them.
  2187. float yarn_ext_factor;
  2188. float yarn_attn_factor;
  2189. float yarn_beta_fast;
  2190. float yarn_beta_slow;
  2191. float defrag_thold;
  2192. bool embeddings;
  2193. bool causal_attn;
  2194. bool offload_kqv;
  2195. bool flash_attn;
  2196. enum llama_pooling_type pooling_type;
  2197. ggml_backend_sched_eval_callback cb_eval;
  2198. void * cb_eval_user_data;
  2199. };
  2200. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2201. struct llama_layer {
  2202. // normalization
  2203. struct ggml_tensor * attn_norm;
  2204. struct ggml_tensor * attn_norm_b;
  2205. struct ggml_tensor * attn_norm_2;
  2206. struct ggml_tensor * attn_norm_2_b;
  2207. struct ggml_tensor * attn_q_norm;
  2208. struct ggml_tensor * attn_q_norm_b;
  2209. struct ggml_tensor * attn_k_norm;
  2210. struct ggml_tensor * attn_k_norm_b;
  2211. struct ggml_tensor * attn_out_norm;
  2212. struct ggml_tensor * attn_out_norm_b;
  2213. struct ggml_tensor * attn_q_a_norm;
  2214. struct ggml_tensor * attn_kv_a_norm;
  2215. struct ggml_tensor * attn_sub_norm;
  2216. struct ggml_tensor * attn_post_norm;
  2217. struct ggml_tensor * ffn_sub_norm;
  2218. struct ggml_tensor * attn_norm_cross;
  2219. struct ggml_tensor * attn_norm_enc;
  2220. // attention
  2221. struct ggml_tensor * wq;
  2222. struct ggml_tensor * wk;
  2223. struct ggml_tensor * wv;
  2224. struct ggml_tensor * wo;
  2225. struct ggml_tensor * wqkv;
  2226. struct ggml_tensor * wq_a;
  2227. struct ggml_tensor * wq_b;
  2228. struct ggml_tensor * wkv_a_mqa;
  2229. struct ggml_tensor * wkv_b;
  2230. struct ggml_tensor * wq_cross;
  2231. struct ggml_tensor * wk_cross;
  2232. struct ggml_tensor * wv_cross;
  2233. struct ggml_tensor * wo_cross;
  2234. struct ggml_tensor * wq_enc;
  2235. struct ggml_tensor * wk_enc;
  2236. struct ggml_tensor * wv_enc;
  2237. struct ggml_tensor * wo_enc;
  2238. // attention bias
  2239. struct ggml_tensor * bq;
  2240. struct ggml_tensor * bk;
  2241. struct ggml_tensor * bv;
  2242. struct ggml_tensor * bo;
  2243. struct ggml_tensor * bqkv;
  2244. // relative position bias
  2245. struct ggml_tensor * attn_rel_b;
  2246. struct ggml_tensor * attn_rel_b_enc;
  2247. struct ggml_tensor * attn_rel_b_cross;
  2248. // normalization
  2249. struct ggml_tensor * ffn_norm;
  2250. struct ggml_tensor * ffn_norm_b;
  2251. struct ggml_tensor * ffn_post_norm;
  2252. struct ggml_tensor * layer_out_norm;
  2253. struct ggml_tensor * layer_out_norm_b;
  2254. struct ggml_tensor * ffn_norm_exps;
  2255. struct ggml_tensor * ffn_norm_enc;
  2256. // ff
  2257. struct ggml_tensor * ffn_gate; // w1
  2258. struct ggml_tensor * ffn_down; // w2
  2259. struct ggml_tensor * ffn_up; // w3
  2260. struct ggml_tensor * ffn_gate_enc;
  2261. struct ggml_tensor * ffn_down_enc;
  2262. struct ggml_tensor * ffn_up_enc;
  2263. // ff MoE
  2264. struct ggml_tensor * ffn_gate_inp;
  2265. struct ggml_tensor * ffn_gate_exps;
  2266. struct ggml_tensor * ffn_down_exps;
  2267. struct ggml_tensor * ffn_up_exps ;
  2268. // ff shared expert (shexp)
  2269. struct ggml_tensor * ffn_gate_inp_shexp;
  2270. struct ggml_tensor * ffn_gate_shexp;
  2271. struct ggml_tensor * ffn_down_shexp;
  2272. struct ggml_tensor * ffn_up_shexp;
  2273. // ff bias
  2274. struct ggml_tensor * ffn_gate_b = nullptr;
  2275. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2276. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2277. struct ggml_tensor * ffn_act;
  2278. // mamba proj
  2279. struct ggml_tensor * ssm_in;
  2280. struct ggml_tensor * ssm_x;
  2281. struct ggml_tensor * ssm_dt;
  2282. struct ggml_tensor * ssm_out;
  2283. // mamba
  2284. struct ggml_tensor * ssm_conv1d;
  2285. struct ggml_tensor * ssm_a;
  2286. struct ggml_tensor * ssm_d;
  2287. // mamba bias
  2288. struct ggml_tensor * ssm_conv1d_b;
  2289. struct ggml_tensor * ssm_dt_b;
  2290. // long rope factors
  2291. struct ggml_tensor * rope_long = nullptr;
  2292. struct ggml_tensor * rope_short = nullptr;
  2293. struct ggml_tensor * rope_freqs = nullptr;
  2294. // bitnet scale
  2295. struct ggml_tensor * wq_scale;
  2296. struct ggml_tensor * wk_scale;
  2297. struct ggml_tensor * wv_scale;
  2298. struct ggml_tensor * wo_scale;
  2299. struct ggml_tensor * ffn_gate_scale;
  2300. struct ggml_tensor * ffn_up_scale;
  2301. struct ggml_tensor * ffn_down_scale;
  2302. };
  2303. // very similar to llama_batch,
  2304. // but has more metadata about sequences
  2305. struct llama_ubatch {
  2306. bool equal_seqs;
  2307. // TODO: whole_seqs for embeddings?
  2308. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  2309. uint32_t n_seq_tokens; // tokens per sequence
  2310. uint32_t n_seqs;
  2311. llama_token * token; // [n_tokens]
  2312. float * embd; // [n_embd, n_tokens]
  2313. llama_pos * pos; // [n_tokens]
  2314. int32_t * n_seq_id; // [n_seqs]
  2315. llama_seq_id ** seq_id; // [n_seqs]
  2316. int8_t * output; // [n_tokens]
  2317. };
  2318. struct llama_kv_cell {
  2319. llama_pos pos = -1;
  2320. llama_pos delta = 0;
  2321. int32_t src = -1; // used by recurrent state models to copy states
  2322. int32_t tail = -1;
  2323. std::set<llama_seq_id> seq_id;
  2324. bool has_seq_id(const llama_seq_id & id) const {
  2325. return seq_id.find(id) != seq_id.end();
  2326. }
  2327. bool is_empty() const {
  2328. return seq_id.empty();
  2329. }
  2330. bool is_same_seq(const llama_kv_cell & other) const {
  2331. return seq_id == other.seq_id;
  2332. }
  2333. };
  2334. // ring-buffer of cached KV data
  2335. struct llama_kv_cache {
  2336. bool has_shift = false;
  2337. bool do_defrag = false;
  2338. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2339. bool v_trans = true; // the value tensor is transposed
  2340. // Note: The value of head isn't only used to optimize searching
  2341. // for a free KV slot. llama_decode_internal also uses it, so it
  2342. // cannot be freely changed after a slot has been allocated.
  2343. uint32_t head = 0;
  2344. uint32_t size = 0;
  2345. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2346. // computed before each graph build
  2347. uint32_t n = 0;
  2348. ggml_type type_k = GGML_TYPE_F16;
  2349. ggml_type type_v = GGML_TYPE_F16;
  2350. std::vector<llama_kv_cell> cells;
  2351. std::vector<struct ggml_tensor *> k_l; // per layer
  2352. std::vector<struct ggml_tensor *> v_l;
  2353. std::vector<struct ggml_context *> ctxs;
  2354. std::vector<ggml_backend_buffer_t> bufs;
  2355. size_t total_size() const {
  2356. size_t size = 0;
  2357. for (ggml_backend_buffer_t buf : bufs) {
  2358. size += ggml_backend_buffer_get_size(buf);
  2359. }
  2360. return size;
  2361. }
  2362. ~llama_kv_cache() {
  2363. for (struct ggml_context * ctx : ctxs) {
  2364. ggml_free(ctx);
  2365. }
  2366. for (ggml_backend_buffer_t buf : bufs) {
  2367. ggml_backend_buffer_free(buf);
  2368. }
  2369. }
  2370. };
  2371. struct llama_control_vector {
  2372. std::vector<struct ggml_tensor *> tensors; // per layer
  2373. std::vector<struct ggml_context *> ctxs;
  2374. std::vector<ggml_backend_buffer_t> bufs;
  2375. int32_t layer_start = -1;
  2376. int32_t layer_end = -1;
  2377. struct ggml_tensor * tensor_for(int il) const {
  2378. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2379. return nullptr;
  2380. }
  2381. return tensors[il];
  2382. }
  2383. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2384. ggml_tensor * layer_dir = tensor_for(il);
  2385. if (layer_dir != nullptr) {
  2386. cur = ggml_add(ctx, cur, layer_dir);
  2387. }
  2388. return cur;
  2389. }
  2390. ~llama_control_vector() {
  2391. for (struct ggml_context * ctx : ctxs) {
  2392. ggml_free(ctx);
  2393. }
  2394. for (ggml_backend_buffer_t buf : bufs) {
  2395. ggml_backend_buffer_free(buf);
  2396. }
  2397. }
  2398. };
  2399. struct llama_model {
  2400. e_model type = MODEL_UNKNOWN;
  2401. llm_arch arch = LLM_ARCH_UNKNOWN;
  2402. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2403. std::string name = "n/a";
  2404. llama_hparams hparams = {};
  2405. llama_vocab vocab;
  2406. struct ggml_tensor * tok_embd;
  2407. struct ggml_tensor * type_embd;
  2408. struct ggml_tensor * pos_embd;
  2409. struct ggml_tensor * tok_norm;
  2410. struct ggml_tensor * tok_norm_b;
  2411. struct ggml_tensor * output_norm;
  2412. struct ggml_tensor * output_norm_b;
  2413. struct ggml_tensor * output;
  2414. struct ggml_tensor * output_b;
  2415. struct ggml_tensor * output_norm_enc;
  2416. std::vector<llama_layer> layers;
  2417. llama_split_mode split_mode;
  2418. int main_gpu;
  2419. int n_gpu_layers;
  2420. std::vector<std::string> rpc_servers;
  2421. // gguf metadata
  2422. std::unordered_map<std::string, std::string> gguf_kv;
  2423. // layer -> buffer type mapping
  2424. struct layer_buft {
  2425. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2426. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2427. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2428. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2429. ggml_backend_buffer_type_t buft; // everything else
  2430. };
  2431. layer_buft buft_input;
  2432. layer_buft buft_output;
  2433. std::vector<layer_buft> buft_layer;
  2434. // contexts where the model tensors metadata is stored
  2435. std::vector<struct ggml_context *> ctxs;
  2436. // the model memory buffers for the tensor data
  2437. std::vector<ggml_backend_buffer_t> bufs;
  2438. // model memory mapped files
  2439. llama_mmaps mappings;
  2440. // objects representing data potentially being locked in memory
  2441. llama_mlocks mlock_bufs;
  2442. llama_mlocks mlock_mmaps;
  2443. // for quantize-stats only
  2444. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2445. int64_t t_load_us = 0;
  2446. int64_t t_start_us = 0;
  2447. // keep track of loaded lora adapters
  2448. std::set<struct llama_lora_adapter *> lora_adapters;
  2449. ~llama_model() {
  2450. for (struct ggml_context * ctx : ctxs) {
  2451. ggml_free(ctx);
  2452. }
  2453. for (ggml_backend_buffer_t buf : bufs) {
  2454. #ifdef GGML_USE_CUDA
  2455. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2456. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2457. }
  2458. #endif
  2459. ggml_backend_buffer_free(buf);
  2460. }
  2461. while (!lora_adapters.empty()) {
  2462. llama_lora_adapter_free(*lora_adapters.begin());
  2463. }
  2464. }
  2465. };
  2466. struct llama_sbatch_seq {
  2467. int32_t n_seq_id;
  2468. llama_seq_id * seq_id;
  2469. size_t offset;
  2470. size_t length;
  2471. // helper for smoother batch API transition -- can be deprecated in the future
  2472. llama_seq_id all_seq_id; // used if seq_id == NULL
  2473. };
  2474. // sequence-length-aware batch splitting
  2475. struct llama_sbatch {
  2476. // tokens left in this batch
  2477. size_t n_tokens;
  2478. size_t n_embd;
  2479. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  2480. // sorted indices into the batch
  2481. std::vector<size_t> ids;
  2482. // batch indices of the output
  2483. std::vector<size_t> out_ids;
  2484. std::vector<llama_sbatch_seq> seq;
  2485. const llama_batch * batch = nullptr;
  2486. // buffers for the ubatch
  2487. std::vector<llama_token> ubatch_token;
  2488. std::vector<float> ubatch_embd;
  2489. std::vector<llama_pos> ubatch_pos;
  2490. std::vector<int32_t> ubatch_n_seq_id;
  2491. std::vector<llama_seq_id *> ubatch_seq_id;
  2492. std::vector<int8_t> ubatch_output;
  2493. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false) {
  2494. // clear empty sequences
  2495. // the previous ubatch is assumed to be gone,
  2496. // so nothing should refer to values in these sequences anymore.
  2497. for (size_t i = seq.size(); i-- > 0;) {
  2498. if (seq[i].length == 0) {
  2499. seq.pop_back();
  2500. } else {
  2501. break;
  2502. }
  2503. }
  2504. ubatch_token.resize(!has_embd ? n_ubatch : 0);
  2505. ubatch_embd.resize(has_embd ? n_embd * n_ubatch : 0);
  2506. ubatch_pos.resize(n_ubatch);
  2507. ubatch_n_seq_id.resize(n_ubatch);
  2508. ubatch_seq_id.resize(n_ubatch);
  2509. ubatch_output.resize(n_ubatch);
  2510. llama_ubatch ubatch = {
  2511. /*equal_seqs =*/ true,
  2512. /*n_tokens =*/ 0,
  2513. /*n_seq_tokens =*/ 0,
  2514. /*n_seqs =*/ 0,
  2515. /*token =*/ !has_embd ? ubatch_token.data() : nullptr,
  2516. /*embd =*/ has_embd ? ubatch_embd.data() : nullptr,
  2517. /*pos =*/ ubatch_pos.data(),
  2518. /*n_seq_id =*/ ubatch_n_seq_id.data(),
  2519. /*seq_id =*/ ubatch_seq_id.data(),
  2520. /*output =*/ ubatch_output.data(),
  2521. };
  2522. return ubatch;
  2523. }
  2524. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length) {
  2525. GGML_ASSERT(batch != nullptr);
  2526. GGML_ASSERT(length <= seq.length);
  2527. // Can only add sequences of equal lengths to a batch,
  2528. // otherwise it isn't clear to which sequence a token belongs
  2529. GGML_ASSERT(seq.n_seq_id == 0 || ubatch.n_seqs == 0 || length == (size_t) ubatch.n_tokens / ubatch.n_seqs);
  2530. GGML_ASSERT((seq.n_seq_id != 0) == ubatch.equal_seqs);
  2531. // NOTE: loops are separated for cache-friendliness
  2532. if (batch->token) {
  2533. if (ubatch.equal_seqs) {
  2534. for (size_t i = 0; i < length; ++i) {
  2535. ubatch.token[ubatch.n_tokens + i] = batch->token[ids[seq.offset + i]];
  2536. }
  2537. } else {
  2538. // simple split
  2539. ubatch.token = batch->token + seq.offset;
  2540. }
  2541. } else {
  2542. ubatch.token = nullptr;
  2543. }
  2544. if (batch->embd) {
  2545. if (ubatch.equal_seqs) {
  2546. for (size_t i = 0; i < length; ++i) {
  2547. memcpy(
  2548. ubatch.embd + n_embd * (ubatch.n_tokens + i),
  2549. batch->embd + n_embd * ids[seq.offset + i],
  2550. n_embd * sizeof(float)
  2551. );
  2552. }
  2553. } else {
  2554. // simple split
  2555. ubatch.embd = batch->embd + (n_embd * seq.offset);
  2556. }
  2557. } else {
  2558. ubatch.embd = nullptr;
  2559. }
  2560. // from here on, the else branches are deprecated;
  2561. // they are helpers for smoother batch API transition
  2562. if (batch->pos) {
  2563. if (ubatch.equal_seqs) {
  2564. for (size_t i = 0; i < length; ++i) {
  2565. ubatch.pos[ubatch.n_tokens + i] = batch->pos[ids[seq.offset + i]];
  2566. }
  2567. } else {
  2568. // simple split
  2569. ubatch.pos = batch->pos + seq.offset;
  2570. }
  2571. } else {
  2572. for (size_t i = 0; i < length; ++i) {
  2573. llama_pos bi = ids[seq.offset + i];
  2574. ubatch.pos[ubatch.n_tokens + i] = batch->all_pos_0 + (bi * batch->all_pos_1);
  2575. }
  2576. }
  2577. if (ubatch.equal_seqs) {
  2578. ubatch.n_seq_id[ubatch.n_seqs] = seq.n_seq_id;
  2579. if (seq.seq_id) {
  2580. ubatch.seq_id[ubatch.n_seqs] = seq.seq_id;
  2581. } else {
  2582. GGML_ASSERT(seq.n_seq_id == 1);
  2583. ubatch.seq_id[ubatch.n_seqs] = &seq.all_seq_id;
  2584. }
  2585. } else {
  2586. // simple split
  2587. if (batch->n_seq_id) {
  2588. for (size_t i = 0; i < length; ++i) {
  2589. ubatch.n_seq_id = batch->n_seq_id + seq.offset;
  2590. }
  2591. } else {
  2592. for (size_t i = 0; i < length; ++i) {
  2593. ubatch.n_seq_id[ubatch.n_seqs + i] = 1;
  2594. }
  2595. }
  2596. if (batch->seq_id) {
  2597. for (size_t i = 0; i < length; ++i) {
  2598. ubatch.seq_id = batch->seq_id + seq.offset;
  2599. }
  2600. } else {
  2601. for (size_t i = 0; i < length; ++i) {
  2602. ubatch.seq_id[ubatch.n_seqs + i] = &seq.all_seq_id;
  2603. }
  2604. }
  2605. }
  2606. if (logits_all) {
  2607. for (size_t i = 0; i < length; ++i) {
  2608. ubatch.output[ubatch.n_tokens + i] = 1;
  2609. out_ids.push_back(ids[seq.offset + i]);
  2610. }
  2611. } else if (batch->logits) {
  2612. if (ubatch.equal_seqs) {
  2613. for (size_t i = 0; i < length; ++i) {
  2614. size_t id = ids[seq.offset + i];
  2615. int8_t is_output = batch->logits[id];
  2616. ubatch.output[ubatch.n_tokens + i] = is_output;
  2617. if (is_output) { out_ids.push_back(id); }
  2618. }
  2619. } else {
  2620. // simple split
  2621. ubatch.output = batch->logits + seq.offset;
  2622. for (size_t i = 0; i < length; ++i) {
  2623. if (ubatch.output[i] != 0) { out_ids.push_back(seq.offset + i); }
  2624. }
  2625. }
  2626. } else {
  2627. // only get last output
  2628. for (size_t i = 0; i < length; ++i) {
  2629. size_t id = ids[seq.offset + i];
  2630. int8_t is_last = id == ids.size() - 1;
  2631. ubatch.output[ubatch.n_tokens + i] = is_last;
  2632. if (is_last) { out_ids.push_back(id); }
  2633. }
  2634. }
  2635. if (ubatch.n_tokens == 0 && ubatch.n_seqs == 0) {
  2636. ubatch.n_seq_tokens = ubatch.equal_seqs ? length : 1;
  2637. }
  2638. ubatch.n_tokens += length;
  2639. ubatch.n_seqs += ubatch.equal_seqs ? 1 : length; // virtual sequences for simple splits
  2640. seq.offset += length;
  2641. seq.length -= length;
  2642. n_tokens -= length;
  2643. GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens * ubatch.n_seqs);
  2644. }
  2645. // simple split, unknown number of sequences of unequal lengths
  2646. llama_ubatch split_simple(size_t n_ubatch) {
  2647. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2648. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2649. ubatch.equal_seqs = false;
  2650. if (!seq.empty()) {
  2651. llama_sbatch_seq & s = seq[0];
  2652. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  2653. GGML_ASSERT(seq.size() == 1 && s.n_seq_id == 0); // don't mix with other splits
  2654. add_seq_to_ubatch(ubatch, s, length);
  2655. }
  2656. return ubatch;
  2657. }
  2658. // make batches of equal-length sequences
  2659. llama_ubatch split_equal(size_t n_ubatch) {
  2660. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2661. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2662. if (!seq.empty()) {
  2663. size_t length = 0;
  2664. size_t n_tokens_in_ubatch = 0;
  2665. GGML_ASSERT(seq[0].n_seq_id > 0); // should not be mixed with simple splits
  2666. // smallest first, because it's easier to split this way;
  2667. // starting from the end to pop in constant time.
  2668. for (size_t i = seq.size(); i-- > 0;) {
  2669. llama_sbatch_seq & s = seq[i];
  2670. GGML_ASSERT(s.length > 0);
  2671. if (length == 0) {
  2672. length = s.length < n_ubatch ? s.length : n_ubatch;
  2673. }
  2674. add_seq_to_ubatch(ubatch, s, length);
  2675. n_tokens_in_ubatch += length;
  2676. // shared prompts can't be mixed with any of their sequences,
  2677. // so it's safer to compute them in their own ubatch
  2678. if (s.n_seq_id > 1) { break; }
  2679. // stop when there isn't enough space for another sequence
  2680. if (length + n_tokens_in_ubatch > n_ubatch) { break; }
  2681. }
  2682. }
  2683. return ubatch;
  2684. }
  2685. // sequence-wise split
  2686. llama_ubatch split_seq(size_t n_ubatch) {
  2687. n_ubatch = n_tokens < n_ubatch ? n_tokens : n_ubatch;
  2688. llama_ubatch ubatch = reserve_ubatch(n_ubatch, /* has_embd */ batch->embd != nullptr);
  2689. if (!seq.empty()) {
  2690. llama_sbatch_seq & s = seq[seq.size() - 1];
  2691. size_t length = s.length < n_ubatch ? s.length : n_ubatch;
  2692. GGML_ASSERT(s.n_seq_id > 0); // should not be mixed with simple splits
  2693. add_seq_to_ubatch(ubatch, s, length);
  2694. }
  2695. return ubatch;
  2696. }
  2697. void from_batch(const llama_batch & batch, const size_t n_embd, const bool simple_split = false, const bool logits_all = false) {
  2698. GGML_ASSERT(batch.n_tokens >= 0);
  2699. this->batch = &batch;
  2700. this->n_embd = n_embd;
  2701. this->logits_all = logits_all;
  2702. n_tokens = batch.n_tokens;
  2703. ids.resize(n_tokens);
  2704. out_ids.clear();
  2705. // TODO: reserve out_ids and seq
  2706. for (size_t i = 0; i < n_tokens; ++i) {
  2707. ids[i] = i;
  2708. }
  2709. if (simple_split) {
  2710. seq.resize(1);
  2711. llama_sbatch_seq & s = seq[0];
  2712. s.n_seq_id = 0;
  2713. s.seq_id = nullptr;
  2714. s.offset = 0;
  2715. s.length = n_tokens;
  2716. s.all_seq_id = batch.all_seq_id;
  2717. return;
  2718. }
  2719. std::sort(ids.begin(), ids.end(),
  2720. [&batch](size_t a, size_t b) {
  2721. int32_t n_seq_a = batch.n_seq_id ? batch.n_seq_id[a] : 1;
  2722. int32_t n_seq_b = batch.n_seq_id ? batch.n_seq_id[b] : 1;
  2723. // sort by seq_id, then by pos
  2724. if (n_seq_a == n_seq_b) {
  2725. if (batch.seq_id) {
  2726. for (int32_t i = 0; i < n_seq_a; ++i) {
  2727. llama_seq_id seq_id_a = batch.seq_id[a][i];
  2728. llama_seq_id seq_id_b = batch.seq_id[b][i];
  2729. // smaller seq_ids go first
  2730. if (seq_id_a != seq_id_b) {
  2731. return seq_id_a < seq_id_b;
  2732. }
  2733. }
  2734. }
  2735. // when all else is equal, sort by pos
  2736. if (batch.pos) {
  2737. return batch.pos[a] < batch.pos[b];
  2738. }
  2739. // no pos, sort by id (assuming batch.all_pos_1 is positive)
  2740. return a < b;
  2741. }
  2742. // shared prompts go first
  2743. return n_seq_a > n_seq_b;
  2744. }
  2745. );
  2746. // init seq
  2747. llama_sbatch_seq * last_seq = nullptr;
  2748. if (batch.n_seq_id != nullptr && batch.seq_id != nullptr) {
  2749. for (size_t i = 0; i < n_tokens; ++i) {
  2750. const size_t bi = ids[i];
  2751. const int32_t n_seqs = batch.n_seq_id[bi];
  2752. llama_seq_id * seq_ids = batch.seq_id[bi];
  2753. if (last_seq != nullptr) {
  2754. bool same = n_seqs == last_seq->n_seq_id;
  2755. for (int32_t j = 0; same && j < n_seqs; ++j) {
  2756. if (seq_ids[j] != last_seq->seq_id[j]) {
  2757. same = false;
  2758. }
  2759. }
  2760. if (same) {
  2761. last_seq->length += 1;
  2762. continue;
  2763. }
  2764. }
  2765. llama_sbatch_seq new_seq = {n_seqs, seq_ids, i, 1, batch.all_seq_id};
  2766. seq.push_back(new_seq);
  2767. last_seq = &seq.back();
  2768. }
  2769. } else {
  2770. llama_sbatch_seq new_seq = {1, nullptr, 0, n_tokens, batch.all_seq_id};
  2771. seq.push_back(new_seq);
  2772. }
  2773. // keep shared prompts first at the end, then sort by length descending.
  2774. std::sort(seq.begin(), seq.end(),
  2775. [](llama_sbatch_seq & a, llama_sbatch_seq & b) {
  2776. if (a.n_seq_id == b.n_seq_id) {
  2777. return a.length > b.length;
  2778. }
  2779. return a.n_seq_id < b.n_seq_id;
  2780. }
  2781. );
  2782. }
  2783. };
  2784. struct llama_context {
  2785. llama_context(const llama_model & model)
  2786. : model(model)
  2787. , sampling(llama_n_vocab(&model))
  2788. , t_start_us(model.t_start_us)
  2789. , t_load_us(model.t_load_us) {}
  2790. ~llama_context() {
  2791. ggml_backend_sched_free(sched);
  2792. for (ggml_backend_t backend : backends) {
  2793. ggml_backend_free(backend);
  2794. }
  2795. ggml_backend_buffer_free(buf_output);
  2796. }
  2797. const struct llama_model & model;
  2798. struct llama_cparams cparams;
  2799. struct llama_sampling sampling;
  2800. struct llama_sbatch sbatch;
  2801. struct llama_kv_cache kv_self;
  2802. struct llama_control_vector cvec;
  2803. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  2804. std::vector<ggml_backend_t> backends;
  2805. #ifdef GGML_USE_METAL
  2806. ggml_backend_t backend_metal = nullptr;
  2807. #endif
  2808. #ifdef GGML_USE_BLAS
  2809. ggml_backend_t backend_blas = nullptr;
  2810. #endif
  2811. ggml_backend_t backend_cpu = nullptr;
  2812. bool has_evaluated_once = false;
  2813. int64_t t_start_us;
  2814. int64_t t_load_us;
  2815. int64_t t_p_eval_us = 0;
  2816. int64_t t_eval_us = 0;
  2817. int64_t t_compute_start_us = 0;
  2818. int64_t n_queued_tokens = 0;
  2819. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  2820. int32_t n_eval = 0; // number of eval calls
  2821. // host buffer for the model output (logits and embeddings)
  2822. ggml_backend_buffer_t buf_output = nullptr;
  2823. // decode output (2-dimensional array: [n_outputs][n_vocab])
  2824. size_t logits_size = 0; // capacity (of floats) for logits
  2825. float * logits = nullptr;
  2826. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  2827. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  2828. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  2829. bool logits_all = false;
  2830. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  2831. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  2832. size_t embd_size = 0; // capacity (of floats) for embeddings
  2833. float * embd = nullptr;
  2834. // sequence embeddings output (map of [n_embd] vectors)
  2835. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2836. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2837. // whether we are computing encoder output or decoder output
  2838. bool is_encoding = false;
  2839. // output of the encoder part of the encoder-decoder models
  2840. std::vector<float> embd_enc;
  2841. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  2842. // memory buffers used to evaluate the model
  2843. std::vector<uint8_t> buf_compute_meta;
  2844. ggml_backend_sched_t sched = nullptr;
  2845. ggml_abort_callback abort_callback = nullptr;
  2846. void * abort_callback_data = nullptr;
  2847. // input tensors
  2848. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2849. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2850. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2851. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2852. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2853. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  2854. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2855. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2856. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2857. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2858. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2859. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2860. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  2861. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  2862. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  2863. };
  2864. struct llama_lora_weight {
  2865. struct ggml_tensor * a = nullptr;
  2866. struct ggml_tensor * b = nullptr;
  2867. llama_lora_weight() = default;
  2868. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  2869. };
  2870. struct llama_lora_adapter {
  2871. struct llama_model * base_model;
  2872. // map tensor name to lora_a_b
  2873. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  2874. std::vector<struct ggml_context *> ctxs;
  2875. std::vector<ggml_backend_buffer_t> bufs;
  2876. float alpha;
  2877. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  2878. base_model->lora_adapters.insert(this);
  2879. }
  2880. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  2881. std::string name(w->name);
  2882. auto pos = ab_map.find(name);
  2883. if (ab_map.find(name) != ab_map.end()) {
  2884. return &pos->second;
  2885. }
  2886. return nullptr;
  2887. }
  2888. ~llama_lora_adapter() {
  2889. for (struct ggml_context * ctx : ctxs) {
  2890. ggml_free(ctx);
  2891. }
  2892. for (ggml_backend_buffer_t buf : bufs) {
  2893. ggml_backend_buffer_free(buf);
  2894. }
  2895. auto pos = base_model->lora_adapters.find(this);
  2896. if (pos != base_model->lora_adapters.end()) {
  2897. base_model->lora_adapters.erase(pos);
  2898. }
  2899. }
  2900. };
  2901. static size_t llama_get_device_count(const llama_model & model) {
  2902. size_t count = 1;
  2903. #if defined(GGML_USE_CUDA)
  2904. count = ggml_backend_cuda_get_device_count();
  2905. #elif defined(GGML_USE_SYCL)
  2906. count = ggml_backend_sycl_get_device_count();
  2907. #elif defined(GGML_USE_VULKAN)
  2908. count = ggml_backend_vk_get_device_count();
  2909. #elif defined(GGML_USE_CANN)
  2910. return ggml_backend_cann_get_device_count();
  2911. #endif
  2912. #if defined(GGML_USE_RPC)
  2913. count += model.rpc_servers.size();
  2914. #endif
  2915. return count;
  2916. GGML_UNUSED(model);
  2917. }
  2918. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2919. ggml_backend_buffer_type_t buft = nullptr;
  2920. #if defined(GGML_USE_RPC)
  2921. int dev_count = (int)llama_get_device_count(model);
  2922. int rpc_count = (int)model.rpc_servers.size();
  2923. if (gpu >= dev_count - rpc_count) {
  2924. const char * endpoint = model.rpc_servers[gpu - dev_count + rpc_count].c_str();
  2925. return ggml_backend_rpc_buffer_type(endpoint);
  2926. }
  2927. #endif
  2928. #if defined(GGML_USE_METAL)
  2929. buft = ggml_backend_metal_buffer_type();
  2930. #elif defined(GGML_USE_CUDA)
  2931. buft = ggml_backend_cuda_buffer_type(gpu);
  2932. #elif defined(GGML_USE_VULKAN)
  2933. buft = ggml_backend_vk_buffer_type(gpu);
  2934. #elif defined(GGML_USE_SYCL)
  2935. buft = ggml_backend_sycl_buffer_type(gpu);
  2936. #elif defined(GGML_USE_KOMPUTE)
  2937. buft = ggml_backend_kompute_buffer_type(gpu);
  2938. if (buft == nullptr) {
  2939. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2940. }
  2941. #elif defined(GGML_USE_CANN)
  2942. buft = ggml_backend_cann_buffer_type(gpu);
  2943. #endif
  2944. if (buft == nullptr) {
  2945. buft = llama_default_buffer_type_cpu(true);
  2946. }
  2947. return buft;
  2948. GGML_UNUSED(model);
  2949. GGML_UNUSED(gpu);
  2950. }
  2951. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2952. ggml_backend_buffer_type_t buft = nullptr;
  2953. #ifdef GGML_USE_CUDA
  2954. if (ggml_backend_cuda_get_device_count() > 1) {
  2955. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2956. }
  2957. #endif
  2958. #ifdef GGML_USE_SYCL
  2959. if (ggml_backend_sycl_get_device_count() > 1) {
  2960. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2961. }
  2962. #endif
  2963. if (buft == nullptr) {
  2964. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2965. }
  2966. return buft;
  2967. GGML_UNUSED(tensor_split);
  2968. }
  2969. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2970. #if defined(GGML_USE_RPC)
  2971. int dev_count = (int)llama_get_device_count(model);
  2972. int rpc_count = (int)model.rpc_servers.size();
  2973. if (device >= dev_count - rpc_count) {
  2974. size_t total;
  2975. size_t free;
  2976. const char * endpoint = model.rpc_servers[device - dev_count + rpc_count].c_str();
  2977. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  2978. return free;
  2979. }
  2980. #endif
  2981. #if defined(GGML_USE_CUDA)
  2982. size_t total;
  2983. size_t free;
  2984. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2985. return free;
  2986. #elif defined(GGML_USE_SYCL)
  2987. size_t total;
  2988. size_t free;
  2989. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2990. return free;
  2991. #elif defined(GGML_USE_VULKAN)
  2992. size_t total;
  2993. size_t free;
  2994. ggml_backend_vk_get_device_memory(device, &free, &total);
  2995. return free;
  2996. #elif defined(GGML_USE_CANN)
  2997. size_t total;
  2998. size_t free;
  2999. ggml_backend_cann_get_device_memory(device, &free, &total);
  3000. return free;
  3001. #else
  3002. return 1;
  3003. #endif
  3004. GGML_UNUSED(model);
  3005. GGML_UNUSED(device);
  3006. }
  3007. //
  3008. // kv cache helpers
  3009. //
  3010. static bool llama_kv_cache_init(
  3011. struct llama_kv_cache & cache,
  3012. const llama_context * ctx,
  3013. ggml_type type_k,
  3014. ggml_type type_v,
  3015. uint32_t kv_size,
  3016. bool offload) {
  3017. const llama_model & model = ctx->model;
  3018. const llama_cparams & cparams = ctx->cparams;
  3019. const struct llama_hparams & hparams = model.hparams;
  3020. const int64_t n_layer = hparams.n_layer;
  3021. cache.has_shift = false;
  3022. cache.recurrent = llama_model_is_recurrent(&model);
  3023. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  3024. cache.head = 0;
  3025. cache.size = kv_size;
  3026. cache.used = 0;
  3027. cache.type_k = type_k;
  3028. cache.type_v = type_v;
  3029. cache.cells.clear();
  3030. cache.cells.resize(kv_size);
  3031. // count used buffer types
  3032. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3033. if (offload) {
  3034. for (int64_t i = 0; i < n_layer; ++i) {
  3035. buft_layer_count[model.buft_layer[i].buft]++;
  3036. }
  3037. } else {
  3038. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  3039. }
  3040. // create a context for each buffer type
  3041. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3042. for (auto & it : buft_layer_count) {
  3043. int n_layers = it.second;
  3044. struct ggml_init_params params = {
  3045. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  3046. /*.mem_buffer =*/ NULL,
  3047. /*.no_alloc =*/ true,
  3048. };
  3049. ggml_context * ctx = ggml_init(params);
  3050. if (!ctx) {
  3051. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  3052. return false;
  3053. }
  3054. ctx_map[it.first] = ctx;
  3055. cache.ctxs.push_back(ctx);
  3056. }
  3057. cache.k_l.reserve(n_layer);
  3058. cache.v_l.reserve(n_layer);
  3059. for (int i = 0; i < (int) n_layer; i++) {
  3060. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  3061. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  3062. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  3063. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  3064. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  3065. ggml_format_name(k, "cache_k_l%d", i);
  3066. ggml_format_name(v, "cache_v_l%d", i);
  3067. cache.k_l.push_back(k);
  3068. cache.v_l.push_back(v);
  3069. }
  3070. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  3071. for (auto it : ctx_map) {
  3072. ggml_backend_buffer_type_t buft = it.first;
  3073. ggml_context * ctx = it.second;
  3074. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3075. if (!buf) {
  3076. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  3077. return false;
  3078. }
  3079. ggml_backend_buffer_clear(buf, 0);
  3080. 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);
  3081. cache.bufs.push_back(buf);
  3082. }
  3083. return true;
  3084. }
  3085. // find an empty slot of size "n_tokens" in the cache
  3086. // updates the cache head
  3087. // Note: On success, it's important that cache.head points
  3088. // to the first cell of the slot.
  3089. static bool llama_kv_cache_find_slot(
  3090. struct llama_kv_cache & cache,
  3091. const struct llama_ubatch & batch) {
  3092. const uint32_t n_tokens = batch.n_tokens;
  3093. const uint32_t n_seqs = batch.n_seqs;
  3094. const uint32_t n_seq_tokens = batch.n_seq_tokens;
  3095. if (cache.recurrent) {
  3096. // For recurrent state architectures (like Mamba),
  3097. // each cache cell can store the state for a whole sequence.
  3098. // A slot should be always be contiguous.
  3099. // can only process batches with an equal number of new tokens in each sequence
  3100. GGML_ASSERT(batch.equal_seqs);
  3101. int32_t min = cache.size - 1;
  3102. int32_t max = 0;
  3103. // everything should fit if all seq_ids are smaller than the max
  3104. for (uint32_t s = 0; s < n_seqs; ++s) {
  3105. const uint32_t n_seq_id = batch.n_seq_id[s];
  3106. for (uint32_t j = 0; j < n_seq_id; ++j) {
  3107. const llama_seq_id seq_id = batch.seq_id[s][j];
  3108. if (seq_id < 0 || (uint32_t) seq_id >= cache.size) {
  3109. // too big seq_id
  3110. // TODO: would it be possible to resize the cache instead?
  3111. LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  3112. return false;
  3113. }
  3114. if (j > 0) {
  3115. llama_kv_cell & seq = cache.cells[seq_id];
  3116. if (seq.tail >= 0) {
  3117. llama_kv_cell & cell = cache.cells[seq.tail];
  3118. // clear cells from seq_ids that become shared
  3119. // (should not normally happen, but let's handle it anyway)
  3120. cell.seq_id.erase(seq_id);
  3121. seq.tail = -1;
  3122. if (cell.seq_id.empty()) {
  3123. cell.pos = -1;
  3124. cell.src = -1;
  3125. cache.used -= 1;
  3126. }
  3127. }
  3128. }
  3129. }
  3130. }
  3131. #ifndef NDEBUG
  3132. {
  3133. std::vector<int32_t> tails_verif;
  3134. tails_verif.assign(cache.size, -1);
  3135. for (uint32_t i = 0; i < cache.size; ++i) {
  3136. llama_kv_cell & cell = cache.cells[i];
  3137. for (llama_seq_id seq_id : cell.seq_id) {
  3138. if (tails_verif[seq_id] != -1) {
  3139. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
  3140. }
  3141. tails_verif[seq_id] = i;
  3142. }
  3143. }
  3144. for (uint32_t i = 0; i < cache.size; ++i) {
  3145. if (tails_verif[i] != cache.cells[i].tail) {
  3146. LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cache.cells[i].tail, tails_verif[i]);
  3147. }
  3148. }
  3149. }
  3150. #endif
  3151. // find next empty cell
  3152. uint32_t next_empty_cell = cache.head;
  3153. for (uint32_t i = 0; i < cache.size; ++i) {
  3154. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3155. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3156. if (cell.is_empty()) { break; }
  3157. next_empty_cell += 1;
  3158. }
  3159. // find usable cell range
  3160. for (uint32_t s = 0; s < n_seqs; ++s) {
  3161. const llama_seq_id seq_id = batch.seq_id[s][0];
  3162. llama_kv_cell & seq_meta = cache.cells[seq_id];
  3163. bool has_cell = false;
  3164. if (seq_meta.tail >= 0) {
  3165. llama_kv_cell & cell = cache.cells[seq_meta.tail];
  3166. GGML_ASSERT(cell.has_seq_id(seq_id));
  3167. // does this seq_id "own" the cell?
  3168. if (cell.seq_id.size() == 1) { has_cell = true; }
  3169. }
  3170. if (!has_cell) {
  3171. llama_kv_cell & empty_cell = cache.cells[next_empty_cell];
  3172. GGML_ASSERT(empty_cell.is_empty());
  3173. // copy old tail into the empty cell
  3174. if (seq_meta.tail >= 0) {
  3175. llama_kv_cell & orig_cell = cache.cells[seq_meta.tail];
  3176. empty_cell.pos = orig_cell.pos;
  3177. empty_cell.src = orig_cell.src;
  3178. orig_cell.seq_id.erase(seq_id);
  3179. empty_cell.seq_id.insert(seq_id); // will be overwritten
  3180. }
  3181. seq_meta.tail = next_empty_cell;
  3182. // find next empty cell
  3183. if (s + 1 < n_seqs) {
  3184. next_empty_cell += 1;
  3185. for (uint32_t i = 0; i < cache.size; ++i) {
  3186. if (next_empty_cell >= cache.size) { next_empty_cell -= cache.size; }
  3187. llama_kv_cell & cell = cache.cells[next_empty_cell];
  3188. if (cell.is_empty()) { break; }
  3189. next_empty_cell += 1;
  3190. }
  3191. }
  3192. }
  3193. if (min > seq_meta.tail) { min = seq_meta.tail; }
  3194. if (max < seq_meta.tail) { max = seq_meta.tail; }
  3195. }
  3196. // gather and re-order
  3197. for (uint32_t s = 0; s < n_seqs; ++s) {
  3198. int32_t dst_id = s + min;
  3199. int32_t src_id = cache.cells[batch.seq_id[s][0]].tail;
  3200. if (dst_id != src_id) {
  3201. llama_kv_cell & dst_cell = cache.cells[dst_id];
  3202. llama_kv_cell & src_cell = cache.cells[src_id];
  3203. std::swap(dst_cell.pos, src_cell.pos);
  3204. std::swap(dst_cell.src, src_cell.src);
  3205. std::swap(dst_cell.seq_id, src_cell.seq_id);
  3206. // swap tails (assuming they NEVER overlap)
  3207. for (const llama_seq_id seq_id : src_cell.seq_id) {
  3208. cache.cells[seq_id].tail = src_id;
  3209. }
  3210. for (const llama_seq_id seq_id : dst_cell.seq_id) {
  3211. cache.cells[seq_id].tail = dst_id;
  3212. }
  3213. }
  3214. }
  3215. // update the pos of the used seqs
  3216. for (uint32_t s = 0; s < n_seqs; ++s) {
  3217. const llama_pos last_pos = batch.pos[n_seq_tokens * s + n_seq_tokens - 1];
  3218. int32_t cell_id = s + min;
  3219. llama_kv_cell & cell = cache.cells[cell_id];
  3220. if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
  3221. // What should happen when the pos backtracks or skips a value?
  3222. // Clearing the state mid-batch would require special-casing which isn't done.
  3223. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
  3224. __func__, last_pos, cell.pos, batch.seq_id[s][0], n_seq_tokens);
  3225. }
  3226. cell.pos = last_pos;
  3227. cell.seq_id.clear();
  3228. for (int32_t j = 0; j < batch.n_seq_id[s]; ++j) {
  3229. const llama_seq_id seq_id = batch.seq_id[s][j];
  3230. cell.seq_id.insert(seq_id);
  3231. cache.cells[seq_id].tail = cell_id;
  3232. }
  3233. }
  3234. // allow getting the range of used cells, from head to head + n
  3235. cache.head = min;
  3236. cache.n = max - min + 1;
  3237. // sanity check
  3238. return cache.n >= n_seqs;
  3239. }
  3240. // otherwise, one cell per token.
  3241. if (n_tokens > cache.size) {
  3242. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  3243. return false;
  3244. }
  3245. uint32_t n_tested = 0;
  3246. while (true) {
  3247. if (cache.head + n_tokens > cache.size) {
  3248. n_tested += cache.size - cache.head;
  3249. cache.head = 0;
  3250. continue;
  3251. }
  3252. bool found = true;
  3253. for (uint32_t i = 0; i < n_tokens; i++) {
  3254. if (cache.cells[cache.head + i].pos >= 0) {
  3255. found = false;
  3256. cache.head += i + 1;
  3257. n_tested += i + 1;
  3258. break;
  3259. }
  3260. }
  3261. if (found) {
  3262. break;
  3263. }
  3264. if (n_tested >= cache.size) {
  3265. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  3266. return false;
  3267. }
  3268. }
  3269. for (uint32_t s = 0; s < n_seqs; s++) {
  3270. for (uint32_t i = 0; i < n_seq_tokens; ++i) {
  3271. uint32_t k = s*n_seq_tokens + i;
  3272. cache.cells[cache.head + k].pos = batch.pos[k];
  3273. for (int32_t j = 0; j < batch.n_seq_id[s]; j++) {
  3274. cache.cells[cache.head + k].seq_id.insert(batch.seq_id[s][j]);
  3275. }
  3276. }
  3277. }
  3278. cache.used += n_tokens;
  3279. return true;
  3280. }
  3281. // find how many cells are currently in use
  3282. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  3283. for (uint32_t i = cache.size; i > 0; --i) {
  3284. const llama_kv_cell & cell = cache.cells[i - 1];
  3285. if (cell.pos >= 0 && !cell.is_empty()) {
  3286. return i;
  3287. }
  3288. }
  3289. return 0;
  3290. }
  3291. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  3292. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  3293. cache.cells[i].pos = -1;
  3294. cache.cells[i].seq_id.clear();
  3295. cache.cells[i].src = -1;
  3296. cache.cells[i].tail = -1;
  3297. }
  3298. cache.head = 0;
  3299. cache.used = 0;
  3300. for (auto & buf : cache.bufs) {
  3301. ggml_backend_buffer_clear(buf, 0);
  3302. }
  3303. }
  3304. static bool llama_kv_cache_seq_rm(
  3305. struct llama_kv_cache & cache,
  3306. llama_seq_id seq_id,
  3307. llama_pos p0,
  3308. llama_pos p1) {
  3309. uint32_t new_head = cache.size;
  3310. if (p0 < 0) p0 = 0;
  3311. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3312. // models like Mamba can't have a state partially erased
  3313. if (cache.recurrent) {
  3314. if (seq_id >= (int64_t) cache.size) {
  3315. // could be fatal
  3316. return false;
  3317. }
  3318. if (0 <= seq_id) {
  3319. int32_t & tail_id = cache.cells[seq_id].tail;
  3320. if (tail_id >= 0) {
  3321. const llama_kv_cell & cell = cache.cells[tail_id];
  3322. // partial intersection is invalid
  3323. if ((0 < p0 && p0 <= cell.pos) || (0 < p1 && p1 <= cell.pos)) {
  3324. return false;
  3325. }
  3326. if (p0 <= cell.pos && p1 < cell.pos) {
  3327. tail_id = -1;
  3328. }
  3329. }
  3330. } else {
  3331. // seq_id is negative, then the range should include everything or nothing
  3332. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  3333. return false;
  3334. }
  3335. }
  3336. }
  3337. for (uint32_t i = 0; i < cache.size; ++i) {
  3338. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3339. if (seq_id < 0) {
  3340. cache.cells[i].seq_id.clear();
  3341. } else if (cache.cells[i].has_seq_id(seq_id)) {
  3342. cache.cells[i].seq_id.erase(seq_id);
  3343. } else {
  3344. continue;
  3345. }
  3346. if (cache.cells[i].is_empty()) {
  3347. // keep count of the number of used cells
  3348. if (cache.cells[i].pos >= 0) cache.used--;
  3349. cache.cells[i].pos = -1;
  3350. cache.cells[i].src = -1;
  3351. if (new_head == cache.size) new_head = i;
  3352. }
  3353. }
  3354. }
  3355. // If we freed up a slot, set head to it so searching can start there.
  3356. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3357. return true;
  3358. }
  3359. static void llama_kv_cache_seq_cp(
  3360. struct llama_kv_cache & cache,
  3361. llama_seq_id seq_id_src,
  3362. llama_seq_id seq_id_dst,
  3363. llama_pos p0,
  3364. llama_pos p1) {
  3365. if (p0 < 0) p0 = 0;
  3366. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3367. if (cache.recurrent) {
  3368. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  3369. llama_kv_cell & tail_src = cache.cells[seq_id_src];
  3370. llama_kv_cell & tail_dst = cache.cells[seq_id_dst];
  3371. if (tail_dst.tail >= 0) {
  3372. // clear destination seq_id if it wasn't empty
  3373. llama_kv_cell & cell_dst = cache.cells[tail_dst.tail];
  3374. cell_dst.seq_id.erase(seq_id_dst);
  3375. tail_dst.tail = -1;
  3376. if (cell_dst.seq_id.empty()) {
  3377. cell_dst.pos = -1;
  3378. cell_dst.delta = -1;
  3379. cell_dst.src = -1;
  3380. cache.used -= 1;
  3381. }
  3382. }
  3383. if (tail_src.tail >= 0) {
  3384. llama_kv_cell & cell_src = cache.cells[tail_src.tail];
  3385. cell_src.seq_id.insert(seq_id_dst);
  3386. tail_dst.tail = tail_src.tail;
  3387. }
  3388. }
  3389. return;
  3390. }
  3391. // otherwise, this is the KV cache of a Transformer-like model
  3392. cache.head = 0;
  3393. for (uint32_t i = 0; i < cache.size; ++i) {
  3394. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3395. cache.cells[i].seq_id.insert(seq_id_dst);
  3396. }
  3397. }
  3398. }
  3399. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3400. uint32_t new_head = cache.size;
  3401. for (uint32_t i = 0; i < cache.size; ++i) {
  3402. if (cache.recurrent && (llama_seq_id) i != seq_id) {
  3403. cache.cells[i].tail = -1;
  3404. }
  3405. if (!cache.cells[i].has_seq_id(seq_id)) {
  3406. if (cache.cells[i].pos >= 0) cache.used--;
  3407. cache.cells[i].pos = -1;
  3408. cache.cells[i].src = -1;
  3409. cache.cells[i].seq_id.clear();
  3410. if (new_head == cache.size) new_head = i;
  3411. } else {
  3412. cache.cells[i].seq_id.clear();
  3413. cache.cells[i].seq_id.insert(seq_id);
  3414. }
  3415. }
  3416. // If we freed up a slot, set head to it so searching can start there.
  3417. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  3418. }
  3419. static void llama_kv_cache_seq_add(
  3420. struct llama_kv_cache & cache,
  3421. llama_seq_id seq_id,
  3422. llama_pos p0,
  3423. llama_pos p1,
  3424. llama_pos delta) {
  3425. uint32_t new_head = cache.size;
  3426. if (p0 < 0) p0 = 0;
  3427. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3428. // If there is no range then return early to avoid looping over the cache.
  3429. if (p0 == p1) return;
  3430. if (cache.recurrent) {
  3431. // for Mamba-like models, only the pos needs to be shifted
  3432. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3433. const int32_t tail_id = cache.cells[seq_id].tail;
  3434. if (tail_id >= 0) {
  3435. llama_kv_cell & cell = cache.cells[tail_id];
  3436. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3437. cell.pos += delta;
  3438. }
  3439. }
  3440. }
  3441. return;
  3442. }
  3443. for (uint32_t i = 0; i < cache.size; ++i) {
  3444. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3445. cache.has_shift = true;
  3446. cache.cells[i].pos += delta;
  3447. cache.cells[i].delta += delta;
  3448. if (cache.cells[i].pos < 0) {
  3449. if (!cache.cells[i].is_empty()) {
  3450. cache.used--;
  3451. }
  3452. cache.cells[i].pos = -1;
  3453. cache.cells[i].seq_id.clear();
  3454. if (new_head == cache.size) {
  3455. new_head = i;
  3456. }
  3457. }
  3458. }
  3459. }
  3460. // If we freed up a slot, set head to it so searching can start there.
  3461. // Otherwise we just start the next search from the beginning.
  3462. cache.head = new_head != cache.size ? new_head : 0;
  3463. }
  3464. static void llama_kv_cache_seq_div(
  3465. struct llama_kv_cache & cache,
  3466. llama_seq_id seq_id,
  3467. llama_pos p0,
  3468. llama_pos p1,
  3469. int d) {
  3470. if (p0 < 0) p0 = 0;
  3471. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  3472. // If there is no range then return early to avoid looping over the cache.
  3473. if (p0 == p1) return;
  3474. if (cache.recurrent) {
  3475. // for Mamba-like models, only the pos needs to be changed
  3476. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  3477. const int32_t tail_id = cache.cells[seq_id].tail;
  3478. if (tail_id >= 0) {
  3479. llama_kv_cell & cell = cache.cells[tail_id];
  3480. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  3481. cell.pos /= d;
  3482. }
  3483. }
  3484. }
  3485. return;
  3486. }
  3487. for (uint32_t i = 0; i < cache.size; ++i) {
  3488. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  3489. cache.has_shift = true;
  3490. {
  3491. llama_pos p_old = cache.cells[i].pos;
  3492. cache.cells[i].pos /= d;
  3493. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3494. }
  3495. }
  3496. }
  3497. }
  3498. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3499. llama_pos result = 0;
  3500. for (uint32_t i = 0; i < cache.size; ++i) {
  3501. if (cache.cells[i].has_seq_id(seq_id)) {
  3502. result = std::max(result, cache.cells[i].pos);
  3503. }
  3504. }
  3505. return result;
  3506. }
  3507. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3508. if (!cache.recurrent) {
  3509. cache.do_defrag = true;
  3510. }
  3511. }
  3512. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3513. // the FA kernels require padding to avoid extra runtime boundary checks
  3514. return cparams.flash_attn ? 256u : 32u;
  3515. }
  3516. //
  3517. // model loading and saving
  3518. //
  3519. enum llama_fver {
  3520. GGUF_FILE_VERSION_V1 = 1,
  3521. GGUF_FILE_VERSION_V2 = 2,
  3522. GGUF_FILE_VERSION_V3 = 3,
  3523. };
  3524. static const char * llama_file_version_name(llama_fver version) {
  3525. switch (version) {
  3526. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3527. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3528. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3529. }
  3530. return "unknown";
  3531. }
  3532. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3533. char buf[256];
  3534. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3535. for (size_t i = 1; i < ne.size(); i++) {
  3536. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3537. }
  3538. return buf;
  3539. }
  3540. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3541. char buf[256];
  3542. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3543. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3544. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3545. }
  3546. return buf;
  3547. }
  3548. namespace GGUFMeta {
  3549. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3550. struct GKV_Base_Type {
  3551. static constexpr gguf_type gt = gt_;
  3552. static T getter(const gguf_context * ctx, const int kid) {
  3553. return gfun(ctx, kid);
  3554. }
  3555. };
  3556. template<typename T> struct GKV_Base;
  3557. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3558. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3559. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3560. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3561. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3562. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3563. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3564. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3565. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3566. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3567. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3568. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3569. template<> struct GKV_Base<std::string> {
  3570. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3571. static std::string getter(const gguf_context * ctx, const int kid) {
  3572. return gguf_get_val_str(ctx, kid);
  3573. }
  3574. };
  3575. struct ArrayInfo {
  3576. const gguf_type gt;
  3577. const size_t length;
  3578. const void * data;
  3579. };
  3580. template<> struct GKV_Base<ArrayInfo> {
  3581. public:
  3582. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3583. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3584. return ArrayInfo {
  3585. gguf_get_arr_type(ctx, k),
  3586. size_t(gguf_get_arr_n(ctx, k)),
  3587. gguf_get_arr_data(ctx, k),
  3588. };
  3589. }
  3590. };
  3591. template<typename T>
  3592. class GKV : public GKV_Base<T> {
  3593. GKV() = delete;
  3594. public:
  3595. static T get_kv(const gguf_context * ctx, const int k) {
  3596. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3597. if (kt != GKV::gt) {
  3598. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3599. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3600. }
  3601. return GKV::getter(ctx, k);
  3602. }
  3603. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3604. switch (ty) {
  3605. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3606. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3607. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3608. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3609. }
  3610. return "unknown";
  3611. }
  3612. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3613. if (!ovrd) { return false; }
  3614. if (ovrd->tag == expected_type) {
  3615. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3616. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3617. switch (ovrd->tag) {
  3618. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3619. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3620. } break;
  3621. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3622. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3623. } break;
  3624. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3625. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3626. } break;
  3627. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3628. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  3629. } break;
  3630. default:
  3631. // Shouldn't be possible to end up here, but just in case...
  3632. throw std::runtime_error(
  3633. format("Unsupported attempt to override %s type for metadata key %s\n",
  3634. override_type_to_str(ovrd->tag), ovrd->key));
  3635. }
  3636. return true;
  3637. }
  3638. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  3639. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  3640. return false;
  3641. }
  3642. template<typename OT>
  3643. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  3644. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3645. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  3646. target = ovrd->val_bool;
  3647. return true;
  3648. }
  3649. return false;
  3650. }
  3651. template<typename OT>
  3652. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  3653. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3654. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  3655. target = ovrd->val_i64;
  3656. return true;
  3657. }
  3658. return false;
  3659. }
  3660. template<typename OT>
  3661. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  3662. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3663. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  3664. target = ovrd->val_f64;
  3665. return true;
  3666. }
  3667. return false;
  3668. }
  3669. template<typename OT>
  3670. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  3671. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3672. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  3673. target = ovrd->val_str;
  3674. return true;
  3675. }
  3676. return false;
  3677. }
  3678. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3679. if (try_override<T>(target, ovrd)) {
  3680. return true;
  3681. }
  3682. if (k < 0) { return false; }
  3683. target = get_kv(ctx, k);
  3684. return true;
  3685. }
  3686. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3687. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  3688. }
  3689. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3690. return set(ctx, key.c_str(), target, ovrd);
  3691. }
  3692. };
  3693. }
  3694. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  3695. static size_t llama_model_max_nodes(const llama_model & model) {
  3696. return std::max<size_t>(8192, model.tensors_by_name.size()*5);
  3697. }
  3698. struct llama_model_loader {
  3699. int n_kv = 0;
  3700. int n_tensors = 0;
  3701. int n_created = 0;
  3702. int64_t n_elements = 0;
  3703. size_t n_bytes = 0;
  3704. bool use_mmap = false;
  3705. bool check_tensors;
  3706. llama_files files;
  3707. llama_ftype ftype;
  3708. llama_fver fver;
  3709. llama_mmaps mappings;
  3710. // Holds information on a model weight
  3711. struct llama_tensor_weight {
  3712. uint16_t idx; // source file index
  3713. size_t offs; // tensor data offset in the original file
  3714. ggml_tensor * tensor;
  3715. 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) {
  3716. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  3717. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  3718. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  3719. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  3720. }
  3721. }
  3722. };
  3723. std::vector<llama_tensor_weight> weights;
  3724. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  3725. struct gguf_context * meta = NULL;
  3726. std::vector<ggml_context *> contexts;
  3727. std::string arch_name;
  3728. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  3729. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  3730. int trace = 0;
  3731. if (getenv("LLAMA_TRACE")) {
  3732. trace = atoi(getenv("LLAMA_TRACE"));
  3733. }
  3734. if (param_overrides_p != nullptr) {
  3735. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  3736. kv_overrides.insert({std::string(p->key), *p});
  3737. }
  3738. }
  3739. struct ggml_context * ctx = NULL;
  3740. struct gguf_init_params params = {
  3741. /*.no_alloc = */ true,
  3742. /*.ctx = */ &ctx,
  3743. };
  3744. meta = gguf_init_from_file(fname.c_str(), params);
  3745. if (!meta) {
  3746. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  3747. }
  3748. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  3749. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  3750. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  3751. contexts.emplace_back(ctx);
  3752. // Save tensors data offset of the main file.
  3753. // For subsidiary files, `meta` tensor data offset must not be used,
  3754. // so we build a unified tensors index for weights.
  3755. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3756. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  3757. }
  3758. uint16_t n_split = 0;
  3759. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  3760. // Load additional GGML contexts
  3761. if (n_split > 1) {
  3762. uint16_t idx = 0;
  3763. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  3764. if (idx != 0) {
  3765. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  3766. }
  3767. char split_prefix[PATH_MAX] = {0};
  3768. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  3769. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  3770. }
  3771. if (trace > 0) {
  3772. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  3773. }
  3774. char split_path[PATH_MAX] = {0};
  3775. for (idx = 1; idx < n_split; idx++) {
  3776. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  3777. struct gguf_init_params split_params = {
  3778. /*.no_alloc = */ true,
  3779. /*.ctx = */ &ctx,
  3780. };
  3781. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  3782. if (!ctx_gguf) {
  3783. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  3784. }
  3785. files.emplace_back(new llama_file(split_path, "rb"));
  3786. contexts.emplace_back(ctx);
  3787. // Save tensors data offset info of the shard.
  3788. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3789. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  3790. }
  3791. gguf_free(ctx_gguf);
  3792. }
  3793. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  3794. // sanity check
  3795. {
  3796. const int n_tensors_loaded = (int) weights.size();
  3797. if (n_tensors != n_tensors_loaded) {
  3798. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  3799. }
  3800. }
  3801. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  3802. }
  3803. n_kv = gguf_get_n_kv(meta);
  3804. n_tensors = weights.size();
  3805. fver = (enum llama_fver) gguf_get_version(meta);
  3806. std::set<std::string> tensor_names;
  3807. for (auto & w : weights) {
  3808. n_elements += ggml_nelements(w.tensor);
  3809. n_bytes += ggml_nbytes(w.tensor);
  3810. // make sure there is no duplicated tensor names
  3811. const std::string name(w.tensor->name);
  3812. auto found = tensor_names.find(name);
  3813. if (found != tensor_names.end()) {
  3814. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  3815. }
  3816. tensor_names.insert(name);
  3817. }
  3818. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  3819. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  3820. // determine file type based on the number of tensors for each quantization and print meta data
  3821. // TODO: make optional
  3822. {
  3823. std::map<enum ggml_type, uint32_t> n_type;
  3824. uint32_t n_type_max = 0;
  3825. enum ggml_type type_max = GGML_TYPE_F32;
  3826. for (int i = 0; i < n_tensors; i++) {
  3827. const ggml_tensor * tensor = weights.at(i).tensor;
  3828. enum ggml_type type = tensor->type;
  3829. n_type[type]++;
  3830. if (n_type_max < n_type[type]) {
  3831. n_type_max = n_type[type];
  3832. type_max = type;
  3833. }
  3834. if (trace > 0) {
  3835. const uint16_t sid = weights.at(i).idx;
  3836. 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());
  3837. }
  3838. }
  3839. switch (type_max) {
  3840. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  3841. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  3842. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  3843. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  3844. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  3845. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  3846. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  3847. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  3848. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  3849. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  3850. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  3851. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  3852. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  3853. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  3854. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  3855. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  3856. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  3857. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  3858. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  3859. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  3860. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  3861. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  3862. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  3863. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  3864. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  3865. default:
  3866. {
  3867. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  3868. ftype = LLAMA_FTYPE_ALL_F32;
  3869. } break;
  3870. }
  3871. // this is a way to mark that we have "guessed" the file type
  3872. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  3873. {
  3874. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  3875. if (kid >= 0) {
  3876. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  3877. }
  3878. }
  3879. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  3880. for (int i = 0; i < n_kv; i++) {
  3881. const char * name = gguf_get_key(meta, i);
  3882. const enum gguf_type type = gguf_get_kv_type(meta, i);
  3883. const std::string type_name =
  3884. type == GGUF_TYPE_ARRAY
  3885. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  3886. : gguf_type_name(type);
  3887. std::string value = gguf_kv_to_str(meta, i);
  3888. const size_t MAX_VALUE_LEN = 40;
  3889. if (value.size() > MAX_VALUE_LEN) {
  3890. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  3891. }
  3892. replace_all(value, "\n", "\\n");
  3893. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  3894. }
  3895. // print type counts
  3896. for (auto & kv : n_type) {
  3897. if (kv.second == 0) {
  3898. continue;
  3899. }
  3900. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  3901. }
  3902. }
  3903. if (!llama_mmap::SUPPORTED) {
  3904. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  3905. use_mmap = false;
  3906. }
  3907. this->use_mmap = use_mmap;
  3908. this->check_tensors = check_tensors;
  3909. }
  3910. ~llama_model_loader() {
  3911. if (meta) {
  3912. gguf_free(meta);
  3913. }
  3914. for (auto * ctx : contexts) {
  3915. ggml_free(ctx);
  3916. }
  3917. }
  3918. template<typename T>
  3919. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3920. get_arr_n(const std::string & key, T & result, const bool required = true) {
  3921. const int kid = gguf_find_key(meta, key.c_str());
  3922. if (kid < 0) {
  3923. if (required) {
  3924. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3925. }
  3926. return false;
  3927. }
  3928. struct GGUFMeta::ArrayInfo arr_info =
  3929. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3930. result = arr_info.length;
  3931. return true;
  3932. }
  3933. template<typename T>
  3934. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3935. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  3936. return get_arr_n(llm_kv(kid), result, required);
  3937. }
  3938. template<typename T>
  3939. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  3940. const int kid = gguf_find_key(meta, key.c_str());
  3941. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3942. if (required) {
  3943. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3944. }
  3945. return false;
  3946. }
  3947. struct GGUFMeta::ArrayInfo arr_info =
  3948. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3949. switch (arr_info.gt) {
  3950. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3951. case GGUF_TYPE_INT32: GGML_ASSERT(
  3952. (std::is_same<T, int32_t>::value) ||
  3953. (std::is_same<T, uint32_t>::value)); break;
  3954. default:
  3955. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3956. }
  3957. result.resize(arr_info.length);
  3958. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  3959. return true;
  3960. }
  3961. template<typename T, size_t N_MAX>
  3962. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  3963. const int kid = gguf_find_key(meta, key.c_str());
  3964. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3965. if (required) {
  3966. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3967. }
  3968. return false;
  3969. }
  3970. struct GGUFMeta::ArrayInfo arr_info =
  3971. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3972. switch (arr_info.gt) {
  3973. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3974. case GGUF_TYPE_INT32: GGML_ASSERT(
  3975. (std::is_same<T, int32_t>::value) ||
  3976. (std::is_same<T, uint32_t>::value)); break;
  3977. default:
  3978. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3979. }
  3980. if (arr_info.length > N_MAX) {
  3981. 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));
  3982. }
  3983. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  3984. return true;
  3985. }
  3986. template<typename T>
  3987. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  3988. return get_arr(llm_kv(kid), result, required);
  3989. }
  3990. template<typename T>
  3991. bool get_key(const std::string & key, T & result, const bool required = true) {
  3992. auto it = kv_overrides.find(key);
  3993. const struct llama_model_kv_override * override =
  3994. it != kv_overrides.end() ? &it->second : nullptr;
  3995. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  3996. if (required && !found) {
  3997. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3998. }
  3999. return found;
  4000. }
  4001. template<typename T>
  4002. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  4003. return get_key(llm_kv(kid), result, required);
  4004. }
  4005. // get array of n <= N_MAX elements, or a single element repeated n times
  4006. template<typename T, size_t N_MAX>
  4007. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  4008. const int kid = gguf_find_key(meta, key.c_str());
  4009. if (kid < 0) {
  4010. if (required) {
  4011. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  4012. }
  4013. return false;
  4014. }
  4015. if (n > N_MAX) {
  4016. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  4017. }
  4018. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  4019. struct GGUFMeta::ArrayInfo arr_info =
  4020. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  4021. if (n != arr_info.length) {
  4022. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  4023. }
  4024. return get_arr(key, result, required);
  4025. } else {
  4026. T value;
  4027. bool ok = get_key(key, value, required);
  4028. if (!ok) {
  4029. return false;
  4030. }
  4031. for (uint32_t i = 0; i < n; i++) {
  4032. result[i] = value;
  4033. }
  4034. return true;
  4035. }
  4036. }
  4037. template<typename T>
  4038. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  4039. return get_key_or_arr(llm_kv(kid), result, n, required);
  4040. }
  4041. std::string get_arch_name() const {
  4042. return arch_name;
  4043. }
  4044. enum llm_arch get_arch() const {
  4045. return llm_kv.arch;
  4046. }
  4047. const char * get_tensor_name(int i) const {
  4048. return weights.at(i).tensor->name;
  4049. }
  4050. const llama_tensor_weight * get_weight(const char * name) const {
  4051. for (const auto & weight : weights) {
  4052. if (strcmp(name, weight.tensor->name) == 0) {
  4053. return &weight;
  4054. }
  4055. }
  4056. return nullptr;
  4057. }
  4058. const llama_tensor_weight * get_weight(int i) const {
  4059. return get_weight(get_tensor_name(i));
  4060. }
  4061. const llama_tensor_weight & require_weight(const char * name) const {
  4062. const llama_tensor_weight * weight = get_weight(name);
  4063. if (!weight) {
  4064. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4065. }
  4066. return *weight;
  4067. }
  4068. struct ggml_tensor * get_tensor_meta(const char * name) const {
  4069. const auto * weight = get_weight(name);
  4070. if (!weight) {
  4071. return nullptr;
  4072. }
  4073. return weight->tensor;
  4074. }
  4075. struct ggml_tensor * require_tensor_meta(const char * name) const {
  4076. struct ggml_tensor * tensor = get_tensor_meta(name);
  4077. if (!tensor) {
  4078. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  4079. }
  4080. return tensor;
  4081. }
  4082. struct ggml_tensor * get_tensor_meta(int i) const {
  4083. return get_tensor_meta(get_tensor_name(i));
  4084. }
  4085. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  4086. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  4087. ggml_set_name(tensor, ggml_get_name(cur));
  4088. if (duplicated) {
  4089. size_data += ggml_nbytes(cur);
  4090. } else {
  4091. n_created++;
  4092. }
  4093. return tensor;
  4094. }
  4095. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  4096. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  4097. if (cur == NULL) {
  4098. if (!required) {
  4099. return NULL;
  4100. }
  4101. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  4102. }
  4103. {
  4104. bool is_ok = true;
  4105. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4106. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  4107. is_ok = false;
  4108. break;
  4109. }
  4110. }
  4111. if (!is_ok) {
  4112. throw std::runtime_error(
  4113. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  4114. __func__, name.c_str(),
  4115. llama_format_tensor_shape(ne).c_str(),
  4116. llama_format_tensor_shape(cur).c_str()));
  4117. }
  4118. }
  4119. return cur;
  4120. }
  4121. static const int TENSOR_NOT_REQUIRED = 1;
  4122. static const int TENSOR_DUPLICATED = 2;
  4123. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  4124. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  4125. if (cur == NULL) {
  4126. return NULL;
  4127. }
  4128. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  4129. }
  4130. 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) {
  4131. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  4132. if (cur == NULL) {
  4133. return NULL;
  4134. }
  4135. if (cur->type != base->type) {
  4136. 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)));
  4137. }
  4138. std::array<int64_t, GGML_MAX_DIMS> dims;
  4139. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  4140. dims[i] = i < ne.size() ? ne[i] : 1;
  4141. }
  4142. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  4143. dims[0], dims[1], dims[2], dims[3],
  4144. cur->nb[1], cur->nb[2], cur->nb[3],
  4145. offset);
  4146. ggml_set_name(tensor, name.c_str());
  4147. n_created++;
  4148. return tensor;
  4149. }
  4150. void done_getting_tensors() const {
  4151. if (n_created != n_tensors) {
  4152. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  4153. }
  4154. }
  4155. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  4156. if (use_mmap) {
  4157. mappings.reserve(files.size());
  4158. mmaps_used.reserve(files.size());
  4159. for (const auto & file : files) {
  4160. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  4161. mmaps_used.emplace_back(mapping->size, 0);
  4162. if (mlock_mmaps) {
  4163. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  4164. mlock_mmap->init(mapping->addr);
  4165. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  4166. }
  4167. mappings.emplace_back(std::move(mapping));
  4168. }
  4169. }
  4170. // compute the total size of all tensors for progress reporting
  4171. for (auto & w : weights) {
  4172. size_data += ggml_nbytes(w.tensor);
  4173. }
  4174. }
  4175. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  4176. GGML_ASSERT(!mappings.empty());
  4177. const auto & mapping = mappings.at(idx);
  4178. *first = mapping->size;
  4179. *last = 0;
  4180. *addr = mapping->addr;
  4181. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  4182. try {
  4183. const auto * weight = get_weight(ggml_get_name(tensor));
  4184. if (!weight) {
  4185. continue;
  4186. }
  4187. if (weight->idx != idx) {
  4188. continue;
  4189. }
  4190. *first = std::min(*first, weight->offs);
  4191. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  4192. } catch(...) {
  4193. // the tensor is not in the model
  4194. }
  4195. }
  4196. }
  4197. // for backwards compatibility, does not support ggml-backend
  4198. void load_data_for(struct ggml_tensor * cur) const {
  4199. const auto & w = require_weight(ggml_get_name(cur));
  4200. if (use_mmap) {
  4201. const auto & mapping = mappings.at(w.idx);
  4202. if (cur->data == nullptr) {
  4203. cur->data = (uint8_t *)mapping->addr + w.offs;
  4204. } else {
  4205. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  4206. }
  4207. } else {
  4208. GGML_ASSERT(cur->data != nullptr);
  4209. GGML_ASSERT(w.idx < files.size());
  4210. const auto & file = files.at(w.idx);
  4211. file->seek(w.offs, SEEK_SET);
  4212. file->read_raw(cur->data, ggml_nbytes(cur));
  4213. }
  4214. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  4215. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4216. }
  4217. }
  4218. size_t size_done = 0;
  4219. size_t size_data = 0;
  4220. std::vector<std::pair<size_t, size_t>> mmaps_used;
  4221. // Returns false if cancelled by progress_callback
  4222. bool load_all_data(
  4223. struct ggml_context * ctx,
  4224. llama_buf_map & bufs_mmap,
  4225. llama_mlocks * lmlocks,
  4226. llama_progress_callback progress_callback,
  4227. void * progress_callback_user_data) {
  4228. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  4229. std::vector<no_init<uint8_t>> read_buf;
  4230. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  4231. #if defined(GGML_USE_CUDA)
  4232. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  4233. // NVMe raid configurations might require more / larger buffers.
  4234. constexpr size_t n_buffers = 4;
  4235. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  4236. std::vector<ggml_backend_buffer_t> host_buffers;
  4237. std::vector<void*> host_ptrs;
  4238. std::vector<ggml_backend_event_t> events;
  4239. size_t buffer_idx = 0; // buffer to use for async loads
  4240. ggml_backend_t cuda_backend = nullptr;
  4241. if (!use_mmap && !check_tensors) {
  4242. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  4243. // First determine if the CUDA backend is active, and if so, determine the device ID.
  4244. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  4245. if (buf) {
  4246. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  4247. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  4248. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  4249. if (buffer_type == cuda_buffer_type) {
  4250. cuda_backend = ggml_backend_cuda_init(i);
  4251. break;
  4252. }
  4253. }
  4254. }
  4255. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  4256. if (cuda_backend) {
  4257. for (size_t idx = 0; idx < n_buffers; ++idx) {
  4258. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  4259. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  4260. events.emplace_back(ggml_backend_event_new(cuda_backend));
  4261. }
  4262. }
  4263. }
  4264. #endif
  4265. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4266. const auto * weight = get_weight(ggml_get_name(cur));
  4267. if (weight == nullptr) {
  4268. // this can happen with split experts models
  4269. continue;
  4270. }
  4271. if (progress_callback) {
  4272. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  4273. return false;
  4274. }
  4275. }
  4276. size_t n_size = ggml_nbytes(cur);
  4277. if (use_mmap) {
  4278. const auto & mapping = mappings.at(weight->idx);
  4279. ggml_backend_buffer_t buf_mmap = nullptr;
  4280. if (bufs_mmap.count(weight->idx)) {
  4281. buf_mmap = bufs_mmap.at(weight->idx);
  4282. }
  4283. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  4284. if (check_tensors) {
  4285. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  4286. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  4287. }));
  4288. }
  4289. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  4290. if (buf_mmap && cur->data == nullptr) {
  4291. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  4292. if (lmlocks) {
  4293. const auto & lmlock = lmlocks->at(weight->idx);
  4294. lmlock->grow_to(weight->offs + n_size);
  4295. }
  4296. auto & mmap_used = mmaps_used[weight->idx];
  4297. mmap_used.first = std::min(mmap_used.first, weight->offs);
  4298. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  4299. } else {
  4300. ggml_backend_tensor_set(cur, data, 0, n_size);
  4301. }
  4302. } else {
  4303. GGML_ASSERT(weight->idx < files.size());
  4304. const auto & file = files.at(weight->idx);
  4305. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4306. file->seek(weight->offs, SEEK_SET);
  4307. file->read_raw(cur->data, n_size);
  4308. if (check_tensors) {
  4309. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  4310. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  4311. }));
  4312. }
  4313. } else {
  4314. #if defined(GGML_USE_CUDA)
  4315. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  4316. if (cuda_backend) {
  4317. file->seek(weight->offs, SEEK_SET);
  4318. size_t bytes_read = 0;
  4319. while (bytes_read < n_size) {
  4320. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  4321. ggml_backend_event_synchronize(events[buffer_idx]);
  4322. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  4323. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  4324. ggml_backend_event_record(events[buffer_idx]);
  4325. bytes_read += read_iteration;
  4326. ++buffer_idx;
  4327. buffer_idx %= n_buffers;
  4328. }
  4329. }
  4330. else
  4331. #endif
  4332. {
  4333. read_buf.resize(n_size);
  4334. file->seek(weight->offs, SEEK_SET);
  4335. file->read_raw(read_buf.data(), n_size);
  4336. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  4337. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  4338. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  4339. }
  4340. }
  4341. }
  4342. }
  4343. size_done += n_size;
  4344. }
  4345. #if defined(GGML_USE_CUDA)
  4346. // free temporary resources used for async cuda uploads
  4347. if (cuda_backend) {
  4348. for (size_t idx = 0; idx < n_buffers;++idx) {
  4349. ggml_backend_event_synchronize(events[idx]);
  4350. ggml_backend_event_free(events[idx]);
  4351. ggml_backend_buffer_free(host_buffers[idx]);
  4352. }
  4353. ggml_backend_free(cuda_backend);
  4354. }
  4355. #endif
  4356. // check validation results
  4357. bool validation_failed = false;
  4358. for (auto & future : validation_result) {
  4359. auto result = future.get();
  4360. if (!result.second) {
  4361. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  4362. validation_failed = true;
  4363. }
  4364. }
  4365. if (validation_failed) {
  4366. throw std::runtime_error("found tensors with invalid data");
  4367. }
  4368. // check if this is the last call and do final cleanup
  4369. if (size_done >= size_data) {
  4370. // unmap offloaded tensors and metadata
  4371. if (use_mmap) {
  4372. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  4373. const auto & mmap_used = mmaps_used.at(idx);
  4374. auto & mapping = mappings.at(idx);
  4375. mapping->unmap_fragment(0, mmap_used.first);
  4376. if (mmap_used.second != 0) {
  4377. mapping->unmap_fragment(mmap_used.second, mapping->size);
  4378. }
  4379. }
  4380. }
  4381. if (progress_callback) {
  4382. // Even though the model is done loading, we still honor
  4383. // cancellation since we need to free allocations.
  4384. return progress_callback(1.0f, progress_callback_user_data);
  4385. }
  4386. }
  4387. return true;
  4388. }
  4389. };
  4390. template<>
  4391. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  4392. uint32_t tmp;
  4393. const bool found = get_key(kid, tmp, required);
  4394. if (found) {
  4395. result = (enum llama_pooling_type) tmp;
  4396. } else {
  4397. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  4398. }
  4399. return found;
  4400. }
  4401. //
  4402. // load LLaMA models
  4403. //
  4404. static const char * llama_model_arch_name(llm_arch arch) {
  4405. auto it = LLM_ARCH_NAMES.find(arch);
  4406. if (it == LLM_ARCH_NAMES.end()) {
  4407. return "unknown";
  4408. }
  4409. return it->second;
  4410. }
  4411. static std::string llama_model_ftype_name(llama_ftype ftype) {
  4412. if (ftype & LLAMA_FTYPE_GUESSED) {
  4413. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  4414. }
  4415. switch (ftype) {
  4416. case LLAMA_FTYPE_ALL_F32: return "all F32";
  4417. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  4418. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  4419. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  4420. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  4421. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  4422. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  4423. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  4424. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  4425. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  4426. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  4427. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  4428. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  4429. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  4430. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  4431. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  4432. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  4433. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  4434. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  4435. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  4436. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  4437. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  4438. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  4439. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  4440. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  4441. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  4442. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  4443. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  4444. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  4445. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  4446. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  4447. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  4448. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  4449. default: return "unknown, may not work";
  4450. }
  4451. }
  4452. static const char * llama_model_type_name(e_model type) {
  4453. switch (type) {
  4454. case MODEL_14M: return "14M";
  4455. case MODEL_17M: return "17M";
  4456. case MODEL_22M: return "22M";
  4457. case MODEL_33M: return "33M";
  4458. case MODEL_60M: return "60M";
  4459. case MODEL_70M: return "70M";
  4460. case MODEL_80M: return "80M";
  4461. case MODEL_109M: return "109M";
  4462. case MODEL_137M: return "137M";
  4463. case MODEL_160M: return "160M";
  4464. case MODEL_220M: return "220M";
  4465. case MODEL_250M: return "250M";
  4466. case MODEL_270M: return "270M";
  4467. case MODEL_335M: return "335M";
  4468. case MODEL_410M: return "410M";
  4469. case MODEL_450M: return "450M";
  4470. case MODEL_770M: return "770M";
  4471. case MODEL_780M: return "780M";
  4472. case MODEL_0_5B: return "0.5B";
  4473. case MODEL_1B: return "1B";
  4474. case MODEL_1_3B: return "1.3B";
  4475. case MODEL_1_4B: return "1.4B";
  4476. case MODEL_2B: return "2B";
  4477. case MODEL_2_8B: return "2.8B";
  4478. case MODEL_3B: return "3B";
  4479. case MODEL_4B: return "4B";
  4480. case MODEL_6B: return "6B";
  4481. case MODEL_6_9B: return "6.9B";
  4482. case MODEL_7B: return "7B";
  4483. case MODEL_8B: return "8B";
  4484. case MODEL_9B: return "9B";
  4485. case MODEL_11B: return "11B";
  4486. case MODEL_12B: return "12B";
  4487. case MODEL_13B: return "13B";
  4488. case MODEL_14B: return "14B";
  4489. case MODEL_15B: return "15B";
  4490. case MODEL_16B: return "16B";
  4491. case MODEL_20B: return "20B";
  4492. case MODEL_30B: return "30B";
  4493. case MODEL_34B: return "34B";
  4494. case MODEL_35B: return "35B";
  4495. case MODEL_40B: return "40B";
  4496. case MODEL_65B: return "65B";
  4497. case MODEL_70B: return "70B";
  4498. case MODEL_236B: return "236B";
  4499. case MODEL_314B: return "314B";
  4500. case MODEL_SMALL: return "0.1B";
  4501. case MODEL_MEDIUM: return "0.4B";
  4502. case MODEL_LARGE: return "0.8B";
  4503. case MODEL_XL: return "1.5B";
  4504. case MODEL_A2_7B: return "A2.7B";
  4505. case MODEL_8x7B: return "8x7B";
  4506. case MODEL_8x22B: return "8x22B";
  4507. case MODEL_16x12B: return "16x12B";
  4508. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4509. case MODEL_57B_A14B: return "57B.A14B";
  4510. case MODEL_27B: return "27B";
  4511. default: return "?B";
  4512. }
  4513. }
  4514. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4515. switch (type) {
  4516. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4517. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4518. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4519. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4520. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4521. default: return "unknown";
  4522. }
  4523. }
  4524. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4525. model.arch = ml.get_arch();
  4526. if (model.arch == LLM_ARCH_UNKNOWN) {
  4527. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4528. }
  4529. }
  4530. static void llm_load_hparams(
  4531. llama_model_loader & ml,
  4532. llama_model & model) {
  4533. auto & hparams = model.hparams;
  4534. const gguf_context * ctx = ml.meta;
  4535. // get metadata as string
  4536. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4537. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4538. if (type == GGUF_TYPE_ARRAY) {
  4539. continue;
  4540. }
  4541. const char * name = gguf_get_key(ctx, i);
  4542. const std::string value = gguf_kv_to_str(ctx, i);
  4543. model.gguf_kv.emplace(name, value);
  4544. }
  4545. // get general kv
  4546. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4547. // get hparams kv
  4548. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4549. // everything past this point is not vocab-related
  4550. if (hparams.vocab_only) {
  4551. return;
  4552. }
  4553. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4554. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4555. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4556. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4557. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4558. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4559. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4560. if (hparams.n_expert > 0) {
  4561. GGML_ASSERT(hparams.n_expert_used > 0);
  4562. } else {
  4563. GGML_ASSERT(hparams.n_expert_used == 0);
  4564. }
  4565. // zero-out the per-layer hparams
  4566. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4567. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4568. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4569. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4570. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4571. // n_head_kv is optional, default to n_head
  4572. hparams.n_head_kv_arr = hparams.n_head_arr;
  4573. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4574. bool rope_finetuned = false;
  4575. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4576. hparams.rope_finetuned = rope_finetuned;
  4577. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4578. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4579. // rope_freq_base (optional)
  4580. hparams.rope_freq_base_train = 10000.0f;
  4581. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4582. std::string rope_scaling("linear");
  4583. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4584. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4585. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4586. // rope_freq_scale (inverse of the kv) is optional
  4587. float ropescale = 0.0f;
  4588. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4589. // try the old key name
  4590. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4591. }
  4592. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4593. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4594. // non-transformer models do not have attention heads
  4595. if (hparams.n_head() > 0) {
  4596. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4597. // gpt-j n_rot = rotary_dim
  4598. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4599. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4600. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  4601. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  4602. // sanity check for n_rot (optional)
  4603. hparams.n_rot = hparams.n_embd_head_k;
  4604. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  4605. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  4606. if (hparams.n_rot != hparams.n_embd_head_k) {
  4607. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  4608. }
  4609. }
  4610. } else {
  4611. hparams.n_rot = 0;
  4612. hparams.n_embd_head_k = 0;
  4613. hparams.n_embd_head_v = 0;
  4614. }
  4615. // arch-specific KVs
  4616. switch (model.arch) {
  4617. case LLM_ARCH_LLAMA:
  4618. {
  4619. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4620. if (hparams.n_expert == 8) {
  4621. switch (hparams.n_layer) {
  4622. case 32: model.type = e_model::MODEL_8x7B; break;
  4623. case 56: model.type = e_model::MODEL_8x22B; break;
  4624. default: model.type = e_model::MODEL_UNKNOWN;
  4625. }
  4626. } else {
  4627. switch (hparams.n_layer) {
  4628. case 22: model.type = e_model::MODEL_1B; break;
  4629. case 26: model.type = e_model::MODEL_3B; break;
  4630. // granite uses a vocab with len 49152
  4631. 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;
  4632. case 36: model.type = e_model::MODEL_8B; break; // granite
  4633. case 40: model.type = e_model::MODEL_13B; break;
  4634. case 48: model.type = e_model::MODEL_34B; break;
  4635. case 60: model.type = e_model::MODEL_30B; break;
  4636. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  4637. default: model.type = e_model::MODEL_UNKNOWN;
  4638. }
  4639. }
  4640. } break;
  4641. case LLM_ARCH_MINICPM:
  4642. {
  4643. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4644. switch (hparams.n_layer) {
  4645. case 40: model.type = e_model::MODEL_2B; break;
  4646. default: model.type = e_model::MODEL_UNKNOWN;
  4647. }
  4648. } break;
  4649. case LLM_ARCH_GROK:
  4650. {
  4651. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4652. switch (hparams.n_layer) {
  4653. case 64: model.type = e_model::MODEL_314B; break;
  4654. default: model.type = e_model::MODEL_UNKNOWN;
  4655. }
  4656. } break;
  4657. case LLM_ARCH_FALCON:
  4658. {
  4659. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4660. switch (hparams.n_layer) {
  4661. case 32: model.type = e_model::MODEL_7B; break;
  4662. case 60: model.type = e_model::MODEL_40B; break;
  4663. default: model.type = e_model::MODEL_UNKNOWN;
  4664. }
  4665. } break;
  4666. case LLM_ARCH_BAICHUAN:
  4667. {
  4668. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4669. switch (hparams.n_layer) {
  4670. case 32: model.type = e_model::MODEL_7B; break;
  4671. case 40: model.type = e_model::MODEL_13B; break;
  4672. default: model.type = e_model::MODEL_UNKNOWN;
  4673. }
  4674. if (model.type == e_model::MODEL_13B) {
  4675. // TODO: become GGUF KV parameter
  4676. hparams.f_max_alibi_bias = 8.0f;
  4677. }
  4678. } break;
  4679. case LLM_ARCH_STARCODER:
  4680. {
  4681. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4682. switch (hparams.n_layer) {
  4683. case 24: model.type = e_model::MODEL_1B; break;
  4684. case 36: model.type = e_model::MODEL_3B; break;
  4685. case 42: model.type = e_model::MODEL_7B; break;
  4686. case 40: model.type = e_model::MODEL_15B; break;
  4687. default: model.type = e_model::MODEL_UNKNOWN;
  4688. }
  4689. } break;
  4690. case LLM_ARCH_REFACT:
  4691. {
  4692. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4693. switch (hparams.n_layer) {
  4694. case 32: model.type = e_model::MODEL_1B; break;
  4695. default: model.type = e_model::MODEL_UNKNOWN;
  4696. }
  4697. // TODO: become GGUF KV parameter
  4698. hparams.f_max_alibi_bias = 8.0f;
  4699. } break;
  4700. case LLM_ARCH_BERT:
  4701. {
  4702. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4703. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4704. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4705. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4706. switch (hparams.n_layer) {
  4707. case 3:
  4708. model.type = e_model::MODEL_17M; break; // bge-micro
  4709. case 6:
  4710. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  4711. case 12:
  4712. switch (hparams.n_embd) {
  4713. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  4714. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  4715. } break;
  4716. case 24:
  4717. model.type = e_model::MODEL_335M; break; // bge-large
  4718. }
  4719. } break;
  4720. case LLM_ARCH_JINA_BERT_V2:
  4721. {
  4722. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4723. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4724. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4725. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4726. hparams.f_max_alibi_bias = 8.0f;
  4727. switch (hparams.n_layer) {
  4728. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  4729. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  4730. }
  4731. } break;
  4732. case LLM_ARCH_NOMIC_BERT:
  4733. {
  4734. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4735. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4736. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4737. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4738. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  4739. model.type = e_model::MODEL_137M;
  4740. }
  4741. } break;
  4742. case LLM_ARCH_BLOOM:
  4743. {
  4744. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4745. switch (hparams.n_layer) {
  4746. case 24: model.type = e_model::MODEL_1B; break;
  4747. case 30:
  4748. switch (hparams.n_embd) {
  4749. case 2560: model.type = e_model::MODEL_3B; break;
  4750. case 4096: model.type = e_model::MODEL_7B; break;
  4751. } break;
  4752. }
  4753. // TODO: become GGUF KV parameter
  4754. hparams.f_max_alibi_bias = 8.0f;
  4755. } break;
  4756. case LLM_ARCH_MPT:
  4757. {
  4758. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4759. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4760. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4761. switch (hparams.n_layer) {
  4762. case 32: model.type = e_model::MODEL_7B; break;
  4763. case 48: model.type = e_model::MODEL_30B; break;
  4764. default: model.type = e_model::MODEL_UNKNOWN;
  4765. }
  4766. } break;
  4767. case LLM_ARCH_STABLELM:
  4768. {
  4769. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4770. switch (hparams.n_layer) {
  4771. case 24: model.type = e_model::MODEL_1B; break;
  4772. case 32: model.type = e_model::MODEL_3B; break;
  4773. case 40: model.type = e_model::MODEL_12B; break;
  4774. default: model.type = e_model::MODEL_UNKNOWN;
  4775. }
  4776. } break;
  4777. case LLM_ARCH_QWEN:
  4778. {
  4779. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4780. switch (hparams.n_layer) {
  4781. case 32: model.type = e_model::MODEL_7B; break;
  4782. case 40: model.type = e_model::MODEL_13B; break;
  4783. default: model.type = e_model::MODEL_UNKNOWN;
  4784. }
  4785. } break;
  4786. case LLM_ARCH_QWEN2:
  4787. {
  4788. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4789. switch (hparams.n_layer) {
  4790. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  4791. case 32: model.type = e_model::MODEL_7B; break;
  4792. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  4793. case 80: model.type = e_model::MODEL_70B; break;
  4794. default: model.type = e_model::MODEL_UNKNOWN;
  4795. }
  4796. } break;
  4797. case LLM_ARCH_QWEN2MOE:
  4798. {
  4799. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  4800. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  4801. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4802. switch (hparams.n_layer) {
  4803. case 24: model.type = e_model::MODEL_A2_7B; break;
  4804. case 28: model.type = e_model::MODEL_57B_A14B; break;
  4805. default: model.type = e_model::MODEL_UNKNOWN;
  4806. }
  4807. } break;
  4808. case LLM_ARCH_PHI2:
  4809. {
  4810. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4811. switch (hparams.n_layer) {
  4812. case 24: model.type = e_model::MODEL_1B; break;
  4813. case 32: model.type = e_model::MODEL_3B; break;
  4814. default: model.type = e_model::MODEL_UNKNOWN;
  4815. }
  4816. } break;
  4817. case LLM_ARCH_PHI3:
  4818. {
  4819. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4820. switch (hparams.n_layer) {
  4821. case 24: model.type = e_model::MODEL_1B; break;
  4822. case 32: model.type = e_model::MODEL_3B; break;
  4823. case 40: model.type = e_model::MODEL_14B; break;
  4824. default: model.type = e_model::MODEL_UNKNOWN;
  4825. }
  4826. // for backward compatibility ; see: https://github.com/ggerganov/llama.cpp/pull/8931
  4827. if ((hparams.n_layer == 32 || hparams.n_layer == 40) && hparams.n_ctx_train == 4096) {
  4828. // default value for Phi-3-mini-4k-instruct and Phi-3-medium-4k-instruct
  4829. hparams.n_swa = 2047;
  4830. } else if (hparams.n_layer == 32 && hparams.n_head_kv(0) == 32 && hparams.n_ctx_train == 131072) {
  4831. // default value for Phi-3-mini-128k-instruct
  4832. hparams.n_swa = 262144;
  4833. } else if (hparams.n_layer == 40 && hparams.n_ctx_train == 131072) {
  4834. // default value for Phi-3-medium-128k-instruct
  4835. hparams.n_swa = 131072;
  4836. }
  4837. bool found_swa = ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  4838. if (!found_swa && hparams.n_swa == 0) {
  4839. throw std::runtime_error("invalid value for sliding_window");
  4840. }
  4841. } break;
  4842. case LLM_ARCH_PLAMO:
  4843. {
  4844. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4845. switch (hparams.n_layer) {
  4846. case 40: model.type = e_model::MODEL_13B; break;
  4847. default: model.type = e_model::MODEL_UNKNOWN;
  4848. }
  4849. } break;
  4850. case LLM_ARCH_GPT2:
  4851. {
  4852. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4853. switch (hparams.n_layer) {
  4854. case 12: model.type = e_model::MODEL_SMALL; break;
  4855. case 24: model.type = e_model::MODEL_MEDIUM; break;
  4856. case 36: model.type = e_model::MODEL_LARGE; break;
  4857. case 48: model.type = e_model::MODEL_XL; break;
  4858. default: model.type = e_model::MODEL_UNKNOWN;
  4859. }
  4860. } break;
  4861. case LLM_ARCH_CODESHELL:
  4862. {
  4863. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4864. switch (hparams.n_layer) {
  4865. case 42: model.type = e_model::MODEL_7B; break;
  4866. default: model.type = e_model::MODEL_UNKNOWN;
  4867. }
  4868. } break;
  4869. case LLM_ARCH_ORION:
  4870. {
  4871. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4872. switch (hparams.n_layer) {
  4873. case 40: model.type = e_model::MODEL_14B; break;
  4874. default: model.type = e_model::MODEL_UNKNOWN;
  4875. }
  4876. } break;
  4877. case LLM_ARCH_INTERNLM2:
  4878. {
  4879. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4880. switch (hparams.n_layer) {
  4881. case 32: model.type = e_model::MODEL_7B; break;
  4882. case 48: model.type = e_model::MODEL_20B; break;
  4883. default: model.type = e_model::MODEL_UNKNOWN;
  4884. }
  4885. } break;
  4886. case LLM_ARCH_GEMMA:
  4887. {
  4888. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4889. switch (hparams.n_layer) {
  4890. case 18: model.type = e_model::MODEL_2B; break;
  4891. case 28: model.type = e_model::MODEL_7B; break;
  4892. default: model.type = e_model::MODEL_UNKNOWN;
  4893. }
  4894. } break;
  4895. case LLM_ARCH_GEMMA2:
  4896. {
  4897. hparams.n_swa = 4096; // default value of gemma 2
  4898. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  4899. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4900. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  4901. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  4902. hparams.attn_soft_cap = true;
  4903. switch (hparams.n_layer) {
  4904. case 26: model.type = e_model::MODEL_2B; break;
  4905. case 42: model.type = e_model::MODEL_9B; break;
  4906. case 46: model.type = e_model::MODEL_27B; break;
  4907. default: model.type = e_model::MODEL_UNKNOWN;
  4908. }
  4909. } break;
  4910. case LLM_ARCH_STARCODER2:
  4911. {
  4912. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4913. switch (hparams.n_layer) {
  4914. case 30: model.type = e_model::MODEL_3B; break;
  4915. case 32: model.type = e_model::MODEL_7B; break;
  4916. case 40: model.type = e_model::MODEL_15B; break;
  4917. case 52: model.type = e_model::MODEL_20B; break; // granite
  4918. case 88: model.type = e_model::MODEL_34B; break; // granite
  4919. default: model.type = e_model::MODEL_UNKNOWN;
  4920. }
  4921. } break;
  4922. case LLM_ARCH_MAMBA:
  4923. {
  4924. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  4925. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  4926. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  4927. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  4928. ml.get_key(LLM_KV_SSM_DT_B_C_RMS, hparams.ssm_dt_b_c_rms, false);
  4929. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4930. switch (hparams.n_layer) {
  4931. case 24:
  4932. switch (hparams.n_embd) {
  4933. case 768: model.type = e_model::MODEL_SMALL; break;
  4934. default: model.type = e_model::MODEL_UNKNOWN;
  4935. } break;
  4936. case 48:
  4937. switch (hparams.n_embd) {
  4938. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  4939. case 1536: model.type = e_model::MODEL_LARGE; break;
  4940. case 2048: model.type = e_model::MODEL_XL; break;
  4941. default: model.type = e_model::MODEL_UNKNOWN;
  4942. } break;
  4943. case 64:
  4944. switch (hparams.n_embd) {
  4945. case 2560: model.type = e_model::MODEL_3B; break;
  4946. default: model.type = e_model::MODEL_UNKNOWN;
  4947. } break;
  4948. default: model.type = e_model::MODEL_UNKNOWN;
  4949. }
  4950. } break;
  4951. case LLM_ARCH_XVERSE:
  4952. {
  4953. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4954. switch (hparams.n_layer) {
  4955. case 32: model.type = e_model::MODEL_7B; break;
  4956. case 40: model.type = e_model::MODEL_13B; break;
  4957. case 80: model.type = e_model::MODEL_65B; break;
  4958. default: model.type = e_model::MODEL_UNKNOWN;
  4959. }
  4960. } break;
  4961. case LLM_ARCH_COMMAND_R:
  4962. {
  4963. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  4964. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4965. switch (hparams.n_layer) {
  4966. case 40: model.type = e_model::MODEL_35B; break;
  4967. default: model.type = e_model::MODEL_UNKNOWN;
  4968. }
  4969. } break;
  4970. case LLM_ARCH_DBRX:
  4971. {
  4972. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4973. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  4974. switch (hparams.n_layer) {
  4975. case 40: model.type = e_model::MODEL_16x12B; break;
  4976. default: model.type = e_model::MODEL_UNKNOWN;
  4977. }
  4978. } break;
  4979. case LLM_ARCH_OLMO:
  4980. {
  4981. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4982. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4983. switch (hparams.n_layer) {
  4984. case 22: model.type = e_model::MODEL_1B; break;
  4985. case 32: model.type = e_model::MODEL_7B; break;
  4986. case 80: model.type = e_model::MODEL_70B; break;
  4987. default: model.type = e_model::MODEL_UNKNOWN;
  4988. }
  4989. } break;
  4990. case LLM_ARCH_OPENELM:
  4991. {
  4992. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4993. switch (hparams.n_layer) {
  4994. case 16: model.type = e_model::MODEL_270M; break;
  4995. case 20: model.type = e_model::MODEL_450M; break;
  4996. case 28: model.type = e_model::MODEL_1B; break;
  4997. case 36: model.type = e_model::MODEL_3B; break;
  4998. default: model.type = e_model::MODEL_UNKNOWN;
  4999. }
  5000. } break;
  5001. case LLM_ARCH_GPTNEOX:
  5002. {
  5003. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5004. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  5005. switch (hparams.n_layer) {
  5006. case 6:
  5007. switch (hparams.n_ff()) {
  5008. case 512: model.type = e_model::MODEL_14M; break;
  5009. case 2048: model.type = e_model::MODEL_70M; break;
  5010. default: model.type = e_model::MODEL_UNKNOWN;
  5011. } break;
  5012. case 12:
  5013. switch (hparams.n_ff()) {
  5014. case 3072: model.type = e_model::MODEL_160M; break;
  5015. default: model.type = e_model::MODEL_UNKNOWN;
  5016. } break;
  5017. case 16:
  5018. switch (hparams.n_ff()) {
  5019. case 8192: model.type = e_model::MODEL_1B; break;
  5020. default: model.type = e_model::MODEL_UNKNOWN;
  5021. } break;
  5022. case 24:
  5023. switch (hparams.n_ff()) {
  5024. case 4096: model.type = e_model::MODEL_410M; break;
  5025. case 8192: model.type = e_model::MODEL_1_4B; break;
  5026. default: model.type = e_model::MODEL_UNKNOWN;
  5027. } break;
  5028. case 32:
  5029. switch (hparams.n_ff()) {
  5030. case 10240: model.type = e_model::MODEL_2_8B; break;
  5031. case 16384: model.type = e_model::MODEL_6_9B; break;
  5032. default: model.type = e_model::MODEL_UNKNOWN;
  5033. } break;
  5034. case 36:
  5035. switch (hparams.n_ff()) {
  5036. case 20480: model.type = e_model::MODEL_12B; break;
  5037. default: model.type = e_model::MODEL_UNKNOWN;
  5038. } break;
  5039. case 44:
  5040. switch (hparams.n_ff()) {
  5041. case 24576: model.type = e_model::MODEL_20B; break;
  5042. default: model.type = e_model::MODEL_UNKNOWN;
  5043. } break;
  5044. default: model.type = e_model::MODEL_UNKNOWN;
  5045. }
  5046. } break;
  5047. case LLM_ARCH_ARCTIC:
  5048. {
  5049. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5050. if (hparams.n_expert == 128) {
  5051. switch (hparams.n_layer) {
  5052. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  5053. default: model.type = e_model::MODEL_UNKNOWN;
  5054. }
  5055. } else {
  5056. model.type = e_model::MODEL_UNKNOWN;
  5057. }
  5058. } break;
  5059. case LLM_ARCH_DEEPSEEK2:
  5060. {
  5061. bool is_lite = (hparams.n_layer == 27);
  5062. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5063. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  5064. if (!is_lite) {
  5065. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  5066. }
  5067. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  5068. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  5069. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  5070. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  5071. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  5072. switch (hparams.n_layer) {
  5073. case 27: model.type = e_model::MODEL_16B; break;
  5074. case 60: model.type = e_model::MODEL_236B; break;
  5075. default: model.type = e_model::MODEL_UNKNOWN;
  5076. }
  5077. } break;
  5078. case LLM_ARCH_CHATGLM:
  5079. {
  5080. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5081. switch (hparams.n_layer) {
  5082. case 28: model.type = e_model::MODEL_6B; break;
  5083. case 40: model.type = e_model::MODEL_9B; break;
  5084. default: model.type = e_model::MODEL_UNKNOWN;
  5085. }
  5086. } break;
  5087. case LLM_ARCH_BITNET:
  5088. {
  5089. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5090. switch (hparams.n_layer) {
  5091. case 26: model.type = e_model::MODEL_3B; break;
  5092. default: model.type = e_model::MODEL_UNKNOWN;
  5093. }
  5094. } break;
  5095. case LLM_ARCH_T5:
  5096. {
  5097. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5098. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5099. uint32_t dec_start_token_id;
  5100. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  5101. hparams.dec_start_token_id = dec_start_token_id;
  5102. }
  5103. switch (hparams.n_layer) {
  5104. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  5105. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  5106. case 12:
  5107. switch (hparams.n_ff()) {
  5108. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  5109. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  5110. default: model.type = e_model::MODEL_UNKNOWN;
  5111. } break;
  5112. case 24:
  5113. switch (hparams.n_ff()) {
  5114. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  5115. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  5116. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  5117. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  5118. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  5119. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  5120. default: model.type = e_model::MODEL_UNKNOWN;
  5121. } break;
  5122. default: model.type = e_model::MODEL_UNKNOWN;
  5123. }
  5124. } break;
  5125. case LLM_ARCH_T5ENCODER:
  5126. {
  5127. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5128. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  5129. model.type = e_model::MODEL_UNKNOWN;
  5130. } break;
  5131. case LLM_ARCH_JAIS:
  5132. {
  5133. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5134. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  5135. switch (hparams.n_layer) {
  5136. case 24: model.type = e_model::MODEL_1_3B; break;
  5137. case 40: model.type = e_model::MODEL_13B; break;
  5138. /* TODO: add variants */
  5139. default: model.type = e_model::MODEL_UNKNOWN;
  5140. }
  5141. } break;
  5142. case LLM_ARCH_NEMOTRON:
  5143. {
  5144. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  5145. switch (hparams.n_layer) {
  5146. case 32: model.type = e_model::MODEL_4B; break;
  5147. default: model.type = e_model::MODEL_UNKNOWN;
  5148. }
  5149. } break;
  5150. case LLM_ARCH_EXAONE:
  5151. {
  5152. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  5153. switch (hparams.n_layer) {
  5154. case 32: model.type = e_model::MODEL_8B; break;
  5155. default: model.type = e_model::MODEL_UNKNOWN;
  5156. }
  5157. } break;
  5158. default: (void)0;
  5159. }
  5160. model.ftype = ml.ftype;
  5161. if (hparams.f_max_alibi_bias > 0.0f) {
  5162. hparams.use_alibi = true;
  5163. }
  5164. hparams.rope_type = llama_rope_type(&model);
  5165. }
  5166. static void llm_load_vocab(
  5167. llama_model_loader & ml,
  5168. llama_model & model) {
  5169. auto & vocab = model.vocab;
  5170. struct gguf_context * ctx = ml.meta;
  5171. const auto kv = LLM_KV(model.arch);
  5172. // determine vocab type
  5173. {
  5174. std::string tokenizer_model;
  5175. std::string tokenizer_pre;
  5176. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  5177. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5178. if (tokenizer_model == "no_vocab") {
  5179. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  5180. // default special tokens
  5181. vocab.special_bos_id = -1;
  5182. vocab.special_eos_id = -1;
  5183. vocab.special_unk_id = -1;
  5184. vocab.special_sep_id = -1;
  5185. vocab.special_pad_id = -1;
  5186. vocab.special_cls_id = -1;
  5187. vocab.special_mask_id = -1;
  5188. vocab.linefeed_id = -1;
  5189. return;
  5190. } else if (tokenizer_model == "llama") {
  5191. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  5192. // default special tokens
  5193. vocab.special_bos_id = 1;
  5194. vocab.special_eos_id = 2;
  5195. vocab.special_unk_id = 0;
  5196. vocab.special_sep_id = -1;
  5197. vocab.special_pad_id = -1;
  5198. vocab.special_cls_id = -1;
  5199. vocab.special_mask_id = -1;
  5200. } else if (tokenizer_model == "bert") {
  5201. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  5202. // default special tokens
  5203. vocab.special_bos_id = -1;
  5204. vocab.special_eos_id = -1;
  5205. vocab.special_unk_id = 100;
  5206. vocab.special_sep_id = 102;
  5207. vocab.special_pad_id = 0;
  5208. vocab.special_cls_id = 101;
  5209. vocab.special_mask_id = 103;
  5210. } else if (tokenizer_model == "gpt2") {
  5211. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  5212. // read bpe merges and populate bpe ranks
  5213. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  5214. if (merges_keyidx == -1) {
  5215. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  5216. }
  5217. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  5218. for (int i = 0; i < n_merges; i++) {
  5219. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  5220. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5221. std::string first;
  5222. std::string second;
  5223. const size_t pos = word.find(' ', 1);
  5224. if (pos != std::string::npos) {
  5225. first = word.substr(0, pos);
  5226. second = word.substr(pos + 1);
  5227. }
  5228. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  5229. }
  5230. // default special tokens
  5231. vocab.special_bos_id = 11;
  5232. vocab.special_eos_id = 11;
  5233. vocab.special_unk_id = -1;
  5234. vocab.special_sep_id = -1;
  5235. vocab.special_pad_id = -1;
  5236. vocab.special_cls_id = -1;
  5237. vocab.special_mask_id = -1;
  5238. } else if (tokenizer_model == "t5") {
  5239. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  5240. // default special tokens
  5241. vocab.special_bos_id = -1;
  5242. vocab.special_eos_id = 1;
  5243. vocab.special_unk_id = 2;
  5244. vocab.special_sep_id = -1;
  5245. vocab.special_pad_id = 0;
  5246. vocab.special_cls_id = -1;
  5247. vocab.special_mask_id = -1;
  5248. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  5249. if (precompiled_charsmap_keyidx != -1) {
  5250. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  5251. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  5252. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  5253. #ifdef IS_BIG_ENDIAN
  5254. // correct endiannes of data in precompiled_charsmap binary blob
  5255. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  5256. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  5257. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  5258. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  5259. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  5260. for (size_t i = 0; i < xcda_array_size; ++i) {
  5261. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  5262. }
  5263. #endif
  5264. }
  5265. } else {
  5266. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  5267. }
  5268. // for now, only BPE models have pre-tokenizers
  5269. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  5270. vocab.tokenizer_add_space_prefix = false;
  5271. vocab.tokenizer_clean_spaces = true;
  5272. if (tokenizer_pre.empty()) {
  5273. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  5274. LLAMA_LOG_WARN("%s: \n", __func__);
  5275. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  5276. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  5277. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  5278. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  5279. LLAMA_LOG_WARN("%s: \n", __func__);
  5280. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5281. } else if (tokenizer_pre == "default") {
  5282. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5283. } else if (
  5284. tokenizer_pre == "llama3" ||
  5285. tokenizer_pre == "llama-v3" ||
  5286. tokenizer_pre == "llama-bpe") {
  5287. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  5288. vocab.tokenizer_ignore_merges = true;
  5289. vocab.tokenizer_add_bos = true;
  5290. } else if (
  5291. tokenizer_pre == "deepseek-llm") {
  5292. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  5293. vocab.tokenizer_clean_spaces = false;
  5294. } else if (
  5295. tokenizer_pre == "deepseek-coder") {
  5296. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  5297. vocab.tokenizer_clean_spaces = false;
  5298. } else if (
  5299. tokenizer_pre == "falcon") {
  5300. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  5301. } else if (
  5302. tokenizer_pre == "mpt") {
  5303. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  5304. } else if (
  5305. tokenizer_pre == "starcoder") {
  5306. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  5307. } else if (
  5308. tokenizer_pre == "gpt-2" ||
  5309. tokenizer_pre == "phi-2" ||
  5310. tokenizer_pre == "jina-es" ||
  5311. tokenizer_pre == "jina-de" ||
  5312. tokenizer_pre == "jina-v2-es" ||
  5313. tokenizer_pre == "jina-v2-de" ||
  5314. tokenizer_pre == "jina-v2-code") {
  5315. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  5316. } else if (
  5317. tokenizer_pre == "refact") {
  5318. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  5319. } else if (
  5320. tokenizer_pre == "command-r") {
  5321. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  5322. vocab.tokenizer_clean_spaces = false;
  5323. } else if (
  5324. tokenizer_pre == "qwen2") {
  5325. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  5326. vocab.tokenizer_clean_spaces = false;
  5327. } else if (
  5328. tokenizer_pre == "stablelm2") {
  5329. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  5330. } else if (
  5331. tokenizer_pre == "olmo") {
  5332. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  5333. } else if (
  5334. tokenizer_pre == "dbrx") {
  5335. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  5336. } else if (
  5337. tokenizer_pre == "smaug-bpe") {
  5338. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  5339. } else if (
  5340. tokenizer_pre == "poro-chat") {
  5341. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  5342. vocab.tokenizer_clean_spaces = false;
  5343. } else if (
  5344. tokenizer_pre == "chatglm-bpe") {
  5345. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  5346. vocab.special_bos_id = -1;
  5347. } else if (
  5348. tokenizer_pre == "viking") {
  5349. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  5350. vocab.tokenizer_clean_spaces = false;
  5351. } else if (
  5352. tokenizer_pre == "jais") {
  5353. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  5354. } else if (
  5355. tokenizer_pre == "tekken") {
  5356. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  5357. vocab.tokenizer_clean_spaces = false;
  5358. vocab.tokenizer_ignore_merges = true;
  5359. vocab.tokenizer_add_bos = true;
  5360. } else if (
  5361. tokenizer_pre == "smollm") {
  5362. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  5363. vocab.tokenizer_clean_spaces = false;
  5364. } else if (
  5365. tokenizer_pre == "codeshell") {
  5366. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  5367. } else if (
  5368. tokenizer_pre == "bloom") {
  5369. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_BLOOM;
  5370. } else if (
  5371. tokenizer_pre == "gpt3-finnish") {
  5372. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT3_FINNISH;
  5373. } else if (
  5374. tokenizer_pre == "exaone") {
  5375. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_EXAONE;
  5376. } else {
  5377. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  5378. }
  5379. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5380. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5381. vocab.tokenizer_add_space_prefix = true;
  5382. vocab.tokenizer_clean_spaces = false;
  5383. vocab.tokenizer_add_bos = true;
  5384. vocab.tokenizer_add_eos = false;
  5385. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5386. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5387. vocab.tokenizer_add_space_prefix = false;
  5388. vocab.tokenizer_clean_spaces = true;
  5389. vocab.tokenizer_add_bos = true;
  5390. vocab.tokenizer_add_eos = false;
  5391. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  5392. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5393. vocab.tokenizer_add_bos = false;
  5394. vocab.tokenizer_add_eos = true;
  5395. } else {
  5396. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  5397. }
  5398. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  5399. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  5400. }
  5401. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  5402. if (token_idx == -1) {
  5403. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  5404. }
  5405. const float * scores = nullptr;
  5406. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  5407. if (score_idx != -1) {
  5408. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  5409. }
  5410. const int * toktypes = nullptr;
  5411. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  5412. if (toktype_idx != -1) {
  5413. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  5414. }
  5415. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  5416. vocab.id_to_token.resize(n_vocab);
  5417. for (uint32_t i = 0; i < n_vocab; i++) {
  5418. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  5419. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  5420. vocab.token_to_id[word] = i;
  5421. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  5422. auto & token_data = vocab.id_to_token[i];
  5423. token_data.text = std::move(word);
  5424. token_data.score = scores ? scores[i] : 0.0f;
  5425. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  5426. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  5427. switch(toktypes[i]) {
  5428. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  5429. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  5430. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  5431. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  5432. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  5433. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  5434. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5435. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  5436. }
  5437. }
  5438. }
  5439. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  5440. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  5441. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  5442. // For Fill-In-the-Middle (FIM)/infill models which where converted
  5443. // prior to support of FIM special tokens in GGUF, the following
  5444. // will allow those models to continue to work. The general names
  5445. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  5446. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  5447. // new versions of these models have been published.
  5448. std::string gen_name;
  5449. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  5450. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  5451. [](unsigned char c){ return std::tolower(c); });
  5452. if (gen_name.find("code") != std::string::npos) {
  5453. if (model.arch == LLM_ARCH_LLAMA
  5454. && 32010 < vocab.id_to_token.size()
  5455. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  5456. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  5457. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  5458. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  5459. vocab.special_prefix_id = 32007;
  5460. vocab.special_suffix_id = 32008;
  5461. vocab.special_middle_id = 32009;
  5462. vocab.special_eot_id = 32010;
  5463. } else if (model.arch == LLM_ARCH_GEMMA
  5464. && 107 < vocab.id_to_token.size()
  5465. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  5466. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  5467. && vocab.id_to_token[68].text == "<|fim_middle|>"
  5468. && vocab.id_to_token[107].text == "<end_of_turn>") {
  5469. vocab.special_prefix_id = 67;
  5470. vocab.special_suffix_id = 69;
  5471. vocab.special_middle_id = 68;
  5472. // TODO: this is not EOT, it is "file separator" token, needs fix
  5473. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  5474. //vocab.special_eot_id = 70;
  5475. vocab.special_eot_id = 107;
  5476. }
  5477. }
  5478. try {
  5479. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  5480. } catch (const std::exception & e) {
  5481. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  5482. vocab.linefeed_id = vocab.special_pad_id;
  5483. }
  5484. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  5485. vocab.linefeed_id = vocab.special_pad_id;
  5486. } else {
  5487. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  5488. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  5489. vocab.linefeed_id = ids[0];
  5490. }
  5491. // special tokens
  5492. {
  5493. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  5494. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  5495. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  5496. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  5497. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  5498. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  5499. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  5500. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  5501. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  5502. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  5503. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  5504. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  5505. { LLM_KV_TOKENIZER_EOM_ID, vocab.special_eom_id },
  5506. };
  5507. for (const auto & it : special_token_types) {
  5508. const std::string & key = kv(std::get<0>(it));
  5509. int32_t & id = std::get<1>(it);
  5510. uint32_t new_id;
  5511. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  5512. continue;
  5513. }
  5514. if (new_id >= vocab.id_to_token.size()) {
  5515. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  5516. __func__, key.c_str(), new_id, id);
  5517. } else {
  5518. id = new_id;
  5519. }
  5520. }
  5521. // Handle add_bos_token and add_eos_token
  5522. {
  5523. bool temp = true;
  5524. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  5525. vocab.tokenizer_add_bos = temp;
  5526. }
  5527. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  5528. vocab.tokenizer_add_eos = temp;
  5529. }
  5530. }
  5531. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  5532. //
  5533. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  5534. // for now, we apply this workaround to find the EOT token based on its text
  5535. if (vocab.special_eot_id == -1) {
  5536. for (const auto & t : vocab.token_to_id) {
  5537. if (
  5538. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  5539. // need to fix convert script
  5540. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  5541. (t.first == "<|eot_id|>" ||
  5542. t.first == "<|im_end|>" ||
  5543. t.first == "<|end|>" ||
  5544. t.first == "<end_of_turn>" ||
  5545. t.first == "<|endoftext|>"
  5546. )
  5547. ) {
  5548. vocab.special_eot_id = t.second;
  5549. break;
  5550. }
  5551. }
  5552. }
  5553. // find EOM token: "<|eom_id|>"
  5554. //
  5555. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOM_ID
  5556. // for now, we apply this workaround to find the EOM token based on its text
  5557. if (vocab.special_eom_id == -1) {
  5558. const auto & t = vocab.token_to_id.find("<|eom_id|>");
  5559. if (t != vocab.token_to_id.end()) {
  5560. vocab.special_eom_id = t->second;
  5561. }
  5562. }
  5563. }
  5564. // build special tokens cache
  5565. {
  5566. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  5567. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  5568. vocab.cache_special_tokens.push_back(id);
  5569. }
  5570. }
  5571. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  5572. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  5573. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  5574. }
  5575. );
  5576. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  5577. }
  5578. // build token to piece cache
  5579. {
  5580. size_t size_cache = 0;
  5581. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  5582. for (uint32_t id = 0; id < n_vocab; ++id) {
  5583. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  5584. size_cache += cache_token_to_piece[id].size();
  5585. }
  5586. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  5587. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  5588. }
  5589. // Handle per token attributes
  5590. //NOTE: Each model customizes per token attributes.
  5591. //NOTE: Per token attributes are missing from the GGUF file.
  5592. //TODO: Extract attributes from GGUF file.
  5593. {
  5594. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  5595. for (auto substr : substrs) {
  5596. if (str.find(substr) < std::string::npos) {
  5597. return true;
  5598. }
  5599. }
  5600. return false;
  5601. };
  5602. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  5603. uint32_t current = vocab.id_to_token.at(id).attr;
  5604. current = value ? (current | attr) : (current & ~attr);
  5605. vocab.id_to_token[id].attr = (llama_token_attr) current;
  5606. };
  5607. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  5608. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  5609. };
  5610. std::string model_name;
  5611. std::string tokenizer_pre;
  5612. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  5613. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5614. // model name to lowercase
  5615. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  5616. [] (const std::string::value_type x) {
  5617. return std::tolower(x);
  5618. }
  5619. );
  5620. // set attributes by model/tokenizer name
  5621. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  5622. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  5623. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  5624. for (auto id : vocab.cache_special_tokens) {
  5625. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5626. }
  5627. for (auto token : {"</s>"}) {
  5628. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5629. }
  5630. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  5631. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  5632. }
  5633. }
  5634. }
  5635. }
  5636. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  5637. const auto & hparams = model.hparams;
  5638. const auto & vocab = model.vocab;
  5639. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  5640. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  5641. bool is_var = false;
  5642. std::vector<uint32_t> v;
  5643. for (uint32_t i = 0; i < n; ++i) {
  5644. v.push_back(f(i));
  5645. if (v[i] != v[0]) {
  5646. is_var = true;
  5647. }
  5648. }
  5649. std::stringstream ss;
  5650. if (is_var) {
  5651. ss << "[";
  5652. for (uint32_t i = 0; i < n; ++i) {
  5653. ss << v[i];
  5654. if (i < n - 1) {
  5655. ss << ", ";
  5656. }
  5657. }
  5658. ss << "]";
  5659. } else {
  5660. ss << v[0];
  5661. }
  5662. return ss.str();
  5663. };
  5664. // hparams
  5665. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  5666. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  5667. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  5668. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  5669. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  5670. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  5671. if (!hparams.vocab_only) {
  5672. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  5673. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  5674. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  5675. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  5676. 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());
  5677. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  5678. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  5679. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  5680. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  5681. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  5682. 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());
  5683. 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());
  5684. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  5685. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  5686. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  5687. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  5688. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  5689. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  5690. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  5691. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  5692. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  5693. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  5694. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  5695. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  5696. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  5697. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  5698. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  5699. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  5700. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  5701. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  5702. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  5703. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  5704. LLAMA_LOG_INFO("%s: ssm_dt_b_c_rms = %d\n", __func__, hparams.ssm_dt_b_c_rms);
  5705. }
  5706. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  5707. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  5708. if (ml.n_elements >= 1e12) {
  5709. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  5710. } else if (ml.n_elements >= 1e9) {
  5711. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  5712. } else if (ml.n_elements >= 1e6) {
  5713. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  5714. } else {
  5715. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  5716. }
  5717. if (ml.n_bytes < GiB) {
  5718. 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);
  5719. } else {
  5720. 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);
  5721. }
  5722. // general kv
  5723. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  5724. // special tokens
  5725. 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() ); }
  5726. 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() ); }
  5727. 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() ); }
  5728. 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() ); }
  5729. 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() ); }
  5730. 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() ); }
  5731. 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() ); }
  5732. 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() ); }
  5733. 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() ); }
  5734. 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() ); }
  5735. 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() ); }
  5736. 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() ); }
  5737. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  5738. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  5739. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  5740. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  5741. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  5742. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5743. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  5744. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  5745. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  5746. }
  5747. if (model.arch == LLM_ARCH_QWEN2MOE) {
  5748. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5749. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  5750. }
  5751. }
  5752. // Returns false if cancelled by progress_callback
  5753. static bool llm_load_tensors(
  5754. llama_model_loader & ml,
  5755. llama_model & model,
  5756. int n_gpu_layers,
  5757. enum llama_split_mode split_mode,
  5758. int main_gpu,
  5759. const float * tensor_split,
  5760. bool use_mlock,
  5761. llama_progress_callback progress_callback,
  5762. void * progress_callback_user_data) {
  5763. model.t_start_us = ggml_time_us();
  5764. auto & hparams = model.hparams;
  5765. model.split_mode = split_mode;
  5766. model.main_gpu = main_gpu;
  5767. model.n_gpu_layers = n_gpu_layers;
  5768. const int n_layer = hparams.n_layer;
  5769. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  5770. bool use_mmap_buffer = true;
  5771. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  5772. model.buft_input = llama_default_buffer_type_cpu(true);
  5773. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  5774. model.buft_layer.resize(n_layer);
  5775. // assign cpu layers
  5776. for (int i = 0; i < i_gpu_start; ++i) {
  5777. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  5778. }
  5779. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  5780. // calculate the split points
  5781. int device_count = llama_get_device_count(model);
  5782. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  5783. std::vector<float> splits(device_count);
  5784. if (all_zero) {
  5785. // default split, by free memory
  5786. for (int i = 0; i < device_count; ++i) {
  5787. splits[i] = llama_get_device_memory(model, i);
  5788. }
  5789. } else {
  5790. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  5791. }
  5792. // sum and normalize the splits to get the split points
  5793. float split_sum = 0.0f;
  5794. for (int i = 0; i < device_count; ++i) {
  5795. split_sum += splits[i];
  5796. splits[i] = split_sum;
  5797. }
  5798. for (int i = 0; i < device_count; ++i) {
  5799. splits[i] /= split_sum;
  5800. }
  5801. // assign the repeating layers to the devices according to the splits
  5802. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  5803. for (int i = i_gpu_start; i < n_layer; ++i) {
  5804. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  5805. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  5806. }
  5807. // assign the output layer
  5808. if (n_gpu_layers > n_layer) {
  5809. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  5810. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  5811. } else {
  5812. model.buft_output = llama_default_buffer_type_cpu(true);
  5813. }
  5814. } else {
  5815. ggml_backend_buffer_type_t split_buft;
  5816. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  5817. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  5818. } else {
  5819. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  5820. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  5821. }
  5822. // assign the repeating layers
  5823. for (int i = i_gpu_start; i < n_layer; ++i) {
  5824. model.buft_layer[i] = {
  5825. split_buft,
  5826. llama_default_buffer_type_offload(model, main_gpu)
  5827. };
  5828. }
  5829. // assign the output layer
  5830. if (n_gpu_layers > n_layer) {
  5831. model.buft_output = {
  5832. split_buft,
  5833. llama_default_buffer_type_offload(model, main_gpu)
  5834. };
  5835. } else {
  5836. model.buft_output = llama_default_buffer_type_cpu(true);
  5837. }
  5838. }
  5839. // count used buffer types
  5840. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  5841. buft_layer_count[model.buft_input.buft]++;
  5842. buft_layer_count[model.buft_input.buft_matrix]++;
  5843. buft_layer_count[model.buft_output.buft]++;
  5844. buft_layer_count[model.buft_output.buft_matrix]++;
  5845. for (int i = 0; i < n_layer; ++i) {
  5846. buft_layer_count[model.buft_layer[i].buft]++;
  5847. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  5848. }
  5849. // create one context per buffer type
  5850. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  5851. // for moe merged tensors
  5852. ctx_size += ggml_tensor_overhead()*n_layer*3;
  5853. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  5854. for (auto & it : buft_layer_count) {
  5855. struct ggml_init_params params = {
  5856. /*.mem_size =*/ ctx_size,
  5857. /*.mem_buffer =*/ NULL,
  5858. /*.no_alloc =*/ true,
  5859. };
  5860. ggml_context * ctx = ggml_init(params);
  5861. if (!ctx) {
  5862. throw std::runtime_error(format("failed to create context"));
  5863. }
  5864. ctx_map[it.first] = ctx;
  5865. model.ctxs.push_back(ctx);
  5866. }
  5867. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  5868. // create tensors for the weights
  5869. {
  5870. // note: cast to int64_t since we will use these for the tensor dimensions
  5871. const int64_t n_head = hparams.n_head();
  5872. const int64_t n_head_kv = hparams.n_head_kv();
  5873. const int64_t n_embd = hparams.n_embd;
  5874. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5875. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5876. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5877. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5878. const int64_t n_ff = hparams.n_ff();
  5879. const int64_t n_embd_gqa = n_embd_v_gqa;
  5880. const int64_t n_vocab = hparams.n_vocab;
  5881. const int64_t n_vocab_type = hparams.n_vocab_type;
  5882. const int64_t n_rot = hparams.n_rot;
  5883. const int64_t n_expert = hparams.n_expert;
  5884. const int64_t n_expert_used = hparams.n_expert_used;
  5885. const int64_t n_ctx_train = hparams.n_ctx_train;
  5886. if (n_expert > 0 && hparams.n_expert_used == 0) {
  5887. throw std::runtime_error("model has expert layers but no expert layers are used");
  5888. }
  5889. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  5890. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  5891. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  5892. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  5893. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  5894. model.layers.resize(n_layer);
  5895. const auto tn = LLM_TN(model.arch);
  5896. switch (model.arch) {
  5897. case LLM_ARCH_LLAMA:
  5898. case LLM_ARCH_REFACT:
  5899. case LLM_ARCH_MINICPM:
  5900. {
  5901. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5902. // output
  5903. {
  5904. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5905. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5906. // if output is NULL, init from the input tok embed
  5907. if (model.output == NULL) {
  5908. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5909. }
  5910. }
  5911. for (int i = 0; i < n_layer; ++i) {
  5912. ggml_context * ctx_layer = ctx_for_layer(i);
  5913. ggml_context * ctx_split = ctx_for_layer_split(i);
  5914. auto & layer = model.layers[i];
  5915. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5916. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  5917. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5918. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5919. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  5920. // optional bias tensors
  5921. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5922. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5923. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5924. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5925. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5926. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  5927. if (n_expert == 0) {
  5928. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5929. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5930. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5931. // optional MLP bias
  5932. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5933. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5934. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5935. } else {
  5936. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5937. 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);
  5938. if (layer.ffn_gate_exps) {
  5939. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5940. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5941. } else {
  5942. // merge split expert into a single tensor for compatibility with older models
  5943. // requires disabling mmap
  5944. use_mmap_buffer = false;
  5945. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5946. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5947. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5948. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5949. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5950. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5951. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5952. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5953. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5954. for (uint32_t x = 0; x < n_expert; ++x) {
  5955. // the individual experts are loaded into a view of the merged tensor
  5956. 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);
  5957. 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);
  5958. 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);
  5959. }
  5960. }
  5961. }
  5962. }
  5963. } break;
  5964. case LLM_ARCH_GROK:
  5965. {
  5966. if (n_expert == 0) {
  5967. throw std::runtime_error("Grok model cannot have zero experts");
  5968. }
  5969. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5970. // output
  5971. {
  5972. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5973. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5974. // if output is NULL, init from the input tok embed
  5975. if (model.output == NULL) {
  5976. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5977. }
  5978. }
  5979. for (int i = 0; i < n_layer; ++i) {
  5980. ggml_context * ctx_layer = ctx_for_layer(i);
  5981. ggml_context * ctx_split = ctx_for_layer_split(i);
  5982. auto & layer = model.layers[i];
  5983. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5984. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5985. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5986. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5987. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5988. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5989. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5990. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5991. 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);
  5992. if (layer.ffn_gate_exps) {
  5993. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5994. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5995. } else {
  5996. // merge split expert into a single tensor for compatibility with older models
  5997. // requires disabling mmap
  5998. use_mmap_buffer = false;
  5999. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  6000. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  6001. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  6002. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  6003. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  6004. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  6005. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  6006. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  6007. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  6008. for (uint32_t x = 0; x < n_expert; ++x) {
  6009. // the individual experts are loaded into a view of the merged tensor
  6010. 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);
  6011. 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);
  6012. 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);
  6013. }
  6014. }
  6015. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6016. }
  6017. } break;
  6018. case LLM_ARCH_DBRX:
  6019. {
  6020. if (n_expert == 0) {
  6021. throw std::runtime_error("DBRX model cannot have zero experts");
  6022. }
  6023. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6024. // output
  6025. {
  6026. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6027. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6028. }
  6029. for (int i = 0; i < n_layer; ++i) {
  6030. ggml_context * ctx_layer = ctx_for_layer(i);
  6031. ggml_context * ctx_split = ctx_for_layer_split(i);
  6032. auto & layer = model.layers[i];
  6033. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6034. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6035. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6036. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6037. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6038. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6039. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  6040. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6041. }
  6042. } break;
  6043. case LLM_ARCH_BAICHUAN:
  6044. {
  6045. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6046. {
  6047. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6048. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6049. }
  6050. for (int i = 0; i < n_layer; ++i) {
  6051. ggml_context * ctx_layer = ctx_for_layer(i);
  6052. ggml_context * ctx_split = ctx_for_layer_split(i);
  6053. auto & layer = model.layers[i];
  6054. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6055. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6056. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6057. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6058. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6059. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6060. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6061. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6062. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6063. }
  6064. } break;
  6065. case LLM_ARCH_FALCON:
  6066. {
  6067. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6068. // output
  6069. {
  6070. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6071. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6072. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6073. if (!model.output) {
  6074. 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
  6075. }
  6076. }
  6077. for (int i = 0; i < n_layer; ++i) {
  6078. ggml_context * ctx_layer = ctx_for_layer(i);
  6079. ggml_context * ctx_split = ctx_for_layer_split(i);
  6080. auto & layer = model.layers[i];
  6081. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6082. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6083. 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);
  6084. 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);
  6085. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6086. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6087. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6088. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6089. }
  6090. } break;
  6091. case LLM_ARCH_STARCODER:
  6092. {
  6093. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6094. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6095. // output
  6096. {
  6097. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6098. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6099. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6100. if (!model.output) {
  6101. // needs to be on GPU
  6102. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6103. }
  6104. }
  6105. for (int i = 0; i < n_layer; ++i) {
  6106. ggml_context * ctx_layer = ctx_for_layer(i);
  6107. ggml_context * ctx_split = ctx_for_layer_split(i);
  6108. auto & layer = model.layers[i];
  6109. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6110. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6111. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6112. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6113. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6114. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6115. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6116. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6117. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6118. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6119. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6120. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6121. }
  6122. } break;
  6123. case LLM_ARCH_BERT:
  6124. case LLM_ARCH_NOMIC_BERT:
  6125. {
  6126. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6127. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  6128. if (model.arch == LLM_ARCH_BERT) {
  6129. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6130. }
  6131. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6132. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6133. for (int i = 0; i < n_layer; ++i) {
  6134. ggml_context * ctx_layer = ctx_for_layer(i);
  6135. ggml_context * ctx_split = ctx_for_layer_split(i);
  6136. auto & layer = model.layers[i];
  6137. if (model.arch == LLM_ARCH_BERT) {
  6138. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6139. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6140. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6141. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6142. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6143. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6144. } else {
  6145. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6146. }
  6147. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6148. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  6149. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6150. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6151. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6152. if (model.arch == LLM_ARCH_BERT) {
  6153. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6154. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6155. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6156. } else {
  6157. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6158. }
  6159. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6160. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6161. }
  6162. } break;
  6163. case LLM_ARCH_JINA_BERT_V2:
  6164. {
  6165. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  6166. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  6167. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  6168. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  6169. for (int i = 0; i < n_layer; ++i) {
  6170. ggml_context * ctx_layer = ctx_for_layer(i);
  6171. ggml_context * ctx_split = ctx_for_layer_split(i);
  6172. auto & layer = model.layers[i]; // JinaBertLayer
  6173. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6174. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6175. 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);
  6176. 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);
  6177. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6178. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6179. 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);
  6180. 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);
  6181. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6182. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6183. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  6184. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  6185. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  6186. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  6187. 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);
  6188. 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);
  6189. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6190. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6191. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6192. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6193. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  6194. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  6195. }
  6196. } break;
  6197. case LLM_ARCH_BLOOM:
  6198. {
  6199. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6200. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  6201. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  6202. // output
  6203. {
  6204. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6205. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6206. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6207. }
  6208. for (int i = 0; i < n_layer; ++i) {
  6209. ggml_context * ctx_layer = ctx_for_layer(i);
  6210. ggml_context * ctx_split = ctx_for_layer_split(i);
  6211. auto & layer = model.layers[i];
  6212. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6213. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6214. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6215. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6216. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6217. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6218. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6219. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6220. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6221. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6222. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6223. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6224. }
  6225. } break;
  6226. case LLM_ARCH_MPT:
  6227. {
  6228. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6229. 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);
  6230. // output
  6231. {
  6232. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6233. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6234. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6235. if (!model.output) {
  6236. 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
  6237. }
  6238. }
  6239. for (int i = 0; i < n_layer; ++i) {
  6240. ggml_context * ctx_layer = ctx_for_layer(i);
  6241. ggml_context * ctx_split = ctx_for_layer_split(i);
  6242. auto & layer = model.layers[i];
  6243. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6244. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6245. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6246. 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);
  6247. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6248. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6249. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6250. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6251. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6252. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6253. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6254. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6255. 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);
  6256. 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);
  6257. 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);
  6258. 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);
  6259. // AWQ ScaleActivation layer
  6260. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6261. }
  6262. } break;
  6263. case LLM_ARCH_STABLELM:
  6264. {
  6265. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6266. // output
  6267. {
  6268. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6269. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6270. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6271. }
  6272. for (int i = 0; i < n_layer; ++i) {
  6273. ggml_context * ctx_layer = ctx_for_layer(i);
  6274. ggml_context * ctx_split = ctx_for_layer_split(i);
  6275. auto & layer = model.layers[i];
  6276. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6277. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6278. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6279. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6280. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6281. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6282. // optional bias tensors, present in Stable LM 2 1.6B
  6283. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6284. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6285. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6286. // optional q and k layernorms, present in StableLM 2 12B
  6287. 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);
  6288. 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);
  6289. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  6290. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6291. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6292. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6294. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6295. }
  6296. } break;
  6297. case LLM_ARCH_QWEN:
  6298. {
  6299. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6300. // output
  6301. {
  6302. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6303. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6304. }
  6305. for (int i = 0; i < n_layer; ++i) {
  6306. ggml_context * ctx_layer = ctx_for_layer(i);
  6307. ggml_context * ctx_split = ctx_for_layer_split(i);
  6308. auto & layer = model.layers[i];
  6309. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6310. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  6311. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  6312. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6313. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6314. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  6315. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  6316. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  6317. }
  6318. } break;
  6319. case LLM_ARCH_QWEN2:
  6320. {
  6321. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6322. // output
  6323. {
  6324. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6325. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6326. // if output is NULL, init from the input tok embed
  6327. if (model.output == NULL) {
  6328. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6329. }
  6330. }
  6331. for (int i = 0; i < n_layer; ++i) {
  6332. ggml_context * ctx_layer = ctx_for_layer(i);
  6333. ggml_context * ctx_split = ctx_for_layer_split(i);
  6334. auto & layer = model.layers[i];
  6335. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6336. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6337. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6338. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6339. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6340. // optional bias tensors
  6341. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6342. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6343. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6344. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6345. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6346. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6347. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6348. }
  6349. } break;
  6350. case LLM_ARCH_QWEN2MOE:
  6351. {
  6352. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6353. // output
  6354. {
  6355. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6356. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6357. }
  6358. for (int i = 0; i < n_layer; ++i) {
  6359. ggml_context * ctx_layer = ctx_for_layer(i);
  6360. ggml_context * ctx_split = ctx_for_layer_split(i);
  6361. auto & layer = model.layers[i];
  6362. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6363. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6364. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6365. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6366. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6367. // optional bias tensors
  6368. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6369. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6370. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6371. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6372. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6373. GGML_ASSERT(n_expert > 0);
  6374. GGML_ASSERT(n_expert_used > 0);
  6375. // MoE branch
  6376. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  6377. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6378. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6379. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6380. // Shared expert branch
  6381. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  6382. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  6383. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  6384. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  6385. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  6386. }
  6387. } break;
  6388. case LLM_ARCH_PHI2:
  6389. {
  6390. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6391. // output
  6392. {
  6393. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6394. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6395. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6396. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  6397. }
  6398. for (int i = 0; i < n_layer; ++i) {
  6399. ggml_context * ctx_layer = ctx_for_layer(i);
  6400. ggml_context * ctx_split = ctx_for_layer_split(i);
  6401. auto & layer = model.layers[i];
  6402. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6403. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6404. 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);
  6405. 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);
  6406. if (layer.wqkv == nullptr) {
  6407. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6408. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6409. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6410. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6411. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6412. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6413. }
  6414. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6415. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6416. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6417. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6418. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6419. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6420. }
  6421. } break;
  6422. case LLM_ARCH_PHI3:
  6423. {
  6424. const int64_t n_embd_head = n_embd / n_head;
  6425. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  6426. // output
  6427. {
  6428. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  6429. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  6430. }
  6431. for (int i = 0; i < n_layer; ++i) {
  6432. ggml_context * ctx_layer = ctx_for_layer(i);
  6433. ggml_context * ctx_split = ctx_for_layer_split(i);
  6434. auto & layer = model.layers[i];
  6435. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  6436. 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);
  6437. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  6438. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  6439. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  6440. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  6441. 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));
  6442. 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));
  6443. }
  6444. } break;
  6445. case LLM_ARCH_PLAMO:
  6446. {
  6447. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6448. // output
  6449. {
  6450. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6451. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6452. }
  6453. for (int i = 0; i < n_layer; ++i) {
  6454. ggml_context * ctx_layer = ctx_for_layer(i);
  6455. ggml_context * ctx_split = ctx_for_layer_split(i);
  6456. auto & layer = model.layers[i];
  6457. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6458. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6459. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6460. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6461. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6462. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6463. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6464. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6465. }
  6466. } break;
  6467. case LLM_ARCH_GPT2:
  6468. {
  6469. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6470. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  6471. // output
  6472. {
  6473. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6474. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6475. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6476. }
  6477. for (int i = 0; i < n_layer; ++i) {
  6478. ggml_context * ctx_layer = ctx_for_layer(i);
  6479. ggml_context * ctx_split = ctx_for_layer_split(i);
  6480. auto & layer = model.layers[i];
  6481. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6482. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6483. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6484. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6485. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6486. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6487. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6488. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6489. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6490. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6491. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6492. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6493. }
  6494. } break;
  6495. case LLM_ARCH_CODESHELL:
  6496. {
  6497. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6498. // output
  6499. {
  6500. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6501. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6502. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6503. }
  6504. for (int i = 0; i < n_layer; ++i) {
  6505. ggml_context * ctx_layer = ctx_for_layer(i);
  6506. ggml_context * ctx_split = ctx_for_layer_split(i);
  6507. auto & layer = model.layers[i];
  6508. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6509. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6510. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6511. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6512. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6513. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6514. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6515. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6516. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6517. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6518. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6519. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6520. }
  6521. } break;
  6522. case LLM_ARCH_ORION:
  6523. {
  6524. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6525. {
  6526. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6527. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6528. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6529. }
  6530. for (int i = 0; i < n_layer; ++i) {
  6531. ggml_context * ctx_layer = ctx_for_layer(i);
  6532. ggml_context * ctx_split = ctx_for_layer_split(i);
  6533. auto & layer = model.layers[i];
  6534. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6535. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6536. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6537. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6538. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6539. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6540. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6541. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6542. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6543. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6544. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6545. }
  6546. } break;
  6547. case LLM_ARCH_INTERNLM2:
  6548. {
  6549. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6550. // output
  6551. {
  6552. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6553. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6554. }
  6555. for (int i = 0; i < n_layer; ++i) {
  6556. ggml_context * ctx_layer = ctx_for_layer(i);
  6557. ggml_context * ctx_split = ctx_for_layer_split(i);
  6558. auto & layer = model.layers[i];
  6559. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6560. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6561. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6562. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6563. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6564. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6565. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6566. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6567. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6568. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6569. }
  6570. } break;
  6571. case LLM_ARCH_GEMMA:
  6572. {
  6573. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6574. // output
  6575. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6576. 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
  6577. for (int i = 0; i < n_layer; ++i) {
  6578. ggml_context * ctx_layer = ctx_for_layer(i);
  6579. ggml_context * ctx_split = ctx_for_layer_split(i);
  6580. auto & layer = model.layers[i];
  6581. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6582. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6583. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6584. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6585. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6586. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6587. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6588. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6589. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6590. }
  6591. } break;
  6592. case LLM_ARCH_GEMMA2:
  6593. {
  6594. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6595. // output
  6596. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6597. 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
  6598. for (int i = 0; i < n_layer; ++i) {
  6599. ggml_context * ctx_layer = ctx_for_layer(i);
  6600. ggml_context * ctx_split = ctx_for_layer_split(i);
  6601. auto & layer = model.layers[i];
  6602. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6603. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6604. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6605. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6606. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6607. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  6608. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6609. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6610. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6611. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6612. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  6613. }
  6614. } break;
  6615. case LLM_ARCH_STARCODER2:
  6616. {
  6617. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6618. // output
  6619. {
  6620. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6621. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6622. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6623. // if output is NULL, init from the input tok embed
  6624. if (model.output == NULL) {
  6625. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6626. }
  6627. }
  6628. for (int i = 0; i < n_layer; ++i) {
  6629. ggml_context * ctx_layer = ctx_for_layer(i);
  6630. ggml_context * ctx_split = ctx_for_layer_split(i);
  6631. auto & layer = model.layers[i];
  6632. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6633. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6634. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6635. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6636. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6637. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6638. // optional bias tensors
  6639. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6640. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6641. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6642. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6643. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6644. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6645. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6646. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6647. // optional bias tensors
  6648. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6649. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  6650. }
  6651. } break;
  6652. case LLM_ARCH_MAMBA:
  6653. {
  6654. const int64_t d_conv = hparams.ssm_d_conv;
  6655. const int64_t d_inner = hparams.ssm_d_inner;
  6656. const int64_t d_state = hparams.ssm_d_state;
  6657. const int64_t dt_rank = hparams.ssm_dt_rank;
  6658. // only an expansion factor of 2 is supported for now
  6659. GGML_ASSERT(2 * n_embd == d_inner);
  6660. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6661. // output
  6662. {
  6663. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6664. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6665. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  6666. if (model.output == NULL) {
  6667. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6668. }
  6669. }
  6670. for (int i = 0; i < n_layer; ++i) {
  6671. ggml_context * ctx_layer = ctx_for_layer(i);
  6672. ggml_context * ctx_split = ctx_for_layer_split(i);
  6673. auto & layer = model.layers[i];
  6674. // norm
  6675. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6676. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  6677. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  6678. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  6679. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  6680. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  6681. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  6682. // no "weight" suffix for these
  6683. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  6684. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  6685. // out_proj
  6686. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  6687. }
  6688. } break;
  6689. case LLM_ARCH_XVERSE:
  6690. {
  6691. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6692. {
  6693. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6694. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6695. }
  6696. for (int i = 0; i < n_layer; ++i) {
  6697. ggml_context * ctx_layer = ctx_for_layer(i);
  6698. ggml_context * ctx_split = ctx_for_layer_split(i);
  6699. auto & layer = model.layers[i];
  6700. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6701. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6702. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6703. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6704. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6705. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6706. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6707. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6708. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6709. }
  6710. } break;
  6711. case LLM_ARCH_COMMAND_R:
  6712. {
  6713. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6714. // output
  6715. {
  6716. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6717. // init output from the input tok embed
  6718. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6719. }
  6720. for (int i = 0; i < n_layer; ++i) {
  6721. ggml_context * ctx_layer = ctx_for_layer(i);
  6722. ggml_context * ctx_split = ctx_for_layer_split(i);
  6723. auto & layer = model.layers[i];
  6724. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6725. if (n_layer >= 64){
  6726. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  6727. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  6728. }
  6729. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6730. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6731. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6732. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6733. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6734. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6735. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6736. }
  6737. } break;
  6738. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  6739. {
  6740. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6741. // output
  6742. {
  6743. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6744. // if output is NULL, init from the input tok embed
  6745. if (model.output == NULL) {
  6746. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6747. }
  6748. }
  6749. for (int i = 0; i < n_layer; ++i) {
  6750. ggml_context * ctx_split = ctx_for_layer_split(i);
  6751. auto & layer = model.layers[i];
  6752. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6753. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6754. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6755. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6756. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6757. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6758. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6759. }
  6760. } break;
  6761. case LLM_ARCH_OPENELM:
  6762. {
  6763. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6764. // output
  6765. {
  6766. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6767. // init output from the input tok embed
  6768. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6769. }
  6770. for (int i = 0; i < n_layer; ++i) {
  6771. const int64_t n_head = hparams.n_head(i);
  6772. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  6773. const int64_t n_ff = hparams.n_ff(i);
  6774. ggml_context * ctx_layer = ctx_for_layer(i);
  6775. ggml_context * ctx_split = ctx_for_layer_split(i);
  6776. auto & layer = model.layers[i];
  6777. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6778. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  6779. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  6780. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  6781. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  6782. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6783. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6784. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6785. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6786. }
  6787. } break;
  6788. case LLM_ARCH_GPTNEOX:
  6789. {
  6790. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6791. // output
  6792. {
  6793. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6794. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6795. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6796. }
  6797. for (int i = 0; i < n_layer; ++i) {
  6798. ggml_context * ctx_layer = ctx_for_layer(i);
  6799. ggml_context * ctx_split = ctx_for_layer_split(i);
  6800. auto & layer = model.layers[i];
  6801. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6802. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6803. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6804. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6805. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6806. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6807. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6808. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6809. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6810. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6811. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6812. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6813. }
  6814. } break;
  6815. case LLM_ARCH_ARCTIC:
  6816. {
  6817. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6818. // output
  6819. {
  6820. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6821. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6822. // if output is NULL, init from the input tok embed
  6823. if (model.output == NULL) {
  6824. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6825. }
  6826. }
  6827. for (int i = 0; i < n_layer; ++i) {
  6828. ggml_context * ctx_layer = ctx_for_layer(i);
  6829. ggml_context * ctx_split = ctx_for_layer_split(i);
  6830. auto & layer = model.layers[i];
  6831. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6832. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6833. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6834. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6835. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6836. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6837. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  6838. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  6839. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  6840. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6841. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  6842. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  6843. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6844. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6845. }
  6846. } break;
  6847. case LLM_ARCH_DEEPSEEK2:
  6848. {
  6849. const bool is_lite = (hparams.n_layer == 27);
  6850. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6851. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6852. const int64_t q_lora_rank = hparams.n_lora_q;
  6853. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6854. const int64_t n_ff_exp = hparams.n_ff_exp;
  6855. const int64_t n_expert_shared = hparams.n_expert_shared;
  6856. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6857. // output
  6858. {
  6859. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6860. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6861. }
  6862. for (int i = 0; i < n_layer; ++i) {
  6863. ggml_context * ctx_layer = ctx_for_layer(i);
  6864. ggml_context * ctx_split = ctx_for_layer_split(i);
  6865. auto & layer = model.layers[i];
  6866. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6867. if (!is_lite) {
  6868. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6869. }
  6870. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6871. if (!is_lite) {
  6872. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6873. 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});
  6874. } else {
  6875. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6876. }
  6877. 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)});
  6878. 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)});
  6879. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6880. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6881. if (i < (int) hparams.n_layer_dense_lead) {
  6882. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6883. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6884. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6885. } else {
  6886. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6887. GGML_ASSERT(n_expert > 0);
  6888. GGML_ASSERT(n_expert_used > 0);
  6889. // MoE branch
  6890. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6891. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6892. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6893. // Shared expert branch
  6894. 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});
  6895. 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});
  6896. 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});
  6897. }
  6898. }
  6899. } break;
  6900. case LLM_ARCH_BITNET:
  6901. {
  6902. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6903. // output
  6904. {
  6905. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6906. }
  6907. for (int i = 0; i < n_layer; ++i) {
  6908. ggml_context * ctx_layer = ctx_for_layer(i);
  6909. ggml_context * ctx_split = ctx_for_layer_split(i);
  6910. auto & layer = model.layers[i];
  6911. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6912. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  6913. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6914. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1});
  6915. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6916. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1});
  6917. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6918. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1});
  6919. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6920. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1});
  6921. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6922. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  6923. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6924. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1});
  6925. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6926. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1});
  6927. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6928. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1});
  6929. }
  6930. } break;
  6931. case LLM_ARCH_T5:
  6932. {
  6933. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  6934. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6935. // output
  6936. {
  6937. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  6938. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  6939. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6940. // if output is NULL, init from the input tok embed
  6941. if (model.output == NULL) {
  6942. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6943. }
  6944. }
  6945. for (int i = 0; i < n_layer; ++i) {
  6946. ggml_context * ctx_layer = ctx_for_layer(i);
  6947. ggml_context * ctx_split = ctx_for_layer_split(i);
  6948. auto & layer = model.layers[i];
  6949. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  6950. 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);
  6951. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6952. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6953. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6954. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6955. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  6956. 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);
  6957. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6958. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  6959. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  6960. 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);
  6961. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6962. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6963. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6964. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6965. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  6966. // this tensor seems to be unused in HF transformers implementation
  6967. 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);
  6968. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6969. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6970. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6971. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6972. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  6973. 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);
  6974. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6975. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  6976. }
  6977. } break;
  6978. case LLM_ARCH_T5ENCODER:
  6979. {
  6980. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  6981. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6982. // output
  6983. {
  6984. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  6985. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6986. // if output is NULL, init from the input tok embed
  6987. if (model.output == NULL) {
  6988. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6989. }
  6990. }
  6991. for (int i = 0; i < n_layer; ++i) {
  6992. ggml_context * ctx_layer = ctx_for_layer(i);
  6993. ggml_context * ctx_split = ctx_for_layer_split(i);
  6994. auto & layer = model.layers[i];
  6995. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  6996. 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);
  6997. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6998. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6999. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7000. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  7001. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  7002. 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);
  7003. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7004. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  7005. }
  7006. } break;
  7007. case LLM_ARCH_JAIS:
  7008. {
  7009. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7010. // Output
  7011. {
  7012. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7013. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7014. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7015. }
  7016. for (int i = 0; i < n_layer; ++i) {
  7017. ggml_context * ctx_layer = ctx_for_layer(i);
  7018. ggml_context * ctx_split = ctx_for_layer_split(i);
  7019. auto & layer = model.layers[i];
  7020. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7021. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7022. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  7023. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  7024. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7025. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  7026. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7027. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7028. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7029. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  7030. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7031. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  7032. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7033. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  7034. }
  7035. } break;
  7036. case LLM_ARCH_CHATGLM:
  7037. {
  7038. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7039. // output
  7040. {
  7041. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7042. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7043. }
  7044. for (int i = 0; i < n_layer; ++i) {
  7045. ggml_context * ctx_layer = ctx_for_layer(i);
  7046. ggml_context * ctx_split = ctx_for_layer_split(i);
  7047. auto & layer = model.layers[i];
  7048. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7049. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + (hparams.n_embd_head_k << 2)});
  7050. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + (hparams.n_embd_head_k << 2)});
  7051. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7052. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7053. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  7054. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  7055. }
  7056. } break;
  7057. case LLM_ARCH_NEMOTRON:
  7058. {
  7059. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7060. // output
  7061. {
  7062. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7063. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  7064. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7065. }
  7066. for (int i = 0; i < n_layer; ++i) {
  7067. ggml_context * ctx_layer = ctx_for_layer(i);
  7068. ggml_context * ctx_split = ctx_for_layer_split(i);
  7069. auto & layer = model.layers[i];
  7070. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7071. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  7072. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  7073. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  7074. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  7075. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  7076. // optional bias tensors
  7077. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7078. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7079. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7080. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7081. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7082. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  7083. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7084. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7085. // optional MLP bias
  7086. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7087. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  7088. }
  7089. } break;
  7090. case LLM_ARCH_EXAONE:
  7091. {
  7092. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  7093. // output
  7094. {
  7095. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  7096. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  7097. }
  7098. for (int i = 0; i < n_layer; ++i) {
  7099. ggml_context * ctx_layer = ctx_for_layer(i);
  7100. ggml_context * ctx_split = ctx_for_layer_split(i);
  7101. auto & layer = model.layers[i];
  7102. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  7103. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  7104. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  7105. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  7106. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  7107. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  7108. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_rot/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  7109. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  7110. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  7111. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  7112. }
  7113. } break;
  7114. default:
  7115. throw std::runtime_error("unknown architecture");
  7116. }
  7117. }
  7118. ml.done_getting_tensors();
  7119. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  7120. model.mappings.reserve(ml.mappings.size());
  7121. // create the backend buffers
  7122. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  7123. ctx_bufs.reserve(ctx_map.size());
  7124. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  7125. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  7126. model.bufs.reserve(n_max_backend_buffer);
  7127. for (auto & it : ctx_map) {
  7128. ggml_backend_buffer_type_t buft = it.first;
  7129. ggml_context * ctx = it.second;
  7130. llama_buf_map bufs;
  7131. bufs.reserve(n_max_backend_buffer);
  7132. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  7133. // 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
  7134. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  7135. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  7136. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7137. void * addr = nullptr;
  7138. size_t first, last;
  7139. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7140. if (first >= last) {
  7141. continue;
  7142. }
  7143. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  7144. if (buf == nullptr) {
  7145. throw std::runtime_error("unable to allocate backend CPU buffer");
  7146. }
  7147. model.bufs.push_back(buf);
  7148. bufs.emplace(idx, buf);
  7149. #ifdef GGML_USE_CUDA
  7150. if (n_layer >= n_gpu_layers) {
  7151. ggml_backend_cuda_register_host_buffer(
  7152. ggml_backend_buffer_get_base(buf),
  7153. ggml_backend_buffer_get_size(buf));
  7154. }
  7155. #endif
  7156. }
  7157. }
  7158. #ifdef GGML_USE_METAL
  7159. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  7160. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7161. const size_t max_size = ggml_get_max_tensor_size(ctx);
  7162. void * addr = nullptr;
  7163. size_t first, last;
  7164. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  7165. if (first >= last) {
  7166. continue;
  7167. }
  7168. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  7169. if (buf == nullptr) {
  7170. throw std::runtime_error("unable to allocate backend metal buffer");
  7171. }
  7172. model.bufs.push_back(buf);
  7173. bufs.emplace(idx, buf);
  7174. }
  7175. }
  7176. #endif
  7177. else {
  7178. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  7179. if (buf == nullptr) {
  7180. throw std::runtime_error("unable to allocate backend buffer");
  7181. }
  7182. model.bufs.push_back(buf);
  7183. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  7184. model.mlock_bufs.emplace_back(new llama_mlock);
  7185. auto & mlock_buf = model.mlock_bufs.back();
  7186. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  7187. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  7188. }
  7189. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  7190. bufs.emplace(idx, buf);
  7191. }
  7192. }
  7193. if (bufs.empty()) {
  7194. throw std::runtime_error("failed to allocate buffer");
  7195. }
  7196. for (auto & buf : bufs) {
  7197. // indicate that this buffer contains weights
  7198. // 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
  7199. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  7200. }
  7201. ctx_bufs.emplace_back(ctx, bufs);
  7202. }
  7203. if (llama_supports_gpu_offload()) {
  7204. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  7205. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  7206. if (n_gpu_layers > (int) hparams.n_layer) {
  7207. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  7208. }
  7209. const int max_backend_supported_layers = hparams.n_layer + 1;
  7210. const int max_offloadable_layers = hparams.n_layer + 1;
  7211. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  7212. }
  7213. // print memory requirements
  7214. for (ggml_backend_buffer_t buf : model.bufs) {
  7215. 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);
  7216. }
  7217. // populate tensors_by_name
  7218. for (ggml_context * ctx : model.ctxs) {
  7219. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  7220. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  7221. }
  7222. }
  7223. // load tensor data
  7224. for (auto & it : ctx_bufs) {
  7225. ggml_context * ctx = it.first;
  7226. auto & bufs = it.second;
  7227. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  7228. return false;
  7229. }
  7230. }
  7231. if (use_mmap_buffer) {
  7232. for (auto & mapping : ml.mappings) {
  7233. model.mappings.emplace_back(std::move(mapping));
  7234. }
  7235. }
  7236. // loading time will be recalculate after the first eval, so
  7237. // we take page faults deferred by mmap() into consideration
  7238. model.t_load_us = ggml_time_us() - model.t_start_us;
  7239. return true;
  7240. }
  7241. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  7242. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  7243. try {
  7244. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  7245. model.hparams.vocab_only = params.vocab_only;
  7246. try {
  7247. llm_load_arch(ml, model);
  7248. } catch(const std::exception & e) {
  7249. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  7250. }
  7251. try {
  7252. llm_load_hparams(ml, model);
  7253. } catch(const std::exception & e) {
  7254. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  7255. }
  7256. try {
  7257. llm_load_vocab(ml, model);
  7258. } catch(const std::exception & e) {
  7259. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  7260. }
  7261. llm_load_print_meta(ml, model);
  7262. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  7263. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  7264. throw std::runtime_error("vocab size mismatch");
  7265. }
  7266. if (params.vocab_only) {
  7267. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  7268. return 0;
  7269. }
  7270. #ifdef GGML_USE_KOMPUTE
  7271. if (params.n_gpu_layers > 0 && (
  7272. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  7273. || !(
  7274. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  7275. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  7276. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  7277. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  7278. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  7279. )
  7280. )) {
  7281. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  7282. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  7283. params.n_gpu_layers = 0;
  7284. }
  7285. #endif
  7286. if (!llm_load_tensors(
  7287. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  7288. params.progress_callback, params.progress_callback_user_data
  7289. )) {
  7290. return -2;
  7291. }
  7292. } catch (const std::exception & err) {
  7293. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  7294. return -1;
  7295. }
  7296. return 0;
  7297. }
  7298. //
  7299. // llm_build
  7300. //
  7301. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  7302. enum llm_ffn_op_type {
  7303. LLM_FFN_SILU,
  7304. LLM_FFN_GELU,
  7305. LLM_FFN_RELU,
  7306. LLM_FFN_RELU_SQR,
  7307. LLM_FFN_SWIGLU,
  7308. };
  7309. enum llm_ffn_gate_type {
  7310. LLM_FFN_SEQ,
  7311. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  7312. };
  7313. enum llm_norm_type {
  7314. LLM_NORM,
  7315. LLM_NORM_RMS,
  7316. };
  7317. static struct ggml_tensor * llm_build_inp_embd(
  7318. struct ggml_context * ctx,
  7319. struct llama_context & lctx,
  7320. const llama_hparams & hparams,
  7321. const llama_ubatch & batch,
  7322. struct ggml_tensor * tok_embd,
  7323. const llm_build_cb & cb) {
  7324. const int64_t n_embd = hparams.n_embd;
  7325. struct ggml_tensor * inpL;
  7326. if (batch.token) {
  7327. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  7328. cb(lctx.inp_tokens, "inp_tokens", -1);
  7329. ggml_set_input(lctx.inp_tokens);
  7330. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  7331. } else {
  7332. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  7333. inpL = lctx.inp_embd;
  7334. ggml_set_input(lctx.inp_embd);
  7335. }
  7336. cb(inpL, "inp_embd", -1);
  7337. return inpL;
  7338. }
  7339. static void llm_build_kv_store(
  7340. struct ggml_context * ctx,
  7341. const llama_hparams & hparams,
  7342. const llama_cparams & cparams,
  7343. const llama_kv_cache & kv,
  7344. struct ggml_cgraph * graph,
  7345. struct ggml_tensor * k_cur,
  7346. struct ggml_tensor * v_cur,
  7347. int32_t n_tokens,
  7348. int32_t kv_head,
  7349. const llm_build_cb & cb,
  7350. int64_t il) {
  7351. const int64_t n_ctx = cparams.n_ctx;
  7352. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7353. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7354. GGML_ASSERT(kv.size == n_ctx);
  7355. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  7356. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  7357. cb(k_cache_view, "k_cache_view", il);
  7358. // note: storing RoPE-ed version of K in the KV cache
  7359. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  7360. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  7361. struct ggml_tensor * v_cache_view = nullptr;
  7362. if (cparams.flash_attn) {
  7363. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  7364. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  7365. } else {
  7366. // note: the V cache is transposed when not using flash attention
  7367. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  7368. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  7369. (kv_head)*ggml_element_size(kv.v_l[il]));
  7370. v_cur = ggml_transpose(ctx, v_cur);
  7371. }
  7372. cb(v_cache_view, "v_cache_view", il);
  7373. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  7374. }
  7375. // do mat_mul, while optionally apply lora
  7376. static struct ggml_tensor * llm_build_lora_mm(
  7377. struct llama_context & lctx,
  7378. struct ggml_context * ctx0,
  7379. struct ggml_tensor * w,
  7380. struct ggml_tensor * cur) {
  7381. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  7382. for (auto & it : lctx.lora_adapters) {
  7383. struct llama_lora_weight * lora = it.first->get_weight(w);
  7384. if (lora == nullptr) {
  7385. continue;
  7386. }
  7387. const float alpha = it.first->alpha;
  7388. const float rank = (float) lora->b->ne[0];
  7389. const float scale = alpha ? it.second * alpha / rank : it.second;
  7390. struct ggml_tensor * ab_cur = ggml_mul_mat(
  7391. ctx0, lora->b,
  7392. ggml_mul_mat(ctx0, lora->a, cur)
  7393. );
  7394. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  7395. res = ggml_add(ctx0, res, ab_cur);
  7396. }
  7397. return res;
  7398. }
  7399. // do mat_mul_id, while optionally apply lora
  7400. static struct ggml_tensor * llm_build_lora_mm_id(
  7401. struct llama_context & lctx,
  7402. struct ggml_context * ctx0,
  7403. struct ggml_tensor * w, // struct ggml_tensor * as
  7404. struct ggml_tensor * cur, // struct ggml_tensor * b
  7405. struct ggml_tensor * ids) {
  7406. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  7407. for (auto & it : lctx.lora_adapters) {
  7408. struct llama_lora_weight * lora = it.first->get_weight(w);
  7409. if (lora == nullptr) {
  7410. continue;
  7411. }
  7412. const float alpha = it.first->alpha;
  7413. const float rank = (float) lora->b->ne[0];
  7414. const float scale = alpha ? it.second * alpha / rank : it.second;
  7415. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  7416. ctx0, lora->b,
  7417. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  7418. ids
  7419. );
  7420. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  7421. res = ggml_add(ctx0, res, ab_cur);
  7422. }
  7423. return res;
  7424. }
  7425. static struct ggml_tensor * llm_build_norm(
  7426. struct ggml_context * ctx,
  7427. struct ggml_tensor * cur,
  7428. const llama_hparams & hparams,
  7429. struct ggml_tensor * mw,
  7430. struct ggml_tensor * mb,
  7431. llm_norm_type type,
  7432. const llm_build_cb & cb,
  7433. int il) {
  7434. switch (type) {
  7435. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  7436. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  7437. }
  7438. if (mw || mb) {
  7439. cb(cur, "norm", il);
  7440. }
  7441. if (mw) {
  7442. cur = ggml_mul(ctx, cur, mw);
  7443. if (mb) {
  7444. cb(cur, "norm_w", il);
  7445. }
  7446. }
  7447. if (mb) {
  7448. cur = ggml_add(ctx, cur, mb);
  7449. }
  7450. return cur;
  7451. }
  7452. static struct ggml_tensor * llm_build_ffn(
  7453. struct ggml_context * ctx,
  7454. struct llama_context & lctx,
  7455. struct ggml_tensor * cur,
  7456. struct ggml_tensor * up,
  7457. struct ggml_tensor * up_b,
  7458. struct ggml_tensor * up_s,
  7459. struct ggml_tensor * gate,
  7460. struct ggml_tensor * gate_b,
  7461. struct ggml_tensor * gate_s,
  7462. struct ggml_tensor * down,
  7463. struct ggml_tensor * down_b,
  7464. struct ggml_tensor * down_s,
  7465. struct ggml_tensor * act_scales,
  7466. llm_ffn_op_type type_op,
  7467. llm_ffn_gate_type type_gate,
  7468. const llm_build_cb & cb,
  7469. int il) {
  7470. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  7471. cb(tmp, "ffn_up", il);
  7472. if (up_b) {
  7473. tmp = ggml_add(ctx, tmp, up_b);
  7474. cb(tmp, "ffn_up_b", il);
  7475. }
  7476. if (up_s) {
  7477. tmp = ggml_mul(ctx, tmp, up_s);
  7478. cb(tmp, "ffn_up_s", il);
  7479. }
  7480. if (gate) {
  7481. switch (type_gate) {
  7482. case LLM_FFN_SEQ:
  7483. {
  7484. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  7485. cb(cur, "ffn_gate", il);
  7486. } break;
  7487. case LLM_FFN_PAR:
  7488. {
  7489. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  7490. cb(cur, "ffn_gate", il);
  7491. } break;
  7492. }
  7493. if (gate_b) {
  7494. cur = ggml_add(ctx, cur, gate_b);
  7495. cb(cur, "ffn_gate_b", il);
  7496. }
  7497. if (gate_s) {
  7498. cur = ggml_mul(ctx, cur, gate_s);
  7499. cb(cur, "ffn_gate_s", il);
  7500. }
  7501. } else {
  7502. cur = tmp;
  7503. }
  7504. switch (type_op) {
  7505. case LLM_FFN_SILU:
  7506. {
  7507. cur = ggml_silu(ctx, cur);
  7508. cb(cur, "ffn_silu", il);
  7509. } break;
  7510. case LLM_FFN_GELU:
  7511. {
  7512. cur = ggml_gelu(ctx, cur);
  7513. cb(cur, "ffn_gelu", il);
  7514. if (act_scales != NULL) {
  7515. cur = ggml_div(ctx, cur, act_scales);
  7516. cb(cur, "ffn_act", il);
  7517. }
  7518. } break;
  7519. case LLM_FFN_RELU:
  7520. {
  7521. cur = ggml_relu(ctx, cur);
  7522. cb(cur, "ffn_relu", il);
  7523. } break;
  7524. case LLM_FFN_RELU_SQR:
  7525. {
  7526. cur = ggml_relu(ctx, cur);
  7527. cb(cur, "ffn_relu", il);
  7528. cur = ggml_sqr(ctx, cur);
  7529. cb(cur, "ffn_sqr(relu)", il);
  7530. } break;
  7531. case LLM_FFN_SWIGLU:
  7532. {
  7533. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  7534. int64_t split_point = cur->ne[0] / 2;
  7535. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  7536. 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)));
  7537. x0 = ggml_silu(ctx, x0);
  7538. cb(cur, "ffn_silu", il);
  7539. cur = ggml_mul(ctx, x0, x1);
  7540. cb(cur, "ffn_mul", il);
  7541. } break;
  7542. }
  7543. if (type_gate == LLM_FFN_PAR) {
  7544. cur = ggml_mul(ctx, cur, tmp);
  7545. cb(cur, "ffn_gate_par", il);
  7546. }
  7547. if (down) {
  7548. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  7549. }
  7550. if (down_b) {
  7551. cb(cur, "ffn_down", il);
  7552. }
  7553. if (down_b) {
  7554. cur = ggml_add(ctx, cur, down_b);
  7555. }
  7556. if (down_s) {
  7557. cur = ggml_mul(ctx, cur, down_s);
  7558. cb(cur, "ffn_down_s", il);
  7559. }
  7560. return cur;
  7561. }
  7562. static struct ggml_tensor * llm_build_moe_ffn(
  7563. struct ggml_context * ctx,
  7564. struct llama_context & lctx,
  7565. struct ggml_tensor * cur,
  7566. struct ggml_tensor * gate_inp,
  7567. struct ggml_tensor * up_exps,
  7568. struct ggml_tensor * gate_exps,
  7569. struct ggml_tensor * down_exps,
  7570. int64_t n_expert,
  7571. int64_t n_expert_used,
  7572. llm_ffn_op_type type_op,
  7573. bool norm_w,
  7574. bool scale_w,
  7575. float w_scale,
  7576. const llm_build_cb & cb,
  7577. int il) {
  7578. int64_t n_embd = cur->ne[0];
  7579. int64_t n_tokens = cur->ne[1];
  7580. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  7581. cb(logits, "ffn_moe_logits", il);
  7582. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  7583. cb(probs, "ffn_moe_probs", il);
  7584. // select experts
  7585. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  7586. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  7587. cb(selected_experts, "ffn_moe_topk", il);
  7588. ggml_tensor * weights = ggml_get_rows(ctx,
  7589. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  7590. cb(weights, "ffn_moe_weights", il);
  7591. if (norm_w) {
  7592. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  7593. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  7594. cb(weights_sum, "ffn_moe_weights_sum", il);
  7595. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  7596. cb(weights, "ffn_moe_weights_norm", il);
  7597. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  7598. }
  7599. if (scale_w) {
  7600. weights = ggml_scale(ctx, weights, w_scale);
  7601. cb(weights, "ffn_moe_weights_scaled", il);
  7602. }
  7603. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  7604. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  7605. cb(up, "ffn_moe_up", il);
  7606. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  7607. cb(gate, "ffn_moe_gate", il);
  7608. switch (type_op) {
  7609. case LLM_FFN_SILU:
  7610. {
  7611. gate = ggml_silu(ctx, gate);
  7612. cb(gate, "ffn_moe_silu", il);
  7613. } break;
  7614. case LLM_FFN_GELU:
  7615. {
  7616. gate = ggml_gelu(ctx, gate);
  7617. cb(gate, "ffn_moe_gelu", il);
  7618. } break;
  7619. default:
  7620. GGML_ABORT("fatal error");
  7621. }
  7622. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  7623. cb(par, "ffn_moe_gate_par", il);
  7624. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  7625. cb(experts, "ffn_moe_down", il);
  7626. experts = ggml_mul(ctx, experts, weights);
  7627. // aggregate experts
  7628. ggml_tensor * moe_out = nullptr;
  7629. for (int i = 0; i < n_expert_used; ++i) {
  7630. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  7631. experts->nb[2], i*experts->nb[1]);
  7632. if (i == 0) {
  7633. moe_out = cur_expert;
  7634. } else {
  7635. moe_out = ggml_add(ctx, moe_out, cur_expert);
  7636. }
  7637. }
  7638. if (n_expert_used == 1) {
  7639. // avoid returning a non-contiguous tensor
  7640. moe_out = ggml_cont(ctx, moe_out);
  7641. }
  7642. return moe_out;
  7643. }
  7644. static struct ggml_tensor * llm_build_kqv(
  7645. struct ggml_context * ctx,
  7646. struct llama_context & lctx,
  7647. const llama_kv_cache & kv,
  7648. struct ggml_cgraph * graph,
  7649. struct ggml_tensor * wo,
  7650. struct ggml_tensor * wo_b,
  7651. struct ggml_tensor * q_cur,
  7652. struct ggml_tensor * kq_mask,
  7653. int32_t n_tokens,
  7654. int32_t n_kv,
  7655. float kq_scale,
  7656. const llm_build_cb & cb,
  7657. int il) {
  7658. const llama_model & model = lctx.model;
  7659. const llama_hparams & hparams = lctx.model.hparams;
  7660. const llama_cparams & cparams = lctx.cparams;
  7661. const int64_t n_ctx = cparams.n_ctx;
  7662. const int64_t n_head = hparams.n_head(il);
  7663. const int64_t n_head_kv = hparams.n_head_kv(il);
  7664. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7665. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7666. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  7667. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7668. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  7669. cb(q, "q", il);
  7670. struct ggml_tensor * k =
  7671. ggml_view_3d(ctx, kv.k_l[il],
  7672. n_embd_head_k, n_kv, n_head_kv,
  7673. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  7674. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  7675. 0);
  7676. cb(k, "k", il);
  7677. struct ggml_tensor * cur;
  7678. if (cparams.flash_attn) {
  7679. GGML_UNUSED(model);
  7680. GGML_UNUSED(n_ctx);
  7681. // split cached v into n_head heads (not transposed)
  7682. struct ggml_tensor * v =
  7683. ggml_view_3d(ctx, kv.v_l[il],
  7684. n_embd_head_v, n_kv, n_head_kv,
  7685. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  7686. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  7687. 0);
  7688. cb(v, "v", il);
  7689. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias,
  7690. hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f);
  7691. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_GEMMA2) {
  7692. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  7693. }
  7694. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  7695. } else {
  7696. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  7697. cb(kq, "kq", il);
  7698. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_QWEN2 || model.arch == LLM_ARCH_NEMOTRON || model.arch == LLM_ARCH_CHATGLM) {
  7699. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  7700. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  7701. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7702. }
  7703. if (model.arch == LLM_ARCH_GROK) {
  7704. // need to do the following:
  7705. // multiply by attn_output_multiplyer of 0.08838834764831845
  7706. // and then :
  7707. // kq = 30 * tanh(kq / 30)
  7708. // before the softmax below
  7709. //try from phi2
  7710. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7711. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  7712. kq = ggml_scale(ctx, kq, 30);
  7713. }
  7714. if (hparams.attn_soft_cap) {
  7715. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  7716. kq = ggml_tanh(ctx, kq);
  7717. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  7718. }
  7719. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7720. cb(kq, "kq_soft_max_ext", il);
  7721. GGML_ASSERT(kv.size == n_ctx);
  7722. // split cached v into n_head heads
  7723. struct ggml_tensor * v =
  7724. ggml_view_3d(ctx, kv.v_l[il],
  7725. n_kv, n_embd_head_v, n_head_kv,
  7726. ggml_element_size(kv.v_l[il])*n_ctx,
  7727. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  7728. 0);
  7729. cb(v, "v", il);
  7730. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  7731. cb(kqv, "kqv", il);
  7732. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  7733. cb(kqv_merged, "kqv_merged", il);
  7734. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  7735. cb(cur, "kqv_merged_cont", il);
  7736. }
  7737. ggml_build_forward_expand(graph, cur);
  7738. if (wo) {
  7739. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  7740. }
  7741. if (wo_b) {
  7742. cb(cur, "kqv_wo", il);
  7743. }
  7744. if (wo_b) {
  7745. cur = ggml_add(ctx, cur, wo_b);
  7746. }
  7747. return cur;
  7748. }
  7749. static struct ggml_tensor * llm_build_kv(
  7750. struct ggml_context * ctx,
  7751. struct llama_context & lctx,
  7752. const llama_kv_cache & kv,
  7753. struct ggml_cgraph * graph,
  7754. struct ggml_tensor * wo,
  7755. struct ggml_tensor * wo_b,
  7756. struct ggml_tensor * k_cur,
  7757. struct ggml_tensor * v_cur,
  7758. struct ggml_tensor * q_cur,
  7759. struct ggml_tensor * kq_mask,
  7760. int32_t n_tokens,
  7761. int32_t kv_head,
  7762. int32_t n_kv,
  7763. float kq_scale,
  7764. const llm_build_cb & cb,
  7765. int il) {
  7766. const llama_hparams & hparams = lctx.model.hparams;
  7767. const llama_cparams & cparams = lctx.cparams;
  7768. // these nodes are added to the graph together so that they are not reordered
  7769. // by doing so, the number of splits in the graph is reduced
  7770. ggml_build_forward_expand(graph, q_cur);
  7771. ggml_build_forward_expand(graph, k_cur);
  7772. ggml_build_forward_expand(graph, v_cur);
  7773. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  7774. struct ggml_tensor * cur;
  7775. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b,
  7776. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  7777. cb(cur, "kqv_out", il);
  7778. return cur;
  7779. }
  7780. static struct ggml_tensor * llm_build_copy_mask_state(
  7781. struct ggml_context * ctx,
  7782. struct ggml_cgraph * graph,
  7783. struct ggml_tensor * s,
  7784. struct ggml_tensor * state_copy,
  7785. struct ggml_tensor * state_mask,
  7786. int32_t n_state,
  7787. int32_t kv_size,
  7788. int32_t kv_head,
  7789. int32_t n_kv,
  7790. int32_t n_seqs) {
  7791. struct ggml_tensor * states = ggml_reshape_2d(ctx, s, n_state, kv_size);
  7792. // copy states
  7793. // NOTE: assuming the copy destinations are ALL contained between kv_head and kv_head + n_kv
  7794. // this shrinks the tensors's ne[1] to n_kv
  7795. states = ggml_get_rows(ctx, states, state_copy);
  7796. // clear states of sequences which are starting at the beginning of this batch
  7797. // FIXME: zero-out NANs?
  7798. states = ggml_mul(ctx, states, state_mask);
  7799. // copy states which won't be changed further (between n_seqs and n_rs)
  7800. ggml_build_forward_expand(graph,
  7801. ggml_cpy(ctx,
  7802. ggml_view_1d(ctx, states, n_state*(n_kv - n_seqs), n_seqs*n_state*ggml_element_size(states)),
  7803. ggml_view_1d(ctx, s, n_state*(n_kv - n_seqs), (kv_head + n_seqs)*n_state*ggml_element_size(s))));
  7804. // the part of the states that will be used and modified
  7805. return ggml_view_2d(ctx, states, n_state, n_seqs, states->nb[1], 0);
  7806. }
  7807. // TODO: split
  7808. static struct ggml_tensor * llm_build_mamba(
  7809. struct ggml_context * ctx,
  7810. struct llama_context & lctx,
  7811. const llama_ubatch & batch,
  7812. struct ggml_cgraph * graph,
  7813. struct ggml_tensor * cur,
  7814. struct ggml_tensor * state_copy,
  7815. struct ggml_tensor * state_mask,
  7816. int32_t kv_head,
  7817. int32_t n_kv,
  7818. const llm_build_cb & cb,
  7819. int il) {
  7820. const llama_model & model = lctx.model;
  7821. const llama_hparams & hparams = model.hparams;
  7822. const llama_kv_cache & kv = lctx.kv_self;
  7823. const int64_t d_conv = hparams.ssm_d_conv;
  7824. const int64_t d_inner = hparams.ssm_d_inner;
  7825. const int64_t d_state = hparams.ssm_d_state;
  7826. const int64_t dt_rank = hparams.ssm_dt_rank;
  7827. const int64_t n_seqs = batch.n_seqs;
  7828. // Some variants of Mamba arch (e.g. FalconMamba do apply layer norm on B and Dt layers)
  7829. const bool ssm_dt_b_c_rms = hparams.ssm_dt_b_c_rms;
  7830. // Use the same RMS norm as the final layer norm
  7831. const float norm_rms_eps = hparams.f_norm_rms_eps;
  7832. const int64_t n_seq_tokens = batch.n_seq_tokens;
  7833. GGML_ASSERT(n_seqs != 0);
  7834. GGML_ASSERT(batch.equal_seqs);
  7835. GGML_ASSERT(batch.n_tokens == n_seq_tokens * n_seqs);
  7836. struct ggml_tensor * conv_states_all = kv.k_l[il];
  7837. struct ggml_tensor * ssm_states_all = kv.v_l[il];
  7838. // (ab)using the KV cache to store the states
  7839. struct ggml_tensor * conv = llm_build_copy_mask_state(ctx,
  7840. graph, conv_states_all, state_copy, state_mask,
  7841. hparams.n_embd_k_s(), kv.size, kv_head, n_kv, n_seqs);
  7842. conv = ggml_reshape_3d(ctx, conv, d_conv - 1, d_inner, n_seqs);
  7843. struct ggml_tensor * ssm = llm_build_copy_mask_state(ctx,
  7844. graph, ssm_states_all, state_copy, state_mask,
  7845. hparams.n_embd_v_s(), kv.size, kv_head, n_kv, n_seqs);
  7846. ssm = ggml_reshape_3d(ctx, ssm, d_state, d_inner, n_seqs);
  7847. // {n_embd, n_tokens} => {n_embd, n_seq_tokens, n_seqs}
  7848. cur = ggml_reshape_3d(ctx, cur, cur->ne[0], n_seq_tokens, n_seqs);
  7849. // {n_embd, 2*d_inner} @ {n_embd, n_seq_tokens, n_seqs} => {2*d_inner, n_seq_tokens, n_seqs}
  7850. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_in, cur);
  7851. // split the above in two
  7852. // => {d_inner, n_seq_tokens, n_seqs}
  7853. struct ggml_tensor * x = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], 0);
  7854. struct ggml_tensor * z = ggml_view_3d(ctx, xz, d_inner, xz->ne[1], xz->ne[2], xz->nb[1], xz->nb[2], d_inner*ggml_element_size(xz));
  7855. // conv
  7856. {
  7857. // => {d_conv - 1 + n_seq_tokens, d_inner, n_seqs}
  7858. struct ggml_tensor * conv_x = ggml_concat(ctx, conv, ggml_transpose(ctx, x), 0);
  7859. // copy last (d_conv - 1) columns back into the state cache
  7860. struct ggml_tensor * last_conv = ggml_view_3d(ctx, conv_x, d_conv - 1, d_inner, n_seqs, conv_x->nb[1], conv_x->nb[2], n_seq_tokens*(conv_x->nb[0]));
  7861. ggml_build_forward_expand(graph,
  7862. ggml_cpy(ctx, last_conv,
  7863. ggml_view_1d(ctx, conv_states_all,
  7864. (d_conv - 1)*(d_inner)*(n_seqs),
  7865. kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(conv_states_all))));
  7866. // 1D convolution
  7867. // The equivalent is to make a self-overlapping view of conv_x
  7868. // over d_conv columns at each stride in the 3rd dimension,
  7869. // then element-wise multiply that with the conv1d weight,
  7870. // then sum the elements of each row,
  7871. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7872. // then permute away the ne[0] dimension,
  7873. // and then you're left with the resulting x tensor.
  7874. // For simultaneous sequences, all sequences need to have the same length.
  7875. x = ggml_ssm_conv(ctx, conv_x, model.layers[il].ssm_conv1d);
  7876. // bias
  7877. x = ggml_add(ctx, x, model.layers[il].ssm_conv1d_b);
  7878. x = ggml_silu(ctx, x);
  7879. }
  7880. // ssm
  7881. {
  7882. // {d_inner, dt_rank + 2*d_state} @ {d_inner, n_seq_tokens, n_seqs} => {dt_rank + 2*d_state, n_seq_tokens, n_seqs}
  7883. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_x, x);
  7884. // split
  7885. struct ggml_tensor * dt = ggml_view_3d(ctx, x_db, dt_rank, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], 0);
  7886. struct ggml_tensor * B = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*dt_rank);
  7887. struct ggml_tensor * C = ggml_view_3d(ctx, x_db, d_state, n_seq_tokens, n_seqs, x_db->nb[1], x_db->nb[2], ggml_element_size(x_db)*(dt_rank+d_state));
  7888. // Some Mamba variants (e.g. FalconMamba) apply RMS norm in B, C & Dt layers
  7889. if (ssm_dt_b_c_rms) {
  7890. dt = ggml_rms_norm(ctx, dt, norm_rms_eps);
  7891. B = ggml_rms_norm(ctx, B, norm_rms_eps);
  7892. C = ggml_rms_norm(ctx, C, norm_rms_eps);
  7893. }
  7894. // {dt_rank, d_inner} @ {dt_rank, n_seq_tokens, n_seqs} => {d_inner, n_seq_tokens, n_seqs}
  7895. dt = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_dt, dt);
  7896. dt = ggml_add(ctx, dt, model.layers[il].ssm_dt_b);
  7897. // Custom operator to optimize the parallel associative scan
  7898. // as described in the Annex D of the Mamba paper.
  7899. // => {d_inner, n_seq_tokens, n_seqs} and {d_state, d_inner, n_seqs}
  7900. struct ggml_tensor * y_ssm = ggml_ssm_scan(ctx, ssm, x, dt, model.layers[il].ssm_a, B, C);
  7901. // store last states
  7902. ggml_build_forward_expand(graph,
  7903. ggml_cpy(ctx,
  7904. ggml_view_1d(ctx, y_ssm, d_state*d_inner*n_seqs, x->nb[3]),
  7905. ggml_view_1d(ctx, ssm_states_all, d_state*d_inner*n_seqs, kv_head*d_state*d_inner*ggml_element_size(ssm_states_all))));
  7906. struct ggml_tensor * y = ggml_view_3d(ctx, y_ssm, d_inner, n_seq_tokens, n_seqs, x->nb[1], x->nb[2], 0);
  7907. // TODO: skip computing output earlier for unused tokens
  7908. // {d_inner, n_seq_tokens, n_seqs} * {d_inner} => {d_inner, n_seq_tokens, n_seqs}
  7909. y = ggml_add(ctx, y, ggml_mul(ctx, x, model.layers[il].ssm_d));
  7910. y = ggml_mul(ctx, y, ggml_silu(ctx, ggml_cont(ctx, z)));
  7911. // {d_inner, n_embd} @ {d_inner, n_seq_tokens, n_seqs} => {n_embd, n_seq_tokens, n_seqs}
  7912. cur = llm_build_lora_mm(lctx, ctx, model.layers[il].ssm_out, y);
  7913. }
  7914. // {n_embd, n_seq_tokens, n_seqs} => {n_embd, n_tokens}
  7915. cur = ggml_reshape_2d(ctx, cur, cur->ne[0], n_seq_tokens * n_seqs);
  7916. cb(cur, "mamba_out", il);
  7917. return cur;
  7918. }
  7919. struct llm_build_context {
  7920. const llama_model & model;
  7921. llama_context & lctx;
  7922. const llama_hparams & hparams;
  7923. const llama_cparams & cparams;
  7924. const llama_ubatch & batch;
  7925. const llama_kv_cache & kv_self;
  7926. const int64_t n_embd;
  7927. const int64_t n_layer;
  7928. const int64_t n_rot;
  7929. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  7930. const int64_t n_head;
  7931. const int64_t n_head_kv;
  7932. const int64_t n_embd_head_k;
  7933. const int64_t n_embd_k_gqa;
  7934. const int64_t n_embd_head_v;
  7935. const int64_t n_embd_v_gqa;
  7936. const int64_t n_expert;
  7937. const int64_t n_expert_used;
  7938. const float freq_base;
  7939. const float freq_scale;
  7940. const float ext_factor;
  7941. const float attn_factor;
  7942. const float beta_fast;
  7943. const float beta_slow;
  7944. const float norm_eps;
  7945. const float norm_rms_eps;
  7946. const int32_t n_tokens;
  7947. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  7948. const int32_t n_outputs;
  7949. const int32_t n_outputs_enc;
  7950. const int32_t kv_head; // index of where we store new KV data in the cache
  7951. const int32_t n_ctx_orig;
  7952. const bool flash_attn;
  7953. const enum llama_pooling_type pooling_type;
  7954. const enum llama_rope_type rope_type;
  7955. const llm_build_cb & cb;
  7956. std::vector<uint8_t> & buf_compute_meta;
  7957. struct ggml_context * ctx0 = nullptr;
  7958. // TODO: consider making the entire interface noexcept
  7959. llm_build_context(
  7960. llama_context & lctx,
  7961. const llama_ubatch & batch,
  7962. const llm_build_cb & cb,
  7963. bool worst_case) :
  7964. model (lctx.model),
  7965. lctx (lctx),
  7966. hparams (model.hparams),
  7967. cparams (lctx.cparams),
  7968. batch (batch),
  7969. kv_self (lctx.kv_self),
  7970. n_embd (hparams.n_embd),
  7971. n_layer (hparams.n_layer),
  7972. n_rot (hparams.n_rot),
  7973. n_ctx (cparams.n_ctx),
  7974. n_head (hparams.n_head()),
  7975. n_head_kv (hparams.n_head_kv()),
  7976. n_embd_head_k (hparams.n_embd_head_k),
  7977. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  7978. n_embd_head_v (hparams.n_embd_head_v),
  7979. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  7980. n_expert (hparams.n_expert),
  7981. n_expert_used (hparams.n_expert_used),
  7982. freq_base (cparams.rope_freq_base),
  7983. freq_scale (cparams.rope_freq_scale),
  7984. ext_factor (cparams.yarn_ext_factor),
  7985. attn_factor (cparams.yarn_attn_factor),
  7986. beta_fast (cparams.yarn_beta_fast),
  7987. beta_slow (cparams.yarn_beta_slow),
  7988. norm_eps (hparams.f_norm_eps),
  7989. norm_rms_eps (hparams.f_norm_rms_eps),
  7990. n_tokens (batch.n_tokens),
  7991. n_kv (worst_case ? kv_self.size : kv_self.n),
  7992. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  7993. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  7994. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  7995. n_ctx_orig (cparams.n_ctx_orig_yarn),
  7996. flash_attn (cparams.flash_attn),
  7997. pooling_type (cparams.pooling_type),
  7998. rope_type (hparams.rope_type),
  7999. cb (cb),
  8000. buf_compute_meta (lctx.buf_compute_meta) {
  8001. // all initializations should be done in init()
  8002. }
  8003. void init() {
  8004. struct ggml_init_params params = {
  8005. /*.mem_size =*/ buf_compute_meta.size(),
  8006. /*.mem_buffer =*/ buf_compute_meta.data(),
  8007. /*.no_alloc =*/ true,
  8008. };
  8009. ctx0 = ggml_init(params);
  8010. lctx.inp_tokens = nullptr;
  8011. lctx.inp_embd = nullptr;
  8012. lctx.inp_pos = nullptr;
  8013. lctx.inp_out_ids = nullptr;
  8014. lctx.inp_KQ_mask = nullptr;
  8015. lctx.inp_KQ_mask_swa = nullptr;
  8016. lctx.inp_K_shift = nullptr;
  8017. lctx.inp_mean = nullptr;
  8018. lctx.inp_cls = nullptr;
  8019. lctx.inp_s_copy = nullptr;
  8020. lctx.inp_s_mask = nullptr;
  8021. lctx.inp_s_seq = nullptr;
  8022. lctx.inp_pos_bucket = nullptr;
  8023. lctx.inp_embd_enc = nullptr;
  8024. lctx.inp_KQ_mask_cross = nullptr;
  8025. }
  8026. void free() {
  8027. if (ctx0) {
  8028. ggml_free(ctx0);
  8029. ctx0 = nullptr;
  8030. }
  8031. }
  8032. struct ggml_cgraph * build_k_shift() {
  8033. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8034. GGML_ASSERT(kv_self.size == n_ctx);
  8035. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  8036. cb(lctx.inp_K_shift, "K_shift", -1);
  8037. ggml_set_input(lctx.inp_K_shift);
  8038. for (int il = 0; il < n_layer; ++il) {
  8039. const int64_t n_head_kv = hparams.n_head_kv(il);
  8040. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8041. struct ggml_tensor * rope_factors = build_rope_factors(il);
  8042. struct ggml_tensor * tmp =
  8043. // we rotate only the first n_rot dimensions
  8044. ggml_rope_ext_inplace(ctx0,
  8045. ggml_view_3d(ctx0, kv_self.k_l[il],
  8046. n_embd_head_k, n_head_kv, n_ctx,
  8047. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  8048. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8049. 0),
  8050. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8051. ext_factor, attn_factor, beta_fast, beta_slow);
  8052. cb(tmp, "K_shifted", il);
  8053. ggml_build_forward_expand(gf, tmp);
  8054. }
  8055. return gf;
  8056. }
  8057. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  8058. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8059. for (uint32_t i = 0; i < ids.size(); ++i) {
  8060. const uint32_t id = ids[i];
  8061. if (i == id || id == ids.size()) {
  8062. continue;
  8063. }
  8064. uint32_t nm = 1;
  8065. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  8066. nm++;
  8067. }
  8068. for (int il = 0; il < n_layer; ++il) {
  8069. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  8070. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  8071. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  8072. n_embd_k_gqa, nm,
  8073. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8074. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  8075. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  8076. n_embd_k_gqa, nm,
  8077. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  8078. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  8079. ggml_tensor * view_v_src;
  8080. ggml_tensor * view_v_dst;
  8081. if (flash_attn) {
  8082. // NOTE: the V cache is not transposed when using flash attention
  8083. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  8084. n_embd_v_gqa, nm,
  8085. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  8086. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  8087. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  8088. n_embd_v_gqa, nm,
  8089. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  8090. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  8091. } else {
  8092. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  8093. nm, n_embd_v_gqa,
  8094. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  8095. ggml_row_size(kv_self.v_l[il]->type, i));
  8096. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  8097. nm, n_embd_v_gqa,
  8098. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  8099. ggml_row_size(kv_self.v_l[il]->type, id));
  8100. }
  8101. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  8102. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  8103. }
  8104. i += nm - 1;
  8105. }
  8106. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  8107. return gf;
  8108. }
  8109. struct ggml_tensor * build_inp_pos() {
  8110. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  8111. cb(lctx.inp_pos, "inp_pos", -1);
  8112. ggml_set_input(lctx.inp_pos);
  8113. return lctx.inp_pos;
  8114. }
  8115. struct ggml_tensor * build_rope_factors(int il) {
  8116. // choose long/short freq factors based on the context size
  8117. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  8118. if (model.layers[il].rope_freqs != nullptr) {
  8119. return model.layers[il].rope_freqs;
  8120. }
  8121. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  8122. return model.layers[il].rope_long;
  8123. }
  8124. return model.layers[il].rope_short;
  8125. }
  8126. struct ggml_tensor * build_inp_out_ids() {
  8127. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  8128. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  8129. ggml_set_input(lctx.inp_out_ids);
  8130. return lctx.inp_out_ids;
  8131. }
  8132. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  8133. lctx.inp_KQ_mask = causal
  8134. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  8135. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  8136. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  8137. ggml_set_input(lctx.inp_KQ_mask);
  8138. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  8139. }
  8140. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  8141. GGML_ASSERT(hparams.n_swa > 0);
  8142. lctx.inp_KQ_mask_swa = causal
  8143. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  8144. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  8145. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  8146. ggml_set_input(lctx.inp_KQ_mask_swa);
  8147. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  8148. }
  8149. struct ggml_tensor * build_inp_mean() {
  8150. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  8151. cb(lctx.inp_mean, "inp_mean", -1);
  8152. ggml_set_input(lctx.inp_mean);
  8153. return lctx.inp_mean;
  8154. }
  8155. struct ggml_tensor * build_inp_cls() {
  8156. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  8157. cb(lctx.inp_cls, "inp_cls", -1);
  8158. ggml_set_input(lctx.inp_cls);
  8159. return lctx.inp_cls;
  8160. }
  8161. struct ggml_tensor * build_inp_s_copy() {
  8162. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_kv);
  8163. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  8164. ggml_set_input(lctx.inp_s_copy);
  8165. return lctx.inp_s_copy;
  8166. }
  8167. struct ggml_tensor * build_inp_s_mask() {
  8168. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  8169. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  8170. ggml_set_input(lctx.inp_s_mask);
  8171. return lctx.inp_s_mask;
  8172. }
  8173. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  8174. // find result_norm tensor for input
  8175. struct ggml_tensor * inp = nullptr;
  8176. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  8177. inp = gf->nodes[i];
  8178. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  8179. break;
  8180. } else {
  8181. inp = nullptr;
  8182. }
  8183. }
  8184. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  8185. struct ggml_tensor * cur;
  8186. switch (pooling_type) {
  8187. case LLAMA_POOLING_TYPE_MEAN:
  8188. {
  8189. struct ggml_tensor * inp_mean = build_inp_mean();
  8190. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  8191. } break;
  8192. case LLAMA_POOLING_TYPE_CLS:
  8193. case LLAMA_POOLING_TYPE_LAST:
  8194. {
  8195. struct ggml_tensor * inp_cls = build_inp_cls();
  8196. cur = ggml_get_rows(ctx0, inp, inp_cls);
  8197. } break;
  8198. case LLAMA_POOLING_TYPE_NONE:
  8199. {
  8200. cur = inp;
  8201. } break;
  8202. default:
  8203. {
  8204. GGML_ABORT("unknown pooling type");
  8205. }
  8206. }
  8207. cb(cur, "result_embd_pooled", -1);
  8208. ggml_build_forward_expand(gf, cur);
  8209. return gf;
  8210. }
  8211. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  8212. if (causal) {
  8213. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  8214. } else {
  8215. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  8216. }
  8217. ggml_set_input(lctx.inp_pos_bucket);
  8218. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  8219. return lctx.inp_pos_bucket;
  8220. }
  8221. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  8222. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  8223. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  8224. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  8225. cb(pos_bias, "pos_bias", -1);
  8226. 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);
  8227. cb(pos_bias, "pos_bias", -1);
  8228. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  8229. cb(pos_bias, "pos_bias", -1);
  8230. pos_bias = ggml_cont(ctx0, pos_bias);
  8231. cb(pos_bias, "pos_bias", -1);
  8232. return pos_bias;
  8233. }
  8234. struct ggml_tensor * llm_build_inp_embd_enc() {
  8235. const int64_t n_embd = hparams.n_embd;
  8236. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  8237. ggml_set_input(lctx.inp_embd_enc);
  8238. cb(lctx.inp_embd_enc, "embd_enc", -1);
  8239. return lctx.inp_embd_enc;
  8240. }
  8241. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  8242. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  8243. ggml_set_input(lctx.inp_KQ_mask_cross);
  8244. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  8245. return lctx.inp_KQ_mask_cross;
  8246. }
  8247. struct ggml_cgraph * build_llama() {
  8248. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8249. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8250. int32_t n_tokens = this->n_tokens;
  8251. const int64_t n_embd_head = hparams.n_embd_head_v;
  8252. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8253. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8254. struct ggml_tensor * cur;
  8255. struct ggml_tensor * inpL;
  8256. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8257. // inp_pos - contains the positions
  8258. struct ggml_tensor * inp_pos = build_inp_pos();
  8259. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8260. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8261. for (int il = 0; il < n_layer; ++il) {
  8262. struct ggml_tensor * inpSA = inpL;
  8263. // norm
  8264. cur = llm_build_norm(ctx0, inpL, hparams,
  8265. model.layers[il].attn_norm, NULL,
  8266. LLM_NORM_RMS, cb, il);
  8267. cb(cur, "attn_norm", il);
  8268. // self-attention
  8269. {
  8270. // rope freq factors for llama3; may return nullptr for llama2 and other models
  8271. struct ggml_tensor * rope_factors = build_rope_factors(il);
  8272. // compute Q and K and RoPE them
  8273. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8274. cb(Qcur, "Qcur", il);
  8275. if (model.layers[il].bq) {
  8276. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8277. cb(Qcur, "Qcur", il);
  8278. }
  8279. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8280. cb(Kcur, "Kcur", il);
  8281. if (model.layers[il].bk) {
  8282. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8283. cb(Kcur, "Kcur", il);
  8284. }
  8285. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8286. cb(Vcur, "Vcur", il);
  8287. if (model.layers[il].bv) {
  8288. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8289. cb(Vcur, "Vcur", il);
  8290. }
  8291. Qcur = ggml_rope_ext(
  8292. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  8293. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8294. ext_factor, attn_factor, beta_fast, beta_slow
  8295. );
  8296. cb(Qcur, "Qcur", il);
  8297. Kcur = ggml_rope_ext(
  8298. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  8299. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8300. ext_factor, attn_factor, beta_fast, beta_slow
  8301. );
  8302. cb(Kcur, "Kcur", il);
  8303. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8304. model.layers[il].wo, model.layers[il].bo,
  8305. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8306. }
  8307. if (il == n_layer - 1) {
  8308. // skip computing output for unused tokens
  8309. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8310. n_tokens = n_outputs;
  8311. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8312. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8313. }
  8314. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8315. cb(ffn_inp, "ffn_inp", il);
  8316. // feed-forward network
  8317. if (model.layers[il].ffn_gate_inp == nullptr) {
  8318. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8319. model.layers[il].ffn_norm, NULL,
  8320. LLM_NORM_RMS, cb, il);
  8321. cb(cur, "ffn_norm", il);
  8322. cur = llm_build_ffn(ctx0, lctx, cur,
  8323. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8324. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  8325. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8326. NULL,
  8327. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8328. cb(cur, "ffn_out", il);
  8329. } else {
  8330. // MoE branch
  8331. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8332. model.layers[il].ffn_norm, NULL,
  8333. LLM_NORM_RMS, cb, il);
  8334. cb(cur, "ffn_norm", il);
  8335. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8336. model.layers[il].ffn_gate_inp,
  8337. model.layers[il].ffn_up_exps,
  8338. model.layers[il].ffn_gate_exps,
  8339. model.layers[il].ffn_down_exps,
  8340. n_expert, n_expert_used,
  8341. LLM_FFN_SILU, true,
  8342. false, 0.0,
  8343. cb, il);
  8344. cb(cur, "ffn_moe_out", il);
  8345. }
  8346. cur = ggml_add(ctx0, cur, ffn_inp);
  8347. cb(cur, "ffn_out", il);
  8348. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8349. cb(cur, "l_out", il);
  8350. // input for next layer
  8351. inpL = cur;
  8352. }
  8353. cur = inpL;
  8354. cur = llm_build_norm(ctx0, cur, hparams,
  8355. model.output_norm, NULL,
  8356. LLM_NORM_RMS, cb, -1);
  8357. cb(cur, "result_norm", -1);
  8358. // lm_head
  8359. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8360. cb(cur, "result_output", -1);
  8361. ggml_build_forward_expand(gf, cur);
  8362. return gf;
  8363. }
  8364. struct ggml_cgraph * build_baichuan() {
  8365. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8366. const int64_t n_embd_head = hparams.n_embd_head_v;
  8367. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8368. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8369. struct ggml_tensor * cur;
  8370. struct ggml_tensor * inpL;
  8371. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8372. // inp_pos - contains the positions
  8373. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  8374. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8375. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8376. for (int il = 0; il < n_layer; ++il) {
  8377. struct ggml_tensor * inpSA = inpL;
  8378. cur = llm_build_norm(ctx0, inpL, hparams,
  8379. model.layers[il].attn_norm, NULL,
  8380. LLM_NORM_RMS, cb, il);
  8381. cb(cur, "attn_norm", il);
  8382. // self-attention
  8383. {
  8384. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8385. cb(Qcur, "Qcur", il);
  8386. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8387. cb(Kcur, "Kcur", il);
  8388. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8389. cb(Vcur, "Vcur", il);
  8390. switch (model.type) {
  8391. case MODEL_7B:
  8392. Qcur = ggml_rope_ext(
  8393. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8394. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8395. ext_factor, attn_factor, beta_fast, beta_slow
  8396. );
  8397. Kcur = ggml_rope_ext(
  8398. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8399. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8400. ext_factor, attn_factor, beta_fast, beta_slow
  8401. );
  8402. break;
  8403. case MODEL_13B:
  8404. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  8405. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  8406. break;
  8407. default:
  8408. GGML_ABORT("fatal error");
  8409. }
  8410. cb(Qcur, "Qcur", il);
  8411. cb(Kcur, "Kcur", il);
  8412. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8413. model.layers[il].wo, NULL,
  8414. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8415. }
  8416. if (il == n_layer - 1) {
  8417. // skip computing output for unused tokens
  8418. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8419. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8420. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8421. }
  8422. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8423. cb(ffn_inp, "ffn_inp", il);
  8424. // feed-forward network
  8425. {
  8426. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8427. model.layers[il].ffn_norm, NULL,
  8428. LLM_NORM_RMS, cb, il);
  8429. cb(cur, "ffn_norm", il);
  8430. cur = llm_build_ffn(ctx0, lctx, cur,
  8431. model.layers[il].ffn_up, NULL, NULL,
  8432. model.layers[il].ffn_gate, NULL, NULL,
  8433. model.layers[il].ffn_down, NULL, NULL,
  8434. NULL,
  8435. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8436. cb(cur, "ffn_out", il);
  8437. }
  8438. cur = ggml_add(ctx0, cur, ffn_inp);
  8439. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8440. cb(cur, "l_out", il);
  8441. // input for next layer
  8442. inpL = cur;
  8443. }
  8444. cur = inpL;
  8445. cur = llm_build_norm(ctx0, cur, hparams,
  8446. model.output_norm, NULL,
  8447. LLM_NORM_RMS, cb, -1);
  8448. cb(cur, "result_norm", -1);
  8449. // lm_head
  8450. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8451. cb(cur, "result_output", -1);
  8452. ggml_build_forward_expand(gf, cur);
  8453. return gf;
  8454. }
  8455. struct ggml_cgraph * build_xverse() {
  8456. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8457. const int64_t n_embd_head = hparams.n_embd_head_v;
  8458. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8459. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8460. struct ggml_tensor * cur;
  8461. struct ggml_tensor * inpL;
  8462. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8463. // inp_pos - contains the positions
  8464. struct ggml_tensor * inp_pos = build_inp_pos();
  8465. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8466. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8467. for (int il = 0; il < n_layer; ++il) {
  8468. struct ggml_tensor * inpSA = inpL;
  8469. cur = llm_build_norm(ctx0, inpL, hparams,
  8470. model.layers[il].attn_norm, NULL,
  8471. LLM_NORM_RMS, cb, il);
  8472. cb(cur, "attn_norm", il);
  8473. // self-attention
  8474. {
  8475. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8476. cb(Qcur, "Qcur", il);
  8477. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8478. cb(Kcur, "Kcur", il);
  8479. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8480. cb(Vcur, "Vcur", il);
  8481. Qcur = ggml_rope_ext(
  8482. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8483. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8484. ext_factor, attn_factor, beta_fast, beta_slow
  8485. );
  8486. cb(Qcur, "Qcur", il);
  8487. Kcur = ggml_rope_ext(
  8488. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8489. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8490. ext_factor, attn_factor, beta_fast, beta_slow
  8491. );
  8492. cb(Kcur, "Kcur", il);
  8493. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8494. model.layers[il].wo, NULL,
  8495. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8496. }
  8497. if (il == n_layer - 1) {
  8498. // skip computing output for unused tokens
  8499. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8500. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8501. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8502. }
  8503. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8504. cb(ffn_inp, "ffn_inp", il);
  8505. // feed-forward network
  8506. {
  8507. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8508. model.layers[il].ffn_norm, NULL,
  8509. LLM_NORM_RMS, cb, il);
  8510. cb(cur, "ffn_norm", il);
  8511. cur = llm_build_ffn(ctx0, lctx, cur,
  8512. model.layers[il].ffn_up, NULL, NULL,
  8513. model.layers[il].ffn_gate, NULL, NULL,
  8514. model.layers[il].ffn_down, NULL, NULL,
  8515. NULL,
  8516. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8517. cb(cur, "ffn_out", il);
  8518. }
  8519. cur = ggml_add(ctx0, cur, ffn_inp);
  8520. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8521. cb(cur, "l_out", il);
  8522. // input for next layer
  8523. inpL = cur;
  8524. }
  8525. cur = inpL;
  8526. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  8527. cb(cur, "result_norm", -1);
  8528. // lm_head
  8529. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8530. cb(cur, "result_output", -1);
  8531. ggml_build_forward_expand(gf, cur);
  8532. return gf;
  8533. }
  8534. struct ggml_cgraph * build_falcon() {
  8535. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8536. const int64_t n_embd_head = hparams.n_embd_head_v;
  8537. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8538. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8539. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8540. struct ggml_tensor * cur;
  8541. struct ggml_tensor * inpL;
  8542. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8543. // inp_pos - contains the positions
  8544. struct ggml_tensor * inp_pos = build_inp_pos();
  8545. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8546. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8547. for (int il = 0; il < n_layer; ++il) {
  8548. struct ggml_tensor * attn_norm;
  8549. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  8550. model.layers[il].attn_norm,
  8551. model.layers[il].attn_norm_b,
  8552. LLM_NORM, cb, il);
  8553. cb(attn_norm, "attn_norm", il);
  8554. // self-attention
  8555. {
  8556. if (model.layers[il].attn_norm_2) {
  8557. // Falcon-40B
  8558. cur = llm_build_norm(ctx0, inpL, hparams,
  8559. model.layers[il].attn_norm_2,
  8560. model.layers[il].attn_norm_2_b,
  8561. LLM_NORM, cb, il);
  8562. cb(cur, "attn_norm_2", il);
  8563. } else {
  8564. cur = attn_norm;
  8565. }
  8566. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8567. cb(cur, "wqkv", il);
  8568. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8569. 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)));
  8570. 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)));
  8571. cb(Qcur, "Qcur", il);
  8572. cb(Kcur, "Kcur", il);
  8573. cb(Vcur, "Vcur", il);
  8574. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8575. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8576. // using mode = 2 for neox mode
  8577. Qcur = ggml_rope_ext(
  8578. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8579. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8580. );
  8581. cb(Qcur, "Qcur", il);
  8582. Kcur = ggml_rope_ext(
  8583. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8584. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8585. );
  8586. cb(Kcur, "Kcur", il);
  8587. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8588. model.layers[il].wo, NULL,
  8589. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8590. }
  8591. if (il == n_layer - 1) {
  8592. // skip computing output for unused tokens
  8593. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8594. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8595. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8596. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  8597. }
  8598. struct ggml_tensor * ffn_inp = cur;
  8599. // feed forward
  8600. {
  8601. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  8602. model.layers[il].ffn_up, NULL, NULL,
  8603. NULL, NULL, NULL,
  8604. model.layers[il].ffn_down, NULL, NULL,
  8605. NULL,
  8606. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8607. cb(cur, "ffn_out", il);
  8608. }
  8609. cur = ggml_add(ctx0, cur, ffn_inp);
  8610. cur = ggml_add(ctx0, cur, inpL);
  8611. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8612. cb(cur, "l_out", il);
  8613. // input for next layer
  8614. inpL = cur;
  8615. }
  8616. cur = inpL;
  8617. // norm
  8618. cur = llm_build_norm(ctx0, cur, hparams,
  8619. model.output_norm,
  8620. model.output_norm_b,
  8621. LLM_NORM, cb, -1);
  8622. cb(cur, "result_norm", -1);
  8623. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8624. cb(cur, "result_output", -1);
  8625. ggml_build_forward_expand(gf, cur);
  8626. return gf;
  8627. }
  8628. struct ggml_cgraph * build_grok() {
  8629. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8630. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8631. int32_t n_tokens = this->n_tokens;
  8632. const int64_t n_embd_head = hparams.n_embd_head_v;
  8633. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8634. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8635. struct ggml_tensor * cur;
  8636. struct ggml_tensor * inpL;
  8637. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8638. // multiply by embedding_multiplier_scale of 78.38367176906169
  8639. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  8640. // inp_pos - contains the positions
  8641. struct ggml_tensor * inp_pos = build_inp_pos();
  8642. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8643. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8644. for (int il = 0; il < n_layer; ++il) {
  8645. struct ggml_tensor * inpSA = inpL;
  8646. // norm
  8647. cur = llm_build_norm(ctx0, inpL, hparams,
  8648. model.layers[il].attn_norm, NULL,
  8649. LLM_NORM_RMS, cb, il);
  8650. cb(cur, "attn_norm", il);
  8651. // self-attention
  8652. {
  8653. // compute Q and K and RoPE them
  8654. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8655. cb(Qcur, "Qcur", il);
  8656. if (model.layers[il].bq) {
  8657. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8658. cb(Qcur, "Qcur", il);
  8659. }
  8660. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8661. cb(Kcur, "Kcur", il);
  8662. if (model.layers[il].bk) {
  8663. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8664. cb(Kcur, "Kcur", il);
  8665. }
  8666. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8667. cb(Vcur, "Vcur", il);
  8668. if (model.layers[il].bv) {
  8669. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8670. cb(Vcur, "Vcur", il);
  8671. }
  8672. Qcur = ggml_rope_ext(
  8673. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8674. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8675. ext_factor, attn_factor, beta_fast, beta_slow
  8676. );
  8677. cb(Qcur, "Qcur", il);
  8678. Kcur = ggml_rope_ext(
  8679. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8680. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8681. ext_factor, attn_factor, beta_fast, beta_slow
  8682. );
  8683. cb(Kcur, "Kcur", il);
  8684. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8685. model.layers[il].wo, model.layers[il].bo,
  8686. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  8687. }
  8688. if (il == n_layer - 1) {
  8689. // skip computing output for unused tokens
  8690. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8691. n_tokens = n_outputs;
  8692. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8693. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8694. }
  8695. // Grok
  8696. // if attn_out_norm is present then apply it before adding the input
  8697. if (model.layers[il].attn_out_norm) {
  8698. cur = llm_build_norm(ctx0, cur, hparams,
  8699. model.layers[il].attn_out_norm, NULL,
  8700. LLM_NORM_RMS, cb, il);
  8701. cb(cur, "attn_out_norm", il);
  8702. }
  8703. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8704. cb(ffn_inp, "ffn_inp", il);
  8705. // feed-forward network
  8706. // MoE branch
  8707. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8708. model.layers[il].ffn_norm, NULL,
  8709. LLM_NORM_RMS, cb, il);
  8710. cb(cur, "ffn_norm", il);
  8711. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8712. model.layers[il].ffn_gate_inp,
  8713. model.layers[il].ffn_up_exps,
  8714. model.layers[il].ffn_gate_exps,
  8715. model.layers[il].ffn_down_exps,
  8716. n_expert, n_expert_used,
  8717. LLM_FFN_GELU, true,
  8718. false, 0.0,
  8719. cb, il);
  8720. cb(cur, "ffn_moe_out", il);
  8721. // Grok
  8722. // if layer_out_norm is present then apply it before adding the input
  8723. // Idea: maybe ffn_out_norm is a better name
  8724. if (model.layers[il].layer_out_norm) {
  8725. cur = llm_build_norm(ctx0, cur, hparams,
  8726. model.layers[il].layer_out_norm, NULL,
  8727. LLM_NORM_RMS, cb, il);
  8728. cb(cur, "layer_out_norm", il);
  8729. }
  8730. cur = ggml_add(ctx0, cur, ffn_inp);
  8731. cb(cur, "ffn_out", il);
  8732. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8733. cb(cur, "l_out", il);
  8734. // input for next layer
  8735. inpL = cur;
  8736. }
  8737. cur = inpL;
  8738. cur = llm_build_norm(ctx0, cur, hparams,
  8739. model.output_norm, NULL,
  8740. LLM_NORM_RMS, cb, -1);
  8741. cb(cur, "result_norm", -1);
  8742. // lm_head
  8743. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8744. // Grok
  8745. // multiply logits by output_multiplier_scale of 0.5773502691896257
  8746. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  8747. cb(cur, "result_output", -1);
  8748. ggml_build_forward_expand(gf, cur);
  8749. return gf;
  8750. }
  8751. struct ggml_cgraph * build_dbrx() {
  8752. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8753. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8754. int32_t n_tokens = this->n_tokens;
  8755. const int64_t n_embd_head = hparams.n_embd_head_v;
  8756. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8757. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8758. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8759. struct ggml_tensor * cur;
  8760. struct ggml_tensor * inpL;
  8761. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8762. // inp_pos - contains the positions
  8763. struct ggml_tensor * inp_pos = build_inp_pos();
  8764. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8765. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8766. for (int il = 0; il < n_layer; ++il) {
  8767. struct ggml_tensor * inpSA = inpL;
  8768. // norm
  8769. cur = llm_build_norm(ctx0, inpL, hparams,
  8770. model.layers[il].attn_norm, NULL,
  8771. LLM_NORM, cb, il);
  8772. cb(cur, "attn_norm", il);
  8773. // self-attention
  8774. {
  8775. struct ggml_tensor * Qcur = nullptr;
  8776. struct ggml_tensor * Kcur = nullptr;
  8777. struct ggml_tensor * Vcur = nullptr;
  8778. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8779. cb(cur, "wqkv", il);
  8780. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8781. cb(cur, "wqkv_clamped", il);
  8782. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8783. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8784. 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)));
  8785. cb(Qcur, "Qcur", il);
  8786. cb(Kcur, "Kcur", il);
  8787. cb(Vcur, "Vcur", il);
  8788. Qcur = ggml_rope_ext(
  8789. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8790. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8791. ext_factor, attn_factor, beta_fast, beta_slow
  8792. );
  8793. cb(Qcur, "Qcur", il);
  8794. Kcur = ggml_rope_ext(
  8795. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8796. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8797. ext_factor, attn_factor, beta_fast, beta_slow
  8798. );
  8799. cb(Kcur, "Kcur", il);
  8800. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8801. model.layers[il].wo, NULL,
  8802. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8803. }
  8804. if (il == n_layer - 1) {
  8805. // skip computing output for unused tokens
  8806. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8807. n_tokens = n_outputs;
  8808. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8809. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8810. }
  8811. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8812. cb(ffn_inp, "ffn_inp", il);
  8813. // feed-forward network
  8814. // MoE branch
  8815. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8816. model.layers[il].attn_out_norm, NULL,
  8817. LLM_NORM, cb, il);
  8818. cb(cur, "attn_out_norm", il);
  8819. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8820. model.layers[il].ffn_gate_inp,
  8821. model.layers[il].ffn_up_exps,
  8822. model.layers[il].ffn_gate_exps,
  8823. model.layers[il].ffn_down_exps,
  8824. n_expert, n_expert_used,
  8825. LLM_FFN_SILU, true,
  8826. false, 0.0,
  8827. cb, il);
  8828. cb(cur, "ffn_moe_out", il);
  8829. cur = ggml_add(ctx0, cur, ffn_inp);
  8830. cb(cur, "ffn_out", il);
  8831. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8832. cb(cur, "l_out", il);
  8833. // input for next layer
  8834. inpL = cur;
  8835. }
  8836. cur = inpL;
  8837. cur = llm_build_norm(ctx0, cur, hparams,
  8838. model.output_norm, NULL,
  8839. LLM_NORM, cb, -1);
  8840. cb(cur, "result_norm", -1);
  8841. // lm_head
  8842. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8843. cb(cur, "result_output", -1);
  8844. ggml_build_forward_expand(gf, cur);
  8845. return gf;
  8846. }
  8847. struct ggml_cgraph * build_starcoder() {
  8848. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8849. const int64_t n_embd_head = hparams.n_embd_head_v;
  8850. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8851. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8852. struct ggml_tensor * cur;
  8853. struct ggml_tensor * inpL;
  8854. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8855. // inp_pos - contains the positions
  8856. struct ggml_tensor * inp_pos = build_inp_pos();
  8857. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8858. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8859. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8860. cb(pos, "pos_embd", -1);
  8861. inpL = ggml_add(ctx0, inpL, pos);
  8862. cb(inpL, "inpL", -1);
  8863. for (int il = 0; il < n_layer; ++il) {
  8864. cur = llm_build_norm(ctx0, inpL, hparams,
  8865. model.layers[il].attn_norm,
  8866. model.layers[il].attn_norm_b,
  8867. LLM_NORM, cb, il);
  8868. cb(cur, "attn_norm", il);
  8869. // self-attention
  8870. {
  8871. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8872. cb(cur, "wqkv", il);
  8873. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8874. cb(cur, "bqkv", il);
  8875. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8876. 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)));
  8877. 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)));
  8878. cb(Qcur, "Qcur", il);
  8879. cb(Kcur, "Kcur", il);
  8880. cb(Vcur, "Vcur", il);
  8881. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8882. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8883. model.layers[il].wo, model.layers[il].bo,
  8884. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8885. }
  8886. if (il == n_layer - 1) {
  8887. // skip computing output for unused tokens
  8888. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8889. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8890. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8891. }
  8892. // add the input
  8893. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8894. cb(ffn_inp, "ffn_inp", il);
  8895. // FF
  8896. {
  8897. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8898. model.layers[il].ffn_norm,
  8899. model.layers[il].ffn_norm_b,
  8900. LLM_NORM, cb, il);
  8901. cb(cur, "ffn_norm", il);
  8902. cur = llm_build_ffn(ctx0, lctx, cur,
  8903. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8904. NULL, NULL, NULL,
  8905. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8906. NULL,
  8907. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8908. cb(cur, "ffn_out", il);
  8909. }
  8910. cur = ggml_add(ctx0, cur, ffn_inp);
  8911. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8912. cb(cur, "l_out", il);
  8913. // input for next layer
  8914. inpL = cur;
  8915. }
  8916. cur = llm_build_norm(ctx0, inpL, hparams,
  8917. model.output_norm,
  8918. model.output_norm_b,
  8919. LLM_NORM, cb, -1);
  8920. cb(cur, "result_norm", -1);
  8921. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8922. cb(cur, "result_output", -1);
  8923. ggml_build_forward_expand(gf, cur);
  8924. return gf;
  8925. }
  8926. struct ggml_cgraph * build_refact() {
  8927. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8928. const int64_t n_embd_head = hparams.n_embd_head_v;
  8929. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8930. struct ggml_tensor * cur;
  8931. struct ggml_tensor * inpL;
  8932. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8933. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8934. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8935. for (int il = 0; il < n_layer; ++il) {
  8936. struct ggml_tensor * inpSA = inpL;
  8937. cur = llm_build_norm(ctx0, inpL, hparams,
  8938. model.layers[il].attn_norm, NULL,
  8939. LLM_NORM_RMS, cb, il);
  8940. cb(cur, "attn_norm", il);
  8941. // self-attention
  8942. {
  8943. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8944. cb(Qcur, "Qcur", il);
  8945. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8946. cb(Kcur, "Kcur", il);
  8947. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8948. cb(Vcur, "Vcur", il);
  8949. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8950. cb(Kcur, "Kcur", il);
  8951. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8952. cb(Qcur, "Qcur", il);
  8953. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8954. model.layers[il].wo, NULL,
  8955. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8956. }
  8957. if (il == n_layer - 1) {
  8958. // skip computing output for unused tokens
  8959. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8960. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8961. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8962. }
  8963. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8964. cb(ffn_inp, "ffn_inp", il);
  8965. // feed-forward network
  8966. {
  8967. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8968. model.layers[il].ffn_norm, NULL,
  8969. LLM_NORM_RMS, cb, il);
  8970. cb(cur, "ffn_norm", il);
  8971. cur = llm_build_ffn(ctx0, lctx, cur,
  8972. model.layers[il].ffn_up, NULL, NULL,
  8973. model.layers[il].ffn_gate, NULL, NULL,
  8974. model.layers[il].ffn_down, NULL, NULL,
  8975. NULL,
  8976. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8977. cb(cur, "ffn_out", il);
  8978. }
  8979. cur = ggml_add(ctx0, cur, ffn_inp);
  8980. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8981. cb(cur, "l_out", il);
  8982. // input for next layer
  8983. inpL = cur;
  8984. }
  8985. cur = inpL;
  8986. cur = llm_build_norm(ctx0, cur, hparams,
  8987. model.output_norm, NULL,
  8988. LLM_NORM_RMS, cb, -1);
  8989. cb(cur, "result_norm", -1);
  8990. // lm_head
  8991. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8992. cb(cur, "result_output", -1);
  8993. ggml_build_forward_expand(gf, cur);
  8994. return gf;
  8995. }
  8996. struct ggml_cgraph * build_bert() {
  8997. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8998. const int64_t n_embd_head = hparams.n_embd_head_v;
  8999. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9000. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9001. struct ggml_tensor * cur;
  9002. struct ggml_tensor * inpL;
  9003. struct ggml_tensor * inp_pos = nullptr;
  9004. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  9005. inp_pos = build_inp_pos();
  9006. }
  9007. // construct input embeddings (token, type, position)
  9008. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9009. // token types are hardcoded to zero ("Sentence A")
  9010. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  9011. inpL = ggml_add(ctx0, inpL, type_row0);
  9012. if (model.arch == LLM_ARCH_BERT) {
  9013. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  9014. }
  9015. cb(inpL, "inp_embd", -1);
  9016. // embed layer norm
  9017. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  9018. cb(inpL, "inp_norm", -1);
  9019. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9020. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  9021. // iterate layers
  9022. for (int il = 0; il < n_layer; ++il) {
  9023. struct ggml_tensor * cur = inpL;
  9024. struct ggml_tensor * Qcur;
  9025. struct ggml_tensor * Kcur;
  9026. struct ggml_tensor * Vcur;
  9027. // self-attention
  9028. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  9029. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  9030. cb(Qcur, "Qcur", il);
  9031. if (model.layers[il].attn_q_norm) {
  9032. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  9033. model.layers[il].attn_q_norm,
  9034. model.layers[il].attn_q_norm_b,
  9035. LLM_NORM, cb, il);
  9036. }
  9037. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  9038. cb(Kcur, "Kcur", il);
  9039. if (model.layers[il].attn_k_norm) {
  9040. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  9041. model.layers[il].attn_k_norm,
  9042. model.layers[il].attn_k_norm_b,
  9043. LLM_NORM, cb, il);
  9044. }
  9045. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  9046. cb(Vcur, "Vcur", il);
  9047. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9048. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9049. } else {
  9050. // compute Q and K and RoPE them
  9051. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9052. cb(cur, "wqkv", il);
  9053. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9054. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9055. 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)));
  9056. cb(Qcur, "Qcur", il);
  9057. cb(Kcur, "Kcur", il);
  9058. cb(Vcur, "Vcur", il);
  9059. Qcur = ggml_rope_ext(
  9060. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9061. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9062. ext_factor, attn_factor, beta_fast, beta_slow
  9063. );
  9064. cb(Qcur, "Qcur", il);
  9065. Kcur = ggml_rope_ext(
  9066. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9067. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9068. ext_factor, attn_factor, beta_fast, beta_slow
  9069. );
  9070. cb(Kcur, "Kcur", il);
  9071. }
  9072. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  9073. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  9074. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  9075. cb(kq, "kq", il);
  9076. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  9077. cb(kq, "kq_soft_max_ext", il);
  9078. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  9079. cb(v, "v", il);
  9080. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  9081. cb(kqv, "kqv", il);
  9082. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  9083. cb(kqv_merged, "kqv_merged", il);
  9084. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  9085. cb(cur, "kqv_merged_cont", il);
  9086. ggml_build_forward_expand(gf, cur);
  9087. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  9088. if (model.layers[il].bo) {
  9089. cb(cur, "kqv_wo", il);
  9090. }
  9091. if (model.layers[il].bo) {
  9092. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  9093. }
  9094. cb(cur, "kqv_out", il);
  9095. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  9096. // skip computing output for unused tokens
  9097. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9098. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9099. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9100. }
  9101. // re-add the layer input
  9102. cur = ggml_add(ctx0, cur, inpL);
  9103. // attention layer norm
  9104. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  9105. if (model.layers[il].attn_norm_2 != nullptr) {
  9106. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  9107. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  9108. }
  9109. struct ggml_tensor * ffn_inp = cur;
  9110. cb(ffn_inp, "ffn_inp", il);
  9111. // feed-forward network
  9112. if (model.arch == LLM_ARCH_BERT) {
  9113. cur = llm_build_ffn(ctx0, lctx, cur,
  9114. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9115. NULL, NULL, NULL,
  9116. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9117. NULL,
  9118. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9119. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  9120. cur = llm_build_ffn(ctx0, lctx, cur,
  9121. model.layers[il].ffn_up, NULL, NULL,
  9122. model.layers[il].ffn_gate, NULL, NULL,
  9123. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9124. NULL,
  9125. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9126. } else {
  9127. cur = llm_build_ffn(ctx0, lctx, cur,
  9128. model.layers[il].ffn_up, NULL, NULL,
  9129. model.layers[il].ffn_gate, NULL, NULL,
  9130. model.layers[il].ffn_down, NULL, NULL,
  9131. NULL,
  9132. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9133. }
  9134. cb(cur, "ffn_out", il);
  9135. // attentions bypass the intermediate layer
  9136. cur = ggml_add(ctx0, cur, ffn_inp);
  9137. // output layer norm
  9138. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  9139. // input for next layer
  9140. inpL = cur;
  9141. }
  9142. // final output
  9143. cur = inpL;
  9144. cb(cur, "result_embd", -1);
  9145. ggml_build_forward_expand(gf, cur);
  9146. return gf;
  9147. }
  9148. struct ggml_cgraph * build_bloom() {
  9149. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9150. const int64_t n_embd_head = hparams.n_embd_head_v;
  9151. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9152. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9153. struct ggml_tensor * cur;
  9154. struct ggml_tensor * inpL;
  9155. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9156. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9157. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9158. inpL = llm_build_norm(ctx0, inpL, hparams,
  9159. model.tok_norm,
  9160. model.tok_norm_b,
  9161. LLM_NORM, cb, -1);
  9162. cb(inpL, "inp_norm", -1);
  9163. for (int il = 0; il < n_layer; ++il) {
  9164. cur = llm_build_norm(ctx0, inpL, hparams,
  9165. model.layers[il].attn_norm,
  9166. model.layers[il].attn_norm_b,
  9167. LLM_NORM, cb, il);
  9168. cb(cur, "attn_norm", il);
  9169. // self-attention
  9170. {
  9171. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9172. cb(cur, "wqkv", il);
  9173. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9174. cb(cur, "bqkv", il);
  9175. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9176. 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)));
  9177. 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)));
  9178. cb(Qcur, "Qcur", il);
  9179. cb(Kcur, "Kcur", il);
  9180. cb(Vcur, "Vcur", il);
  9181. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9182. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9183. model.layers[il].wo, model.layers[il].bo,
  9184. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9185. }
  9186. if (il == n_layer - 1) {
  9187. // skip computing output for unused tokens
  9188. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9189. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9190. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9191. }
  9192. // Add the input
  9193. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9194. cb(ffn_inp, "ffn_inp", il);
  9195. // FF
  9196. {
  9197. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9198. model.layers[il].ffn_norm,
  9199. model.layers[il].ffn_norm_b,
  9200. LLM_NORM, cb, il);
  9201. cb(cur, "ffn_norm", il);
  9202. cur = llm_build_ffn(ctx0, lctx, cur,
  9203. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9204. NULL, NULL, NULL,
  9205. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9206. NULL,
  9207. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9208. cb(cur, "ffn_out", il);
  9209. }
  9210. cur = ggml_add(ctx0, cur, ffn_inp);
  9211. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9212. cb(cur, "l_out", il);
  9213. // input for next layer
  9214. inpL = cur;
  9215. }
  9216. cur = llm_build_norm(ctx0, inpL, hparams,
  9217. model.output_norm,
  9218. model.output_norm_b,
  9219. LLM_NORM, cb, -1);
  9220. cb(cur, "result_norm", -1);
  9221. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9222. cb(cur, "result_output", -1);
  9223. ggml_build_forward_expand(gf, cur);
  9224. return gf;
  9225. }
  9226. struct ggml_cgraph * build_mpt() {
  9227. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9228. const int64_t n_embd_head = hparams.n_embd_head_v;
  9229. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9230. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9231. struct ggml_tensor * cur;
  9232. struct ggml_tensor * pos;
  9233. struct ggml_tensor * inpL;
  9234. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9235. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9236. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9237. if (model.pos_embd) {
  9238. // inp_pos - contains the positions
  9239. struct ggml_tensor * inp_pos = build_inp_pos();
  9240. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  9241. cb(pos, "pos_embd", -1);
  9242. inpL = ggml_add(ctx0, inpL, pos);
  9243. cb(inpL, "inpL", -1);
  9244. }
  9245. for (int il = 0; il < n_layer; ++il) {
  9246. struct ggml_tensor * attn_norm;
  9247. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  9248. model.layers[il].attn_norm,
  9249. model.layers[il].attn_norm_b,
  9250. LLM_NORM, cb, il);
  9251. cb(attn_norm, "attn_norm", il);
  9252. // self-attention
  9253. {
  9254. cur = attn_norm;
  9255. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9256. cb(cur, "wqkv", il);
  9257. if (model.layers[il].bqkv){
  9258. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9259. cb(cur, "bqkv", il);
  9260. }
  9261. if (hparams.f_clamp_kqv > 0.0f) {
  9262. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  9263. cb(cur, "wqkv_clamped", il);
  9264. }
  9265. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9266. 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)));
  9267. 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)));
  9268. cb(Qcur, "Qcur", il);
  9269. cb(Kcur, "Kcur", il);
  9270. cb(Vcur, "Vcur", il);
  9271. // Q/K Layernorm
  9272. if (model.layers[il].attn_q_norm) {
  9273. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  9274. model.layers[il].attn_q_norm,
  9275. model.layers[il].attn_q_norm_b,
  9276. LLM_NORM, cb, il);
  9277. cb(Qcur, "Qcur", il);
  9278. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  9279. model.layers[il].attn_k_norm,
  9280. model.layers[il].attn_k_norm_b,
  9281. LLM_NORM, cb, il);
  9282. cb(Kcur, "Kcur", il);
  9283. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9284. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9285. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9286. model.layers[il].wo, model.layers[il].bo,
  9287. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9288. } else {
  9289. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9290. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9291. model.layers[il].wo, model.layers[il].bo,
  9292. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9293. }
  9294. }
  9295. if (il == n_layer - 1) {
  9296. // skip computing output for unused tokens
  9297. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9298. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9299. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9300. }
  9301. // Add the input
  9302. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9303. cb(ffn_inp, "ffn_inp", il);
  9304. // feed forward
  9305. {
  9306. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9307. model.layers[il].ffn_norm,
  9308. model.layers[il].ffn_norm_b,
  9309. LLM_NORM, cb, il);
  9310. cb(cur, "ffn_norm", il);
  9311. cur = llm_build_ffn(ctx0, lctx, cur,
  9312. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9313. NULL, NULL, NULL,
  9314. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9315. model.layers[il].ffn_act,
  9316. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9317. cb(cur, "ffn_out", il);
  9318. }
  9319. cur = ggml_add(ctx0, cur, ffn_inp);
  9320. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9321. cb(cur, "l_out", il);
  9322. // input for next layer
  9323. inpL = cur;
  9324. }
  9325. cur = inpL;
  9326. cur = llm_build_norm(ctx0, cur, hparams,
  9327. model.output_norm,
  9328. model.output_norm_b,
  9329. LLM_NORM, cb, -1);
  9330. cb(cur, "result_norm", -1);
  9331. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9332. cb(cur, "result_output", -1);
  9333. ggml_build_forward_expand(gf, cur);
  9334. return gf;
  9335. }
  9336. struct ggml_cgraph * build_stablelm() {
  9337. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  9338. const int64_t n_embd_head = hparams.n_embd_head_v;
  9339. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9340. struct ggml_tensor * cur;
  9341. struct ggml_tensor * inpL;
  9342. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9343. // inp_pos - contains the positions
  9344. struct ggml_tensor * inp_pos = build_inp_pos();
  9345. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9346. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9347. for (int il = 0; il < n_layer; ++il) {
  9348. // norm
  9349. cur = llm_build_norm(ctx0, inpL, hparams,
  9350. model.layers[il].attn_norm,
  9351. model.layers[il].attn_norm_b,
  9352. LLM_NORM, cb, il);
  9353. cb(cur, "attn_norm", il);
  9354. struct ggml_tensor * inpSA = cur;
  9355. // self-attention
  9356. {
  9357. // compute Q and K and RoPE them
  9358. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9359. cb(Qcur, "Qcur", il);
  9360. if (model.layers[il].bq) {
  9361. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9362. cb(Qcur, "Qcur", il);
  9363. }
  9364. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9365. cb(Kcur, "Kcur", il);
  9366. if (model.layers[il].bk) {
  9367. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9368. cb(Kcur, "Kcur", il);
  9369. }
  9370. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9371. cb(Vcur, "Vcur", il);
  9372. if (model.layers[il].bv) {
  9373. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9374. cb(Vcur, "Vcur", il);
  9375. }
  9376. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9377. cb(Qcur, "Qcur", il);
  9378. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9379. cb(Kcur, "Kcur", il);
  9380. if (model.layers[il].attn_q_norm) {
  9381. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  9382. model.layers[il].attn_q_norm,
  9383. NULL,
  9384. LLM_NORM, cb, il);
  9385. cb(Qcur, "Qcur", il);
  9386. }
  9387. if (model.layers[il].attn_k_norm) {
  9388. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  9389. model.layers[il].attn_k_norm,
  9390. NULL,
  9391. LLM_NORM, cb, il);
  9392. cb(Kcur, "Kcur", il);
  9393. }
  9394. Qcur = ggml_rope_ext(
  9395. ctx0, Qcur, inp_pos, nullptr,
  9396. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9397. ext_factor, attn_factor, beta_fast, beta_slow
  9398. );
  9399. cb(Qcur, "Qcur", il);
  9400. Kcur = ggml_rope_ext(
  9401. ctx0, Kcur, inp_pos, nullptr,
  9402. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9403. ext_factor, attn_factor, beta_fast, beta_slow
  9404. );
  9405. cb(Kcur, "Kcur", il);
  9406. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9407. model.layers[il].wo, NULL,
  9408. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9409. }
  9410. if (il == n_layer - 1) {
  9411. // skip computing output for unused tokens
  9412. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9413. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9414. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9415. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9416. }
  9417. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9418. cb(ffn_inp, "ffn_inp", il);
  9419. // feed-forward network
  9420. {
  9421. if (model.layers[il].ffn_norm) {
  9422. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9423. model.layers[il].ffn_norm,
  9424. model.layers[il].ffn_norm_b,
  9425. LLM_NORM, cb, il);
  9426. cb(cur, "ffn_norm", il);
  9427. } else {
  9428. // parallel residual
  9429. cur = inpSA;
  9430. }
  9431. cur = llm_build_ffn(ctx0, lctx, cur,
  9432. model.layers[il].ffn_up, NULL, NULL,
  9433. model.layers[il].ffn_gate, NULL, NULL,
  9434. model.layers[il].ffn_down, NULL, NULL,
  9435. NULL,
  9436. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9437. cb(cur, "ffn_out", il);
  9438. }
  9439. cur = ggml_add(ctx0, cur, ffn_inp);
  9440. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9441. cb(cur, "l_out", il);
  9442. // input for next layer
  9443. inpL = cur;
  9444. }
  9445. cur = inpL;
  9446. cur = llm_build_norm(ctx0, cur, hparams,
  9447. model.output_norm,
  9448. model.output_norm_b,
  9449. LLM_NORM, cb, -1);
  9450. cb(cur, "result_norm", -1);
  9451. // lm_head
  9452. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9453. cb(cur, "result_output", -1);
  9454. ggml_build_forward_expand(gf, cur);
  9455. return gf;
  9456. }
  9457. struct ggml_cgraph * build_qwen() {
  9458. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9459. const int64_t n_embd_head = hparams.n_embd_head_v;
  9460. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9461. struct ggml_tensor * cur;
  9462. struct ggml_tensor * inpL;
  9463. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9464. // inp_pos - contains the positions
  9465. struct ggml_tensor * inp_pos = build_inp_pos();
  9466. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9467. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9468. for (int il = 0; il < n_layer; ++il) {
  9469. struct ggml_tensor * inpSA = inpL;
  9470. cur = llm_build_norm(ctx0, inpL, hparams,
  9471. model.layers[il].attn_norm, NULL,
  9472. LLM_NORM_RMS, cb, il);
  9473. cb(cur, "attn_norm", il);
  9474. // self-attention
  9475. {
  9476. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9477. cb(cur, "wqkv", il);
  9478. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9479. cb(cur, "bqkv", il);
  9480. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9481. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9482. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  9483. cb(Qcur, "Qcur", il);
  9484. cb(Kcur, "Kcur", il);
  9485. cb(Vcur, "Vcur", il);
  9486. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9487. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9488. // using mode = 2 for neox mode
  9489. Qcur = ggml_rope_ext(
  9490. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9491. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9492. );
  9493. cb(Qcur, "Qcur", il);
  9494. Kcur = ggml_rope_ext(
  9495. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9496. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9497. );
  9498. cb(Kcur, "Kcur", il);
  9499. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9500. model.layers[il].wo, NULL,
  9501. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9502. }
  9503. if (il == n_layer - 1) {
  9504. // skip computing output for unused tokens
  9505. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9506. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9507. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9508. }
  9509. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9510. cb(ffn_inp, "ffn_inp", il);
  9511. // feed-forward forward
  9512. {
  9513. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9514. model.layers[il].ffn_norm, NULL,
  9515. LLM_NORM_RMS, cb, il);
  9516. cb(cur, "ffn_norm", il);
  9517. cur = llm_build_ffn(ctx0, lctx, cur,
  9518. model.layers[il].ffn_up, NULL, NULL,
  9519. model.layers[il].ffn_gate, NULL, NULL,
  9520. model.layers[il].ffn_down, NULL, NULL,
  9521. NULL,
  9522. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9523. cb(cur, "ffn_out", il);
  9524. }
  9525. cur = ggml_add(ctx0, cur, ffn_inp);
  9526. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9527. cb(cur, "l_out", il);
  9528. // input for next layer
  9529. inpL = cur;
  9530. }
  9531. cur = inpL;
  9532. cur = llm_build_norm(ctx0, cur, hparams,
  9533. model.output_norm, NULL,
  9534. LLM_NORM_RMS, cb, -1);
  9535. cb(cur, "result_norm", -1);
  9536. // lm_head
  9537. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9538. cb(cur, "result_output", -1);
  9539. ggml_build_forward_expand(gf, cur);
  9540. return gf;
  9541. }
  9542. struct ggml_cgraph * build_qwen2() {
  9543. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9544. const int64_t n_embd_head = hparams.n_embd_head_v;
  9545. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9546. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9547. struct ggml_tensor * cur;
  9548. struct ggml_tensor * inpL;
  9549. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9550. // inp_pos - contains the positions
  9551. struct ggml_tensor * inp_pos = build_inp_pos();
  9552. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9553. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9554. for (int il = 0; il < n_layer; ++il) {
  9555. struct ggml_tensor * inpSA = inpL;
  9556. // norm
  9557. cur = llm_build_norm(ctx0, inpL, hparams,
  9558. model.layers[il].attn_norm, NULL,
  9559. LLM_NORM_RMS, cb, il);
  9560. cb(cur, "attn_norm", il);
  9561. // self-attention
  9562. {
  9563. // compute Q and K and RoPE them
  9564. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9565. cb(Qcur, "Qcur", il);
  9566. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9567. cb(Qcur, "Qcur", il);
  9568. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9569. cb(Kcur, "Kcur", il);
  9570. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9571. cb(Kcur, "Kcur", il);
  9572. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9573. cb(Vcur, "Vcur", il);
  9574. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9575. cb(Vcur, "Vcur", il);
  9576. Qcur = ggml_rope_ext(
  9577. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9578. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9579. ext_factor, attn_factor, beta_fast, beta_slow
  9580. );
  9581. cb(Qcur, "Qcur", il);
  9582. Kcur = ggml_rope_ext(
  9583. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9584. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9585. ext_factor, attn_factor, beta_fast, beta_slow
  9586. );
  9587. cb(Kcur, "Kcur", il);
  9588. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9589. model.layers[il].wo, model.layers[il].bo,
  9590. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9591. }
  9592. if (il == n_layer - 1) {
  9593. // skip computing output for unused tokens
  9594. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9595. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9596. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9597. }
  9598. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9599. cb(ffn_inp, "ffn_inp", il);
  9600. // feed-forward network
  9601. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9602. model.layers[il].ffn_norm, NULL,
  9603. LLM_NORM_RMS, cb, il);
  9604. cb(cur, "ffn_norm", il);
  9605. cur = llm_build_ffn(ctx0, lctx, cur,
  9606. model.layers[il].ffn_up, NULL, NULL,
  9607. model.layers[il].ffn_gate, NULL, NULL,
  9608. model.layers[il].ffn_down, NULL, NULL,
  9609. NULL,
  9610. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9611. cb(cur, "ffn_out", il);
  9612. cur = ggml_add(ctx0, cur, ffn_inp);
  9613. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9614. cb(cur, "l_out", il);
  9615. // input for next layer
  9616. inpL = cur;
  9617. }
  9618. cur = inpL;
  9619. cur = llm_build_norm(ctx0, cur, hparams,
  9620. model.output_norm, NULL,
  9621. LLM_NORM_RMS, cb, -1);
  9622. cb(cur, "result_norm", -1);
  9623. // lm_head
  9624. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9625. cb(cur, "result_output", -1);
  9626. ggml_build_forward_expand(gf, cur);
  9627. return gf;
  9628. }
  9629. struct ggml_cgraph * build_qwen2moe() {
  9630. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9631. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9632. int32_t n_tokens = this->n_tokens;
  9633. const int64_t n_embd_head = hparams.n_embd_head_v;
  9634. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9635. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9636. struct ggml_tensor * cur;
  9637. struct ggml_tensor * inpL;
  9638. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9639. // inp_pos - contains the positions
  9640. struct ggml_tensor * inp_pos = build_inp_pos();
  9641. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9642. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9643. for (int il = 0; il < n_layer; ++il) {
  9644. struct ggml_tensor * inpSA = inpL;
  9645. // norm
  9646. cur = llm_build_norm(ctx0, inpL, hparams,
  9647. model.layers[il].attn_norm, NULL,
  9648. LLM_NORM_RMS, cb, il);
  9649. cb(cur, "attn_norm", il);
  9650. // self_attention
  9651. {
  9652. // compute Q and K and RoPE them
  9653. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9654. cb(Qcur, "Qcur", il);
  9655. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9656. cb(Qcur, "Qcur", il);
  9657. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9658. cb(Kcur, "Kcur", il);
  9659. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9660. cb(Kcur, "Kcur", il);
  9661. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9662. cb(Vcur, "Vcur", il);
  9663. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9664. cb(Vcur, "Vcur", il);
  9665. Qcur = ggml_rope_ext(
  9666. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9667. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9668. ext_factor, attn_factor, beta_fast, beta_slow
  9669. );
  9670. cb(Qcur, "Qcur", il);
  9671. Kcur = ggml_rope_ext(
  9672. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9673. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9674. ext_factor, attn_factor, beta_fast, beta_slow
  9675. );
  9676. cb(Kcur, "Kcur", il);
  9677. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9678. model.layers[il].wo, model.layers[il].bo,
  9679. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9680. }
  9681. if (il == n_layer - 1) {
  9682. // skip computing output for unused tokens
  9683. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9684. n_tokens = n_outputs;
  9685. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9686. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9687. }
  9688. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9689. cb(ffn_inp, "ffn_inp", il);
  9690. // MoE branch
  9691. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9692. model.layers[il].ffn_norm, NULL,
  9693. LLM_NORM_RMS, cb, il);
  9694. cb(cur, "ffn_norm", il);
  9695. ggml_tensor * moe_out =
  9696. llm_build_moe_ffn(ctx0, lctx, cur,
  9697. model.layers[il].ffn_gate_inp,
  9698. model.layers[il].ffn_up_exps,
  9699. model.layers[il].ffn_gate_exps,
  9700. model.layers[il].ffn_down_exps,
  9701. n_expert, n_expert_used,
  9702. LLM_FFN_SILU, false,
  9703. false, 0.0,
  9704. cb, il);
  9705. cb(cur, "ffn_moe_out", il);
  9706. // FFN shared expert
  9707. {
  9708. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  9709. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  9710. // sigmoid
  9711. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  9712. cb(cur_gate, "ffn_shexp_gate", il);
  9713. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  9714. model.layers[il].ffn_up_shexp, NULL, NULL,
  9715. model.layers[il].ffn_gate_shexp, NULL, NULL,
  9716. model.layers[il].ffn_down_shexp, NULL, NULL,
  9717. NULL,
  9718. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9719. cb(cur_ffn, "ffn_shexp", il);
  9720. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  9721. cb(ffn_shexp_out, "ffn_shexp_out", il);
  9722. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  9723. cb(moe_out, "ffn_out", il);
  9724. cur = moe_out;
  9725. }
  9726. cur = ggml_add(ctx0, cur, ffn_inp);
  9727. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9728. cb(cur, "l_out", il);
  9729. // input for next layer
  9730. inpL = cur;
  9731. }
  9732. cur = inpL;
  9733. cur = llm_build_norm(ctx0, cur, hparams,
  9734. model.output_norm, NULL,
  9735. LLM_NORM_RMS, cb, -1);
  9736. cb(cur, "result_norm", -1);
  9737. // lm_head
  9738. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9739. cb(cur, "result_output", -1);
  9740. ggml_build_forward_expand(gf, cur);
  9741. return gf;
  9742. }
  9743. struct ggml_cgraph * build_phi2() {
  9744. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9745. const int64_t n_embd_head = hparams.n_embd_head_v;
  9746. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9747. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9748. struct ggml_tensor * cur;
  9749. struct ggml_tensor * attn_norm_output;
  9750. struct ggml_tensor * ffn_output;
  9751. struct ggml_tensor * inpL;
  9752. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9753. // inp_pos - contains the positions
  9754. struct ggml_tensor * inp_pos = build_inp_pos();
  9755. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9756. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9757. for (int il = 0; il < n_layer; ++il) {
  9758. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9759. model.layers[il].attn_norm,
  9760. model.layers[il].attn_norm_b,
  9761. LLM_NORM, cb, il);
  9762. cb(attn_norm_output, "attn_norm", il);
  9763. // self-attention
  9764. {
  9765. struct ggml_tensor * Qcur = nullptr;
  9766. struct ggml_tensor * Kcur = nullptr;
  9767. struct ggml_tensor * Vcur = nullptr;
  9768. if (model.layers[il].wqkv) {
  9769. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9770. cb(cur, "wqkv", il);
  9771. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9772. cb(cur, "bqkv", il);
  9773. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9774. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9775. 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)));
  9776. } else {
  9777. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9778. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9779. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9780. }
  9781. cb(Qcur, "Qcur", il);
  9782. cb(Kcur, "Kcur", il);
  9783. cb(Vcur, "Vcur", il);
  9784. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9785. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9786. Qcur = ggml_rope_ext(
  9787. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9788. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9789. );
  9790. cb(Qcur, "Qcur", il);
  9791. // with phi2, we scale the Q to avoid precision issues
  9792. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  9793. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  9794. cb(Qcur, "Qcur", il);
  9795. Kcur = ggml_rope_ext(
  9796. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9797. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9798. );
  9799. cb(Kcur, "Kcur", il);
  9800. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9801. model.layers[il].wo, model.layers[il].bo,
  9802. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9803. }
  9804. if (il == n_layer - 1) {
  9805. // skip computing output for unused tokens
  9806. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9807. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9808. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9809. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  9810. }
  9811. // FF
  9812. {
  9813. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  9814. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9815. NULL, NULL, NULL,
  9816. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9817. NULL,
  9818. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9819. cb(ffn_output, "ffn_out", il);
  9820. }
  9821. cur = ggml_add(ctx0, cur, ffn_output);
  9822. cur = ggml_add(ctx0, cur, inpL);
  9823. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9824. cb(cur, "l_out", il);
  9825. // input for next layer
  9826. inpL = cur;
  9827. }
  9828. cur = llm_build_norm(ctx0, inpL, hparams,
  9829. model.output_norm,
  9830. model.output_norm_b,
  9831. LLM_NORM, cb, -1);
  9832. cb(cur, "result_norm", -1);
  9833. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9834. cb(cur, "result_output_no_bias", -1);
  9835. cur = ggml_add(ctx0, cur, model.output_b);
  9836. cb(cur, "result_output", -1);
  9837. ggml_build_forward_expand(gf, cur);
  9838. return gf;
  9839. }
  9840. struct ggml_cgraph * build_phi3() {
  9841. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9842. const int64_t n_embd_head = hparams.n_embd_head_v;
  9843. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9844. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9845. struct ggml_tensor * cur;
  9846. struct ggml_tensor * inpL;
  9847. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9848. // inp_pos - contains the positions
  9849. struct ggml_tensor * inp_pos = build_inp_pos();
  9850. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9851. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  9852. for (int il = 0; il < n_layer; ++il) {
  9853. auto residual = inpL;
  9854. // self-attention
  9855. {
  9856. // rope freq factors for 128k context
  9857. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9858. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9859. model.layers[il].attn_norm,
  9860. NULL,
  9861. LLM_NORM_RMS, cb, il);
  9862. cb(attn_norm_output, "attn_norm", il);
  9863. struct ggml_tensor * Qcur = nullptr;
  9864. struct ggml_tensor * Kcur = nullptr;
  9865. struct ggml_tensor * Vcur = nullptr;
  9866. if (model.layers[il].wqkv) {
  9867. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9868. cb(cur, "wqkv", il);
  9869. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  9870. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  9871. 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)));
  9872. }
  9873. else {
  9874. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9875. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9876. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9877. }
  9878. cb(Qcur, "Qcur", il);
  9879. cb(Kcur, "Kcur", il);
  9880. cb(Vcur, "Vcur", il);
  9881. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9882. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9883. Qcur = ggml_rope_ext(
  9884. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9885. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9886. );
  9887. cb(Qcur, "Qcur", il);
  9888. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  9889. cb(Qcur, "Qcur", il);
  9890. Kcur = ggml_rope_ext(
  9891. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9892. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9893. );
  9894. cb(Kcur, "Kcur", il);
  9895. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9896. model.layers[il].wo, model.layers[il].bo,
  9897. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9898. }
  9899. if (il == n_layer - 1) {
  9900. // skip computing output for unused tokens
  9901. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  9902. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9903. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  9904. }
  9905. cur = ggml_add(ctx0, cur, residual);
  9906. residual = cur;
  9907. cur = llm_build_norm(ctx0, cur, hparams,
  9908. model.layers[il].ffn_norm, NULL,
  9909. LLM_NORM_RMS, cb, il);
  9910. cb(cur, "ffn_norm", il);
  9911. // FF
  9912. // special-case: the up and gate tensors are merged into a single tensor
  9913. // TOOD: support into llm_build_ffn
  9914. {
  9915. cur = llm_build_ffn(ctx0, lctx, cur,
  9916. model.layers[il].ffn_up, NULL, NULL,
  9917. NULL, NULL, NULL,
  9918. model.layers[il].ffn_down, NULL, NULL,
  9919. NULL,
  9920. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  9921. cb(cur, "ffn_out", il);
  9922. }
  9923. cur = ggml_add(ctx0, residual, cur);
  9924. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9925. cb(cur, "l_out", il);
  9926. // input for next layer
  9927. inpL = cur;
  9928. }
  9929. cur = llm_build_norm(ctx0, inpL, hparams,
  9930. model.output_norm,
  9931. NULL,
  9932. LLM_NORM_RMS, cb, -1);
  9933. cb(cur, "result_norm", -1);
  9934. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9935. cb(cur, "result_output", -1);
  9936. ggml_build_forward_expand(gf, cur);
  9937. return gf;
  9938. }
  9939. struct ggml_cgraph * build_plamo() {
  9940. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  9941. const int64_t n_embd_head = hparams.n_embd_head_v;
  9942. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9943. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9944. struct ggml_tensor * cur;
  9945. struct ggml_tensor * inpL;
  9946. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9947. // inp_pos - contains the positions
  9948. struct ggml_tensor * inp_pos = build_inp_pos();
  9949. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9950. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9951. for (int il = 0; il < n_layer; ++il) {
  9952. // norm
  9953. cur = llm_build_norm(ctx0, inpL, hparams,
  9954. model.layers[il].attn_norm, NULL,
  9955. LLM_NORM_RMS, cb, il);
  9956. cb(cur, "attn_norm", il);
  9957. struct ggml_tensor * attention_norm = cur;
  9958. // self-attention
  9959. {
  9960. // compute Q and K and RoPE them
  9961. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9962. cb(Qcur, "Qcur", il);
  9963. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9964. cb(Kcur, "Kcur", il);
  9965. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9966. cb(Vcur, "Vcur", il);
  9967. Qcur = ggml_rope_ext(
  9968. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  9969. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9970. ext_factor, attn_factor, beta_fast, beta_slow);
  9971. cb(Qcur, "Qcur", il);
  9972. Kcur = ggml_rope_ext(
  9973. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  9974. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9975. ext_factor, attn_factor, beta_fast, beta_slow);
  9976. cb(Kcur, "Kcur", il);
  9977. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9978. model.layers[il].wo, NULL,
  9979. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9980. }
  9981. struct ggml_tensor * sa_out = cur;
  9982. cur = attention_norm;
  9983. if (il == n_layer - 1) {
  9984. // skip computing output for unused tokens
  9985. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9986. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9987. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  9988. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9989. }
  9990. // feed-forward network
  9991. {
  9992. cur = llm_build_ffn(ctx0, lctx, cur,
  9993. model.layers[il].ffn_up, NULL, NULL,
  9994. model.layers[il].ffn_gate, NULL, NULL,
  9995. model.layers[il].ffn_down, NULL, NULL,
  9996. NULL,
  9997. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9998. cb(cur, "ffn_out", il);
  9999. }
  10000. cur = ggml_add(ctx0, cur, sa_out);
  10001. cur = ggml_add(ctx0, cur, inpL);
  10002. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10003. cb(cur, "l_out", il);
  10004. // input for next layer
  10005. inpL = cur;
  10006. }
  10007. cur = inpL;
  10008. cur = llm_build_norm(ctx0, cur, hparams,
  10009. model.output_norm, NULL,
  10010. LLM_NORM_RMS, cb, -1);
  10011. cb(cur, "result_norm", -1);
  10012. // lm_head
  10013. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10014. cb(cur, "result_output", -1);
  10015. ggml_build_forward_expand(gf, cur);
  10016. return gf;
  10017. }
  10018. struct ggml_cgraph * build_gpt2() {
  10019. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10020. const int64_t n_embd_head = hparams.n_embd_head_v;
  10021. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10022. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10023. struct ggml_tensor * cur;
  10024. struct ggml_tensor * pos;
  10025. struct ggml_tensor * inpL;
  10026. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10027. // inp_pos - contains the positions
  10028. struct ggml_tensor * inp_pos = build_inp_pos();
  10029. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10030. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10031. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  10032. cb(pos, "pos_embd", -1);
  10033. inpL = ggml_add(ctx0, inpL, pos);
  10034. cb(inpL, "inpL", -1);
  10035. for (int il = 0; il < n_layer; ++il) {
  10036. cur = llm_build_norm(ctx0, inpL, hparams,
  10037. model.layers[il].attn_norm,
  10038. model.layers[il].attn_norm_b,
  10039. LLM_NORM, cb, il);
  10040. cb(cur, "attn_norm", il);
  10041. // self-attention
  10042. {
  10043. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10044. cb(cur, "wqkv", il);
  10045. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10046. cb(cur, "bqkv", il);
  10047. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10048. 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)));
  10049. 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)));
  10050. cb(Qcur, "Qcur", il);
  10051. cb(Kcur, "Kcur", il);
  10052. cb(Vcur, "Vcur", il);
  10053. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10054. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10055. model.layers[il].wo, model.layers[il].bo,
  10056. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10057. }
  10058. if (il == n_layer - 1) {
  10059. // skip computing output for unused tokens
  10060. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10061. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10062. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10063. }
  10064. // add the input
  10065. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10066. cb(ffn_inp, "ffn_inp", il);
  10067. // FF
  10068. {
  10069. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10070. model.layers[il].ffn_norm,
  10071. model.layers[il].ffn_norm_b,
  10072. LLM_NORM, cb, il);
  10073. cb(cur, "ffn_norm", il);
  10074. cur = llm_build_ffn(ctx0, lctx, cur,
  10075. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10076. NULL, NULL, NULL,
  10077. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10078. NULL,
  10079. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10080. cb(cur, "ffn_out", il);
  10081. }
  10082. cur = ggml_add(ctx0, cur, ffn_inp);
  10083. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10084. cb(cur, "l_out", il);
  10085. // input for next layer
  10086. inpL = cur;
  10087. }
  10088. cur = llm_build_norm(ctx0, inpL, hparams,
  10089. model.output_norm,
  10090. model.output_norm_b,
  10091. LLM_NORM, cb, -1);
  10092. cb(cur, "result_norm", -1);
  10093. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10094. cb(cur, "result_output", -1);
  10095. ggml_build_forward_expand(gf, cur);
  10096. return gf;
  10097. }
  10098. struct ggml_cgraph * build_codeshell() {
  10099. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10100. const int64_t n_embd_head = hparams.n_embd_head_v;
  10101. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10102. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10103. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10104. struct ggml_tensor * cur;
  10105. struct ggml_tensor * inpL;
  10106. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10107. // inp_pos - contains the positions
  10108. struct ggml_tensor * inp_pos = build_inp_pos();
  10109. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10110. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10111. for (int il = 0; il < n_layer; ++il) {
  10112. cur = llm_build_norm(ctx0, inpL, hparams,
  10113. model.layers[il].attn_norm,
  10114. model.layers[il].attn_norm_b,
  10115. LLM_NORM, cb, il);
  10116. cb(cur, "attn_norm", il);
  10117. // self-attention
  10118. {
  10119. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10120. cb(cur, "wqkv", il);
  10121. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10122. cb(cur, "bqkv", il);
  10123. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10124. 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)));
  10125. 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)));
  10126. cb(tmpq, "tmpq", il);
  10127. cb(tmpk, "tmpk", il);
  10128. cb(Vcur, "Vcur", il);
  10129. struct ggml_tensor * Qcur = ggml_rope_ext(
  10130. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10131. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10132. ext_factor, attn_factor, beta_fast, beta_slow
  10133. );
  10134. cb(Qcur, "Qcur", il);
  10135. struct ggml_tensor * Kcur = ggml_rope_ext(
  10136. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10137. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10138. ext_factor, attn_factor, beta_fast, beta_slow
  10139. );
  10140. cb(Kcur, "Kcur", il);
  10141. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10142. model.layers[il].wo, model.layers[il].bo,
  10143. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10144. }
  10145. if (il == n_layer - 1) {
  10146. // skip computing output for unused tokens
  10147. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10148. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10149. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10150. }
  10151. // add the input
  10152. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10153. cb(ffn_inp, "ffn_inp", il);
  10154. // FF
  10155. {
  10156. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10157. model.layers[il].ffn_norm,
  10158. model.layers[il].ffn_norm_b,
  10159. LLM_NORM, cb, il);
  10160. cb(cur, "ffn_norm", il);
  10161. cur = llm_build_ffn(ctx0, lctx, cur,
  10162. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10163. NULL, NULL, NULL,
  10164. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10165. NULL,
  10166. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10167. cb(cur, "ffn_out", il);
  10168. }
  10169. cur = ggml_add(ctx0, cur, ffn_inp);
  10170. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10171. cb(cur, "l_out", il);
  10172. // input for next layer
  10173. inpL = cur;
  10174. }
  10175. cur = llm_build_norm(ctx0, inpL, hparams,
  10176. model.output_norm,
  10177. model.output_norm_b,
  10178. LLM_NORM, cb, -1);
  10179. cb(cur, "result_norm", -1);
  10180. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10181. cb(cur, "result_output", -1);
  10182. ggml_build_forward_expand(gf, cur);
  10183. return gf;
  10184. }
  10185. struct ggml_cgraph * build_orion() {
  10186. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10187. const int64_t n_embd_head = hparams.n_embd_head_v;
  10188. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10189. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10190. struct ggml_tensor * cur;
  10191. struct ggml_tensor * inpL;
  10192. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10193. // inp_pos - contains the positions
  10194. struct ggml_tensor * inp_pos = build_inp_pos();
  10195. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10196. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10197. for (int il = 0; il < n_layer; ++il) {
  10198. struct ggml_tensor * inpSA = inpL;
  10199. // norm
  10200. cur = llm_build_norm(ctx0, inpL, hparams,
  10201. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  10202. LLM_NORM, cb, il);
  10203. cb(cur, "attn_norm", il);
  10204. // self-attention
  10205. {
  10206. // compute Q and K and RoPE them
  10207. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10208. cb(Qcur, "Qcur", il);
  10209. // if (model.layers[il].bq) {
  10210. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10211. // cb(Qcur, "Qcur", il);
  10212. // }
  10213. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10214. cb(Kcur, "Kcur", il);
  10215. // if (model.layers[il].bk) {
  10216. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10217. // cb(Kcur, "Kcur", il);
  10218. // }
  10219. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10220. cb(Vcur, "Vcur", il);
  10221. // if (model.layers[il].bv) {
  10222. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10223. // cb(Vcur, "Vcur", il);
  10224. // }
  10225. Qcur = ggml_rope_ext(
  10226. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10227. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10228. ext_factor, attn_factor, beta_fast, beta_slow
  10229. );
  10230. cb(Qcur, "Qcur", il);
  10231. Kcur = ggml_rope_ext(
  10232. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10233. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10234. ext_factor, attn_factor, beta_fast, beta_slow
  10235. );
  10236. cb(Kcur, "Kcur", il);
  10237. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10238. model.layers[il].wo, NULL,
  10239. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10240. }
  10241. if (il == n_layer - 1) {
  10242. // skip computing output for unused tokens
  10243. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10244. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10245. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10246. }
  10247. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10248. cb(ffn_inp, "ffn_inp", il);
  10249. // feed-forward network
  10250. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10251. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  10252. LLM_NORM, cb, il);
  10253. cb(cur, "ffn_norm", il);
  10254. cur = llm_build_ffn(ctx0, lctx, cur,
  10255. model.layers[il].ffn_up, NULL, NULL,
  10256. model.layers[il].ffn_gate, NULL, NULL,
  10257. model.layers[il].ffn_down, NULL, NULL,
  10258. NULL,
  10259. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10260. cb(cur, "ffn_out", il);
  10261. cur = ggml_add(ctx0, cur, ffn_inp);
  10262. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10263. cb(cur, "l_out", il);
  10264. // input for next layer
  10265. inpL = cur;
  10266. }
  10267. cur = inpL;
  10268. cur = llm_build_norm(ctx0, cur, hparams,
  10269. model.output_norm, model.output_norm_b,
  10270. LLM_NORM, cb, -1);
  10271. cb(cur, "result_norm", -1);
  10272. // lm_head
  10273. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10274. cb(cur, "result_output", -1);
  10275. ggml_build_forward_expand(gf, cur);
  10276. return gf;
  10277. }
  10278. struct ggml_cgraph * build_internlm2() {
  10279. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10280. const int64_t n_embd_head = hparams.n_embd_head_v;
  10281. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10282. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10283. struct ggml_tensor * cur;
  10284. struct ggml_tensor * inpL;
  10285. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10286. // inp_pos - contains the positions
  10287. struct ggml_tensor * inp_pos = build_inp_pos();
  10288. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10289. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10290. for (int il = 0; il < n_layer; ++il) {
  10291. struct ggml_tensor * inpSA = inpL;
  10292. // norm
  10293. cur = llm_build_norm(ctx0, inpL, hparams,
  10294. model.layers[il].attn_norm, NULL,
  10295. LLM_NORM_RMS, cb, il);
  10296. cb(cur, "attn_norm", il);
  10297. // self-attention
  10298. {
  10299. // compute Q and K and RoPE them
  10300. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10301. cb(Qcur, "Qcur", il);
  10302. if (model.layers[il].bq) {
  10303. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10304. cb(Qcur, "Qcur", il);
  10305. }
  10306. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10307. cb(Kcur, "Kcur", il);
  10308. if (model.layers[il].bk) {
  10309. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10310. cb(Kcur, "Kcur", il);
  10311. }
  10312. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10313. cb(Vcur, "Vcur", il);
  10314. if (model.layers[il].bv) {
  10315. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10316. cb(Vcur, "Vcur", il);
  10317. }
  10318. Qcur = ggml_rope_ext(
  10319. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10320. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10321. ext_factor, attn_factor, beta_fast, beta_slow
  10322. );
  10323. cb(Qcur, "Qcur", il);
  10324. Kcur = ggml_rope_ext(
  10325. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10326. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10327. ext_factor, attn_factor, beta_fast, beta_slow
  10328. );
  10329. cb(Kcur, "Kcur", il);
  10330. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10331. model.layers[il].wo, model.layers[il].bo,
  10332. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10333. }
  10334. if (il == n_layer - 1) {
  10335. // skip computing output for unused tokens
  10336. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10337. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10338. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10339. }
  10340. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10341. cb(ffn_inp, "ffn_inp", il);
  10342. // feed-forward network
  10343. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10344. model.layers[il].ffn_norm, NULL,
  10345. LLM_NORM_RMS, cb, il);
  10346. cb(cur, "ffn_norm", il);
  10347. cur = llm_build_ffn(ctx0, lctx, cur,
  10348. model.layers[il].ffn_up, NULL, NULL,
  10349. model.layers[il].ffn_gate, NULL, NULL,
  10350. model.layers[il].ffn_down, NULL, NULL,
  10351. NULL,
  10352. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10353. cb(cur, "ffn_out", il);
  10354. cur = ggml_add(ctx0, cur, ffn_inp);
  10355. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10356. cb(cur, "l_out", il);
  10357. // input for next layer
  10358. inpL = cur;
  10359. }
  10360. cur = inpL;
  10361. cur = llm_build_norm(ctx0, cur, hparams,
  10362. model.output_norm, NULL,
  10363. LLM_NORM_RMS, cb, -1);
  10364. cb(cur, "result_norm", -1);
  10365. // lm_head
  10366. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10367. cb(cur, "result_output", -1);
  10368. ggml_build_forward_expand(gf, cur);
  10369. return gf;
  10370. }
  10371. // ref: https://arxiv.org/abs/2203.03466
  10372. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  10373. // based on the original build_llama() function
  10374. struct ggml_cgraph * build_minicpm() {
  10375. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10376. const int64_t n_embd_head = hparams.n_embd_head_v;
  10377. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10378. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10379. const int64_t n_embd = hparams.n_embd;
  10380. //TODO: if the model varies, these parameters need to be read from the model
  10381. const int64_t n_embd_base = 256;
  10382. const float scale_embd = 12.0f;
  10383. const float scale_depth = 1.4f;
  10384. struct ggml_tensor * cur;
  10385. struct ggml_tensor * inpL;
  10386. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10387. // scale the input embeddings
  10388. inpL = ggml_scale(ctx0, inpL, scale_embd);
  10389. cb(inpL, "inp_scaled", -1);
  10390. // inp_pos - contains the positions
  10391. struct ggml_tensor * inp_pos = build_inp_pos();
  10392. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10393. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10394. for (int il = 0; il < n_layer; ++il) {
  10395. struct ggml_tensor * inpSA = inpL;
  10396. // norm
  10397. cur = llm_build_norm(ctx0, inpL, hparams,
  10398. model.layers[il].attn_norm, NULL,
  10399. LLM_NORM_RMS, cb, il);
  10400. cb(cur, "attn_norm", il);
  10401. // self-attention
  10402. {
  10403. // compute Q and K and RoPE them
  10404. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10405. cb(Qcur, "Qcur", il);
  10406. if (model.layers[il].bq) {
  10407. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10408. cb(Qcur, "Qcur", il);
  10409. }
  10410. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10411. cb(Kcur, "Kcur", il);
  10412. if (model.layers[il].bk) {
  10413. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10414. cb(Kcur, "Kcur", il);
  10415. }
  10416. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10417. cb(Vcur, "Vcur", il);
  10418. if (model.layers[il].bv) {
  10419. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10420. cb(Vcur, "Vcur", il);
  10421. }
  10422. Qcur = ggml_rope_ext(
  10423. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10424. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10425. ext_factor, attn_factor, beta_fast, beta_slow
  10426. );
  10427. cb(Qcur, "Qcur", il);
  10428. Kcur = ggml_rope_ext(
  10429. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10430. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10431. ext_factor, attn_factor, beta_fast, beta_slow
  10432. );
  10433. cb(Kcur, "Kcur", il);
  10434. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10435. model.layers[il].wo, model.layers[il].bo,
  10436. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10437. }
  10438. if (il == n_layer - 1) {
  10439. // skip computing output for unused tokens
  10440. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10441. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10442. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10443. }
  10444. // scale_res - scale the hidden states for residual connection
  10445. const float scale_res = scale_depth/sqrtf(float(n_layer));
  10446. cur = ggml_scale(ctx0, cur, scale_res);
  10447. cb(cur, "hidden_scaled", -1);
  10448. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10449. cb(ffn_inp, "ffn_inp", il);
  10450. // feed-forward network
  10451. {
  10452. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10453. model.layers[il].ffn_norm, NULL,
  10454. LLM_NORM_RMS, cb, il);
  10455. cb(cur, "ffn_norm", il);
  10456. cur = llm_build_ffn(ctx0, lctx, cur,
  10457. model.layers[il].ffn_up, NULL, NULL,
  10458. model.layers[il].ffn_gate, NULL, NULL,
  10459. model.layers[il].ffn_down, NULL, NULL,
  10460. NULL,
  10461. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10462. cb(cur, "ffn_out", il);
  10463. }
  10464. // scale the hidden states for residual connection
  10465. cur = ggml_scale(ctx0, cur, scale_res);
  10466. cb(cur, "hidden_scaled_ffn", -1);
  10467. cur = ggml_add(ctx0, cur, ffn_inp);
  10468. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10469. cb(cur, "l_out", il);
  10470. // input for next layer
  10471. inpL = cur;
  10472. }
  10473. cur = inpL;
  10474. cur = llm_build_norm(ctx0, cur, hparams,
  10475. model.output_norm, NULL,
  10476. LLM_NORM_RMS, cb, -1);
  10477. cb(cur, "result_norm", -1);
  10478. // lm_head scaling
  10479. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  10480. cur = ggml_scale(ctx0, cur, scale_lmhead);
  10481. cb(cur, "lmhead_scaling", -1);
  10482. // lm_head
  10483. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10484. cb(cur, "result_output", -1);
  10485. ggml_build_forward_expand(gf, cur);
  10486. return gf;
  10487. }
  10488. struct ggml_cgraph * build_gemma() {
  10489. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10490. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  10491. struct ggml_tensor * cur;
  10492. struct ggml_tensor * inpL;
  10493. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10494. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  10495. cb(inpL, "inp_scaled", -1);
  10496. // inp_pos - contains the positions
  10497. struct ggml_tensor * inp_pos = build_inp_pos();
  10498. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10499. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10500. for (int il = 0; il < n_layer; ++il) {
  10501. // norm
  10502. cur = llm_build_norm(ctx0, inpL, hparams,
  10503. model.layers[il].attn_norm, NULL,
  10504. LLM_NORM_RMS, cb, il);
  10505. cb(cur, "attn_norm", il);
  10506. // self-attention
  10507. {
  10508. // compute Q and K and RoPE them
  10509. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10510. cb(Qcur, "Qcur", il);
  10511. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10512. cb(Kcur, "Kcur", il);
  10513. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10514. cb(Vcur, "Vcur", il);
  10515. Qcur = ggml_rope_ext(
  10516. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  10517. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10518. ext_factor, attn_factor, beta_fast, beta_slow);
  10519. cb(Qcur, "Qcur", il);
  10520. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  10521. cb(Qcur, "Qcur_scaled", il);
  10522. Kcur = ggml_rope_ext(
  10523. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  10524. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10525. ext_factor, attn_factor, beta_fast, beta_slow);
  10526. cb(Kcur, "Kcur", il);
  10527. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10528. model.layers[il].wo, NULL,
  10529. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10530. }
  10531. if (il == n_layer - 1) {
  10532. // skip computing output for unused tokens
  10533. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10534. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10535. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10536. }
  10537. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  10538. cb(sa_out, "sa_out", il);
  10539. cur = llm_build_norm(ctx0, sa_out, hparams,
  10540. model.layers[il].ffn_norm, NULL,
  10541. LLM_NORM_RMS, cb, il);
  10542. cb(cur, "ffn_norm", il);
  10543. // feed-forward network
  10544. {
  10545. cur = llm_build_ffn(ctx0, lctx, cur,
  10546. model.layers[il].ffn_up, NULL, NULL,
  10547. model.layers[il].ffn_gate, NULL, NULL,
  10548. model.layers[il].ffn_down, NULL, NULL,
  10549. NULL,
  10550. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10551. cb(cur, "ffn_out", il);
  10552. }
  10553. cur = ggml_add(ctx0, cur, sa_out);
  10554. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10555. cb(cur, "l_out", il);
  10556. // input for next layer
  10557. inpL = cur;
  10558. }
  10559. cur = inpL;
  10560. cur = llm_build_norm(ctx0, cur, hparams,
  10561. model.output_norm, NULL,
  10562. LLM_NORM_RMS, cb, -1);
  10563. cb(cur, "result_norm", -1);
  10564. // lm_head
  10565. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10566. cb(cur, "result_output", -1);
  10567. ggml_build_forward_expand(gf, cur);
  10568. return gf;
  10569. }
  10570. struct ggml_cgraph * build_gemma2() {
  10571. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10572. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  10573. struct ggml_tensor * cur;
  10574. struct ggml_tensor * inpL;
  10575. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10576. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  10577. cb(inpL, "inp_scaled", -1);
  10578. // inp_pos - contains the positions
  10579. struct ggml_tensor * inp_pos = build_inp_pos();
  10580. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10581. // gemma 2 requires different mask for layers using sliding window (SWA)
  10582. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  10583. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  10584. for (int il = 0; il < n_layer; ++il) {
  10585. // (il % 2) layers use SWA
  10586. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  10587. // norm
  10588. cur = llm_build_norm(ctx0, inpL, hparams,
  10589. model.layers[il].attn_norm, NULL,
  10590. LLM_NORM_RMS, cb, il);
  10591. cb(cur, "attn_norm", il);
  10592. // self-attention
  10593. {
  10594. // compute Q and K and RoPE them
  10595. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10596. cb(Qcur, "Qcur", il);
  10597. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10598. cb(Kcur, "Kcur", il);
  10599. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10600. cb(Vcur, "Vcur", il);
  10601. Qcur = ggml_rope_ext(
  10602. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  10603. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10604. ext_factor, attn_factor, beta_fast, beta_slow);
  10605. cb(Qcur, "Qcur", il);
  10606. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  10607. switch (model.type) {
  10608. case e_model::MODEL_2B:
  10609. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  10610. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  10611. default: GGML_ABORT("fatal error");
  10612. };
  10613. cb(Qcur, "Qcur_scaled", il);
  10614. Kcur = ggml_rope_ext(
  10615. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  10616. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10617. ext_factor, attn_factor, beta_fast, beta_slow);
  10618. cb(Kcur, "Kcur", il);
  10619. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10620. model.layers[il].wo, NULL,
  10621. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  10622. }
  10623. cur = llm_build_norm(ctx0, cur, hparams,
  10624. model.layers[il].attn_post_norm, NULL,
  10625. LLM_NORM_RMS, cb, il);
  10626. cb(cur, "attn_post_norm", il);
  10627. if (il == n_layer - 1) {
  10628. // skip computing output for unused tokens
  10629. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10630. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10631. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10632. }
  10633. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  10634. cb(sa_out, "sa_out", il);
  10635. cur = llm_build_norm(ctx0, sa_out, hparams,
  10636. model.layers[il].ffn_norm, NULL,
  10637. LLM_NORM_RMS, cb, il);
  10638. cb(cur, "ffn_norm", il);
  10639. // feed-forward network
  10640. {
  10641. cur = llm_build_ffn(ctx0, lctx, cur,
  10642. model.layers[il].ffn_up, NULL, NULL,
  10643. model.layers[il].ffn_gate, NULL, NULL,
  10644. model.layers[il].ffn_down, NULL, NULL,
  10645. NULL,
  10646. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  10647. cb(cur, "ffn_out", il);
  10648. }
  10649. cur = llm_build_norm(ctx0, cur, hparams,
  10650. model.layers[il].ffn_post_norm, NULL,
  10651. LLM_NORM_RMS, cb, -1);
  10652. cb(cur, "ffn_post_norm", -1);
  10653. cur = ggml_add(ctx0, cur, sa_out);
  10654. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10655. cb(cur, "l_out", il);
  10656. // input for next layer
  10657. inpL = cur;
  10658. }
  10659. cur = inpL;
  10660. cur = llm_build_norm(ctx0, cur, hparams,
  10661. model.output_norm, NULL,
  10662. LLM_NORM_RMS, cb, -1);
  10663. cb(cur, "result_norm", -1);
  10664. // lm_head
  10665. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10666. // final logit soft-capping
  10667. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  10668. cur = ggml_tanh(ctx0, cur);
  10669. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  10670. cb(cur, "result_output", -1);
  10671. ggml_build_forward_expand(gf, cur);
  10672. return gf;
  10673. }
  10674. struct ggml_cgraph * build_starcoder2() {
  10675. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10676. const int64_t n_embd_head = hparams.n_embd_head_v;
  10677. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10678. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10679. struct ggml_tensor * cur;
  10680. struct ggml_tensor * inpL;
  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, model.layers[il].attn_norm_b,
  10691. LLM_NORM, cb, il);
  10692. cb(cur, "attn_norm", il);
  10693. // self-attention
  10694. {
  10695. // compute Q and K and RoPE them
  10696. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10697. cb(Qcur, "Qcur", il);
  10698. if (model.layers[il].bq) {
  10699. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10700. cb(Qcur, "Qcur", il);
  10701. }
  10702. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10703. cb(Kcur, "Kcur", il);
  10704. if (model.layers[il].bk) {
  10705. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10706. cb(Kcur, "Kcur", il);
  10707. }
  10708. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10709. cb(Vcur, "Vcur", il);
  10710. if (model.layers[il].bv) {
  10711. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10712. cb(Vcur, "Vcur", il);
  10713. }
  10714. Qcur = ggml_rope_ext(
  10715. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10716. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10717. ext_factor, attn_factor, beta_fast, beta_slow
  10718. );
  10719. cb(Qcur, "Qcur", il);
  10720. Kcur = ggml_rope_ext(
  10721. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10722. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10723. ext_factor, attn_factor, beta_fast, beta_slow
  10724. );
  10725. cb(Kcur, "Kcur", il);
  10726. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10727. model.layers[il].wo, model.layers[il].bo,
  10728. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10729. }
  10730. if (il == n_layer - 1) {
  10731. // skip computing output for unused tokens
  10732. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10733. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10734. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10735. }
  10736. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10737. cb(ffn_inp, "ffn_inp", il);
  10738. // feed-forward network
  10739. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10740. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  10741. LLM_NORM, cb, il);
  10742. cb(cur, "ffn_norm", il);
  10743. cur = llm_build_ffn(ctx0, lctx, cur,
  10744. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10745. NULL, NULL, NULL,
  10746. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10747. NULL,
  10748. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10749. cb(cur, "ffn_out", il);
  10750. cur = ggml_add(ctx0, cur, ffn_inp);
  10751. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10752. cb(cur, "l_out", il);
  10753. // input for next layer
  10754. inpL = cur;
  10755. }
  10756. cur = inpL;
  10757. cur = llm_build_norm(ctx0, cur, hparams,
  10758. model.output_norm, model.output_norm_b,
  10759. LLM_NORM, cb, -1);
  10760. cb(cur, "result_norm", -1);
  10761. // lm_head
  10762. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10763. cb(cur, "result_output", -1);
  10764. ggml_build_forward_expand(gf, cur);
  10765. return gf;
  10766. }
  10767. struct ggml_cgraph * build_mamba() {
  10768. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10769. struct ggml_tensor * cur;
  10770. struct ggml_tensor * inpL;
  10771. // {n_embd, n_tokens}
  10772. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10773. struct ggml_tensor * state_copy = build_inp_s_copy();
  10774. struct ggml_tensor * state_mask = build_inp_s_mask();
  10775. for (int il = 0; il < n_layer; ++il) {
  10776. // norm
  10777. cur = llm_build_norm(ctx0, inpL, hparams,
  10778. model.layers[il].attn_norm, NULL,
  10779. LLM_NORM_RMS, cb, il);
  10780. cb(cur, "attn_norm", il);
  10781. cur = llm_build_mamba(ctx0, lctx, batch, gf, cur,
  10782. state_copy, state_mask,
  10783. kv_head, n_kv, cb, il);
  10784. if (il == n_layer - 1) {
  10785. // skip computing output for unused tokens
  10786. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10787. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10788. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10789. }
  10790. // residual
  10791. cur = ggml_add(ctx0, cur, inpL);
  10792. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10793. cb(cur, "l_out", il);
  10794. // input for next layer
  10795. inpL = cur;
  10796. }
  10797. // final rmsnorm
  10798. cur = llm_build_norm(ctx0, inpL, hparams,
  10799. model.output_norm, NULL,
  10800. LLM_NORM_RMS, cb, -1);
  10801. cb(cur, "result_norm", -1);
  10802. // lm_head
  10803. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10804. cb(cur, "result_output", -1);
  10805. ggml_build_forward_expand(gf, cur);
  10806. return gf;
  10807. }
  10808. struct ggml_cgraph * build_command_r() {
  10809. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10810. const int64_t n_embd_head = hparams.n_embd_head_v;
  10811. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10812. const float f_logit_scale = hparams.f_logit_scale;
  10813. struct ggml_tensor * cur;
  10814. struct ggml_tensor * inpL;
  10815. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10816. // inp_pos - contains the positions
  10817. struct ggml_tensor * inp_pos = build_inp_pos();
  10818. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10819. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10820. for (int il = 0; il < n_layer; ++il) {
  10821. // norm
  10822. cur = llm_build_norm(ctx0, inpL, hparams,
  10823. model.layers[il].attn_norm, NULL,
  10824. LLM_NORM, cb, il);
  10825. cb(cur, "attn_norm", il);
  10826. struct ggml_tensor * ffn_inp = cur;
  10827. // self-attention
  10828. {
  10829. // compute Q and K and RoPE them
  10830. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10831. cb(Qcur, "Qcur", il);
  10832. if (model.layers[il].bq) {
  10833. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10834. cb(Qcur, "Qcur", il);
  10835. }
  10836. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10837. cb(Kcur, "Kcur", il);
  10838. if (model.layers[il].bk) {
  10839. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10840. cb(Kcur, "Kcur", il);
  10841. }
  10842. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10843. cb(Vcur, "Vcur", il);
  10844. if (model.layers[il].bv) {
  10845. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10846. cb(Vcur, "Vcur", il);
  10847. }
  10848. if (model.layers[il].attn_q_norm) {
  10849. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  10850. ggml_element_size(Qcur) * n_embd_head,
  10851. ggml_element_size(Qcur) * n_embd_head * n_head,
  10852. 0);
  10853. cb(Qcur, "Qcur", il);
  10854. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  10855. ggml_element_size(Kcur) * n_embd_head,
  10856. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  10857. 0);
  10858. cb(Kcur, "Kcur", il);
  10859. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10860. model.layers[il].attn_q_norm,
  10861. NULL,
  10862. LLM_NORM, cb, il);
  10863. cb(Qcur, "Qcur", il);
  10864. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10865. model.layers[il].attn_k_norm,
  10866. NULL,
  10867. LLM_NORM, cb, il);
  10868. cb(Kcur, "Kcur", il);
  10869. }
  10870. Qcur = ggml_rope_ext(
  10871. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10872. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10873. ext_factor, attn_factor, beta_fast, beta_slow
  10874. );
  10875. cb(Qcur, "Qcur", il);
  10876. Kcur = ggml_rope_ext(
  10877. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10878. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10879. ext_factor, attn_factor, beta_fast, beta_slow
  10880. );
  10881. cb(Kcur, "Kcur", il);
  10882. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10883. model.layers[il].wo, model.layers[il].bo,
  10884. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10885. }
  10886. if (il == n_layer - 1) {
  10887. // skip computing output for unused tokens
  10888. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10889. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10890. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10891. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  10892. }
  10893. struct ggml_tensor * attn_out = cur;
  10894. // feed-forward network
  10895. {
  10896. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  10897. model.layers[il].ffn_up, NULL, NULL,
  10898. model.layers[il].ffn_gate, NULL, NULL,
  10899. model.layers[il].ffn_down, NULL, NULL,
  10900. NULL,
  10901. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10902. cb(cur, "ffn_out", il);
  10903. }
  10904. // add together residual + FFN + self-attention
  10905. cur = ggml_add(ctx0, cur, inpL);
  10906. cur = ggml_add(ctx0, cur, attn_out);
  10907. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10908. cb(cur, "l_out", il);
  10909. // input for next layer
  10910. inpL = cur;
  10911. }
  10912. cur = inpL;
  10913. cur = llm_build_norm(ctx0, cur, hparams,
  10914. model.output_norm, NULL,
  10915. LLM_NORM, cb, -1);
  10916. cb(cur, "result_norm", -1);
  10917. // lm_head
  10918. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10919. if (f_logit_scale) {
  10920. cur = ggml_scale(ctx0, cur, f_logit_scale);
  10921. }
  10922. cb(cur, "result_output", -1);
  10923. ggml_build_forward_expand(gf, cur);
  10924. return gf;
  10925. }
  10926. // ref: https://allenai.org/olmo
  10927. // based on the original build_llama() function, changes:
  10928. // * non-parametric layer norm
  10929. // * clamp qkv
  10930. // * removed bias
  10931. // * removed MoE
  10932. struct ggml_cgraph * build_olmo() {
  10933. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10934. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10935. int32_t n_tokens = this->n_tokens;
  10936. const int64_t n_embd_head = hparams.n_embd_head_v;
  10937. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10938. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10939. struct ggml_tensor * cur;
  10940. struct ggml_tensor * inpL;
  10941. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10942. // inp_pos - contains the positions
  10943. struct ggml_tensor * inp_pos = build_inp_pos();
  10944. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10945. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10946. for (int il = 0; il < n_layer; ++il) {
  10947. struct ggml_tensor * inpSA = inpL;
  10948. // norm
  10949. cur = llm_build_norm(ctx0, inpL, hparams,
  10950. NULL, NULL,
  10951. LLM_NORM, cb, il);
  10952. cb(cur, "attn_norm", il);
  10953. // self-attention
  10954. {
  10955. // compute Q and K and RoPE them
  10956. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10957. cb(Qcur, "Qcur", il);
  10958. if (hparams.f_clamp_kqv > 0.0f) {
  10959. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10960. cb(Qcur, "Qcur", il);
  10961. }
  10962. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10963. cb(Kcur, "Kcur", il);
  10964. if (hparams.f_clamp_kqv > 0.0f) {
  10965. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10966. cb(Kcur, "Kcur", il);
  10967. }
  10968. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10969. cb(Vcur, "Vcur", il);
  10970. if (hparams.f_clamp_kqv > 0.0f) {
  10971. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10972. cb(Vcur, "Vcur", il);
  10973. }
  10974. Qcur = ggml_rope_ext(
  10975. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10976. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10977. ext_factor, attn_factor, beta_fast, beta_slow
  10978. );
  10979. cb(Qcur, "Qcur", il);
  10980. Kcur = ggml_rope_ext(
  10981. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10982. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10983. ext_factor, attn_factor, beta_fast, beta_slow
  10984. );
  10985. cb(Kcur, "Kcur", il);
  10986. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10987. model.layers[il].wo, nullptr,
  10988. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10989. }
  10990. if (il == n_layer - 1) {
  10991. // skip computing output for unused tokens
  10992. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10993. n_tokens = n_outputs;
  10994. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10995. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10996. }
  10997. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10998. cb(ffn_inp, "ffn_inp", il);
  10999. // feed-forward network
  11000. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11001. NULL, NULL,
  11002. LLM_NORM, cb, il);
  11003. cb(cur, "ffn_norm", il);
  11004. cur = llm_build_ffn(ctx0, lctx, cur,
  11005. model.layers[il].ffn_up, NULL, NULL,
  11006. model.layers[il].ffn_gate, NULL, NULL,
  11007. model.layers[il].ffn_down, NULL, NULL,
  11008. NULL,
  11009. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11010. cb(cur, "ffn_out", il);
  11011. cur = ggml_add(ctx0, cur, ffn_inp);
  11012. cb(cur, "ffn_out", il);
  11013. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11014. cb(cur, "l_out", il);
  11015. // input for next layer
  11016. inpL = cur;
  11017. }
  11018. cur = inpL;
  11019. cur = llm_build_norm(ctx0, cur, hparams,
  11020. NULL, NULL,
  11021. LLM_NORM, cb, -1);
  11022. cb(cur, "result_norm", -1);
  11023. // lm_head
  11024. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11025. cb(cur, "result_output", -1);
  11026. ggml_build_forward_expand(gf, cur);
  11027. return gf;
  11028. }
  11029. struct ggml_cgraph * build_openelm() {
  11030. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11031. const int64_t n_embd_head = hparams.n_embd_head_v;
  11032. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11033. struct ggml_tensor * cur;
  11034. struct ggml_tensor * inpL;
  11035. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11036. // inp_pos - contains the positions
  11037. struct ggml_tensor * inp_pos = build_inp_pos();
  11038. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11039. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11040. for (int il = 0; il < n_layer; ++il) {
  11041. const int64_t n_head = hparams.n_head(il);
  11042. const int64_t n_head_kv = hparams.n_head_kv(il);
  11043. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  11044. cur = inpL;
  11045. struct ggml_tensor * residual = cur;
  11046. // norm
  11047. cur = llm_build_norm(ctx0, inpL, hparams,
  11048. model.layers[il].attn_norm, NULL,
  11049. LLM_NORM_RMS, cb, il);
  11050. cb(cur, "attn_norm", il);
  11051. // self-attention
  11052. {
  11053. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11054. cb(cur, "wqkv", il);
  11055. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  11056. 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));
  11057. cb(Qcur, "Qcur", il);
  11058. 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));
  11059. cb(Kcur, "Kcur", il);
  11060. 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)));
  11061. cb(Vcur, "Vcur", il);
  11062. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  11063. model.layers[il].attn_q_norm, NULL,
  11064. LLM_NORM_RMS, cb, il);
  11065. cb(Qcur, "Qcur", il);
  11066. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  11067. model.layers[il].attn_k_norm, NULL,
  11068. LLM_NORM_RMS, cb, il);
  11069. cb(Kcur, "Kcur", il);
  11070. Qcur = ggml_rope_ext(
  11071. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  11072. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11073. );
  11074. cb(Qcur, "Qcur", il);
  11075. Kcur = ggml_rope_ext(
  11076. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  11077. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  11078. );
  11079. cb(Kcur, "Kcur", il);
  11080. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  11081. cb(Qcur, "Vcur", il);
  11082. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11083. model.layers[il].wo, NULL,
  11084. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11085. }
  11086. if (il == n_layer - 1) {
  11087. // skip computing output for unused tokens
  11088. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11089. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  11090. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11091. }
  11092. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  11093. cb(ffn_inp, "ffn_inp", il);
  11094. // feed-forward network
  11095. {
  11096. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11097. model.layers[il].ffn_norm, NULL,
  11098. LLM_NORM_RMS, cb, il);
  11099. cb(cur, "ffn_norm", il);
  11100. cur = llm_build_ffn(ctx0, lctx, cur,
  11101. model.layers[il].ffn_up, NULL, NULL,
  11102. model.layers[il].ffn_gate, NULL, NULL,
  11103. model.layers[il].ffn_down, NULL, NULL,
  11104. NULL,
  11105. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11106. cb(cur, "ffn_out", il);
  11107. }
  11108. cur = ggml_add(ctx0, cur, ffn_inp);
  11109. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11110. cb(cur, "l_out", il);
  11111. inpL = cur;
  11112. }
  11113. cur = inpL;
  11114. // norm
  11115. cur = llm_build_norm(ctx0, cur, hparams,
  11116. model.output_norm, NULL,
  11117. LLM_NORM_RMS, cb, -1);
  11118. cb(cur, "result_norm", -1);
  11119. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11120. cb(cur, "result_output", -1);
  11121. ggml_build_forward_expand(gf, cur);
  11122. return gf;
  11123. }
  11124. struct ggml_cgraph * build_gptneox() {
  11125. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11126. const int64_t n_embd_head = hparams.n_embd_head_v;
  11127. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11128. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11129. struct ggml_tensor * cur;
  11130. struct ggml_tensor * inpL;
  11131. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11132. // inp_pos - contains the positions
  11133. struct ggml_tensor * inp_pos = build_inp_pos();
  11134. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11135. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11136. for (int il = 0; il < n_layer; ++il) {
  11137. cur = llm_build_norm(ctx0, inpL, hparams,
  11138. model.layers[il].attn_norm,
  11139. model.layers[il].attn_norm_b,
  11140. LLM_NORM, cb, il);
  11141. cb(cur, "attn_norm", il);
  11142. // self-attention
  11143. {
  11144. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11145. cb(cur, "wqkv", il);
  11146. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11147. cb(cur, "bqkv", il);
  11148. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11149. 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)));
  11150. 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)));
  11151. cb(Qcur, "Qcur", il);
  11152. cb(Kcur, "Kcur", il);
  11153. cb(Vcur, "Vcur", il);
  11154. Qcur = ggml_rope_ext(
  11155. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11156. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11157. ext_factor, attn_factor, beta_fast, beta_slow
  11158. );
  11159. cb(Qcur, "Qcur", il);
  11160. Kcur = ggml_rope_ext(
  11161. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11162. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11163. ext_factor, attn_factor, beta_fast, beta_slow
  11164. );
  11165. cb(Kcur, "Kcur", il);
  11166. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11167. model.layers[il].wo, model.layers[il].bo,
  11168. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11169. }
  11170. if (il == n_layer - 1) {
  11171. // skip computing output for unused tokens
  11172. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11173. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11174. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11175. }
  11176. // ffn
  11177. if (hparams.use_par_res) {
  11178. // attention and ffn are computed in parallel
  11179. // x = x + attn(ln1(x)) + ffn(ln2(x))
  11180. struct ggml_tensor * attn_out = cur;
  11181. cur = llm_build_norm(ctx0, inpL, hparams,
  11182. model.layers[il].ffn_norm,
  11183. model.layers[il].ffn_norm_b,
  11184. LLM_NORM, cb, il);
  11185. cb(cur, "ffn_norm", il);
  11186. cur = llm_build_ffn(ctx0, lctx, cur,
  11187. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11188. NULL, NULL, NULL,
  11189. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11190. NULL,
  11191. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11192. cb(cur, "ffn_out", il);
  11193. cur = ggml_add(ctx0, cur, inpL);
  11194. cb(cur, "ffn_out", il);
  11195. cur = ggml_add(ctx0, cur, attn_out);
  11196. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11197. cb(cur, "l_out", il);
  11198. // input for next layer
  11199. inpL = cur;
  11200. } else {
  11201. // attention and ffn are computed sequentially
  11202. // x = x + attn(ln1(x))
  11203. // x = x + ffn(ln2(x))
  11204. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11205. cb(ffn_inp, "ffn_inp", il);
  11206. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11207. model.layers[il].ffn_norm,
  11208. model.layers[il].ffn_norm_b,
  11209. LLM_NORM, cb, il);
  11210. cb(cur, "ffn_norm", il);
  11211. cur = llm_build_ffn(ctx0, lctx, cur,
  11212. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11213. NULL, NULL, NULL,
  11214. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11215. NULL,
  11216. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  11217. cb(cur, "ffn_out", il);
  11218. cur = ggml_add(ctx0, cur, ffn_inp);
  11219. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11220. cb(cur, "l_out", il);
  11221. // input for next layer
  11222. inpL = cur;
  11223. }
  11224. }
  11225. cur = llm_build_norm(ctx0, inpL, hparams,
  11226. model.output_norm,
  11227. model.output_norm_b,
  11228. LLM_NORM, cb, -1);
  11229. cb(cur, "result_norm", -1);
  11230. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11231. cb(cur, "result_output", -1);
  11232. ggml_build_forward_expand(gf, cur);
  11233. return gf;
  11234. }
  11235. struct ggml_cgraph * build_arctic() {
  11236. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11237. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11238. int32_t n_tokens = this->n_tokens;
  11239. const int64_t n_embd_head = hparams.n_embd_head_v;
  11240. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11241. GGML_ASSERT(n_embd_head == hparams.n_rot);
  11242. struct ggml_tensor * cur;
  11243. struct ggml_tensor * inpL;
  11244. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11245. // inp_pos - contains the positions
  11246. struct ggml_tensor * inp_pos = build_inp_pos();
  11247. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11248. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11249. for (int il = 0; il < n_layer; ++il) {
  11250. struct ggml_tensor * inpSA = inpL;
  11251. // norm
  11252. cur = llm_build_norm(ctx0, inpL, hparams,
  11253. model.layers[il].attn_norm, NULL,
  11254. LLM_NORM_RMS, cb, il);
  11255. cb(cur, "attn_norm", il);
  11256. // self-attention
  11257. {
  11258. // compute Q and K and RoPE them
  11259. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11260. cb(Qcur, "Qcur", il);
  11261. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11262. cb(Kcur, "Kcur", il);
  11263. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11264. cb(Vcur, "Vcur", il);
  11265. Qcur = ggml_rope_ext(
  11266. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11267. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11268. ext_factor, attn_factor, beta_fast, beta_slow
  11269. );
  11270. cb(Qcur, "Qcur", il);
  11271. Kcur = ggml_rope_ext(
  11272. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11273. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11274. ext_factor, attn_factor, beta_fast, beta_slow
  11275. );
  11276. cb(Kcur, "Kcur", il);
  11277. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11278. model.layers[il].wo, NULL,
  11279. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11280. }
  11281. if (il == n_layer - 1) {
  11282. // skip computing output for unused tokens
  11283. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11284. n_tokens = n_outputs;
  11285. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11286. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11287. }
  11288. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11289. cb(ffn_inp, "ffn_inp", il);
  11290. // feed-forward network
  11291. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11292. model.layers[il].ffn_norm, NULL,
  11293. LLM_NORM_RMS, cb, il);
  11294. cb(cur, "ffn_norm", il);
  11295. cur = llm_build_ffn(ctx0, lctx, cur,
  11296. model.layers[il].ffn_up, NULL, NULL,
  11297. model.layers[il].ffn_gate, NULL, NULL,
  11298. model.layers[il].ffn_down, NULL, NULL,
  11299. NULL,
  11300. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11301. cb(cur, "ffn_out", il);
  11302. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  11303. cb(ffn_out, "ffn_out", il);
  11304. // MoE
  11305. cur = llm_build_norm(ctx0, inpSA, hparams,
  11306. model.layers[il].ffn_norm_exps, NULL,
  11307. LLM_NORM_RMS, cb, il);
  11308. cb(cur, "ffn_norm_exps", il);
  11309. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  11310. model.layers[il].ffn_gate_inp,
  11311. model.layers[il].ffn_up_exps,
  11312. model.layers[il].ffn_gate_exps,
  11313. model.layers[il].ffn_down_exps,
  11314. n_expert, n_expert_used,
  11315. LLM_FFN_SILU, true,
  11316. false, 0.0,
  11317. cb, il);
  11318. cb(cur, "ffn_moe_out", il);
  11319. cur = ggml_add(ctx0, cur, ffn_out);
  11320. cb(cur, "ffn_out", il);
  11321. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11322. cb(cur, "l_out", il);
  11323. // input for next layer
  11324. inpL = cur;
  11325. }
  11326. cur = inpL;
  11327. cur = llm_build_norm(ctx0, cur, hparams,
  11328. model.output_norm, NULL,
  11329. LLM_NORM_RMS, cb, -1);
  11330. cb(cur, "result_norm", -1);
  11331. // lm_head
  11332. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11333. cb(cur, "result_output", -1);
  11334. ggml_build_forward_expand(gf, cur);
  11335. return gf;
  11336. }
  11337. struct ggml_cgraph * build_deepseek2() {
  11338. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11339. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11340. int32_t n_tokens = this->n_tokens;
  11341. bool is_lite = (hparams.n_layer == 27);
  11342. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  11343. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  11344. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  11345. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  11346. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  11347. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  11348. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  11349. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  11350. struct ggml_tensor * cur;
  11351. struct ggml_tensor * inpL;
  11352. // {n_embd, n_tokens}
  11353. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11354. // inp_pos - contains the positions
  11355. struct ggml_tensor * inp_pos = build_inp_pos();
  11356. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11357. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11358. for (int il = 0; il < n_layer; ++il) {
  11359. struct ggml_tensor * inpSA = inpL;
  11360. // norm
  11361. cur = llm_build_norm(ctx0, inpL, hparams,
  11362. model.layers[il].attn_norm, NULL,
  11363. LLM_NORM_RMS, cb, il);
  11364. cb(cur, "attn_norm", il);
  11365. // self_attention
  11366. {
  11367. struct ggml_tensor * q = NULL;
  11368. if (!is_lite) {
  11369. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  11370. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  11371. cb(q, "q", il);
  11372. q = llm_build_norm(ctx0, q, hparams,
  11373. model.layers[il].attn_q_a_norm, NULL,
  11374. LLM_NORM_RMS, cb, il);
  11375. cb(q, "q", il);
  11376. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  11377. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  11378. cb(q, "q", il);
  11379. } else {
  11380. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  11381. cb(q, "q", il);
  11382. }
  11383. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11384. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  11385. ggml_row_size(q->type, hparams.n_embd_head_k),
  11386. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11387. 0);
  11388. cb(q_nope, "q_nope", il);
  11389. // and {n_head * n_embd_head_qk_rope, n_tokens}
  11390. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  11391. ggml_row_size(q->type, hparams.n_embd_head_k),
  11392. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  11393. ggml_row_size(q->type, n_embd_head_qk_nope));
  11394. cb(q_pe, "q_pe", il);
  11395. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  11396. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  11397. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  11398. // split into {kv_lora_rank, n_tokens}
  11399. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  11400. kv_pe_compresseed->nb[1],
  11401. 0);
  11402. cb(kv_compressed, "kv_compressed", il);
  11403. // and {n_embd_head_qk_rope, n_tokens}
  11404. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  11405. kv_pe_compresseed->nb[1],
  11406. kv_pe_compresseed->nb[1],
  11407. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  11408. cb(k_pe, "k_pe", il);
  11409. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  11410. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  11411. model.layers[il].attn_kv_a_norm, NULL,
  11412. LLM_NORM_RMS, cb, il);
  11413. cb(kv_compressed, "kv_compressed", il);
  11414. // {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}
  11415. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  11416. cb(kv, "kv", il);
  11417. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  11418. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  11419. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  11420. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11421. 0);
  11422. cb(k_nope, "k_nope", il);
  11423. // and {n_head * n_embd_head_v, n_tokens}
  11424. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  11425. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  11426. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  11427. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  11428. cb(v_states, "v_states", il);
  11429. v_states = ggml_cont(ctx0, v_states);
  11430. cb(v_states, "v_states", il);
  11431. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  11432. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  11433. 0);
  11434. cb(v_states, "v_states", il);
  11435. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11436. q_pe = ggml_rope_ext(
  11437. ctx0, q_pe, inp_pos, nullptr,
  11438. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11439. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  11440. );
  11441. cb(q_pe, "q_pe", il);
  11442. // shared RoPE key
  11443. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  11444. k_pe = ggml_rope_ext(
  11445. ctx0, k_pe, inp_pos, nullptr,
  11446. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11447. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  11448. );
  11449. cb(k_pe, "k_pe", il);
  11450. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  11451. cb(q_states, "q_states", il);
  11452. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  11453. cb(k_states, "k_states", il);
  11454. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11455. model.layers[il].wo, NULL,
  11456. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  11457. }
  11458. if (il == n_layer - 1) {
  11459. // skip computing output for unused tokens
  11460. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11461. n_tokens = n_outputs;
  11462. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11463. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11464. }
  11465. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11466. cb(ffn_inp, "ffn_inp", il);
  11467. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11468. model.layers[il].ffn_norm, NULL,
  11469. LLM_NORM_RMS, cb, il);
  11470. cb(cur, "ffn_norm", il);
  11471. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  11472. cur = llm_build_ffn(ctx0, lctx, cur,
  11473. model.layers[il].ffn_up, NULL, NULL,
  11474. model.layers[il].ffn_gate, NULL, NULL,
  11475. model.layers[il].ffn_down, NULL, NULL,
  11476. NULL,
  11477. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11478. cb(cur, "ffn_out", il);
  11479. } else {
  11480. // MoE branch
  11481. ggml_tensor * moe_out =
  11482. llm_build_moe_ffn(ctx0, lctx, cur,
  11483. model.layers[il].ffn_gate_inp,
  11484. model.layers[il].ffn_up_exps,
  11485. model.layers[il].ffn_gate_exps,
  11486. model.layers[il].ffn_down_exps,
  11487. n_expert, n_expert_used,
  11488. LLM_FFN_SILU, false,
  11489. true, hparams.expert_weights_scale,
  11490. cb, il);
  11491. cb(moe_out, "ffn_moe_out", il);
  11492. // FFN shared expert
  11493. {
  11494. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  11495. model.layers[il].ffn_up_shexp, NULL, NULL,
  11496. model.layers[il].ffn_gate_shexp, NULL, NULL,
  11497. model.layers[il].ffn_down_shexp, NULL, NULL,
  11498. NULL,
  11499. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11500. cb(ffn_shexp, "ffn_shexp", il);
  11501. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  11502. cb(cur, "ffn_out", il);
  11503. }
  11504. }
  11505. cur = ggml_add(ctx0, cur, ffn_inp);
  11506. cur = lctx.cvec.apply_to(ctx0, cur, il);
  11507. cb(cur, "l_out", il);
  11508. // input for next layer
  11509. inpL = cur;
  11510. }
  11511. cur = inpL;
  11512. cur = llm_build_norm(ctx0, cur, hparams,
  11513. model.output_norm, NULL,
  11514. LLM_NORM_RMS, cb, -1);
  11515. cb(cur, "result_norm", -1);
  11516. // lm_head
  11517. cur = ggml_mul_mat(ctx0, model.output, cur);
  11518. cb(cur, "result_output", -1);
  11519. ggml_build_forward_expand(gf, cur);
  11520. return gf;
  11521. }
  11522. struct ggml_cgraph * build_bitnet() {
  11523. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11524. const int64_t n_embd_head = hparams.n_embd_head_v;
  11525. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11526. struct ggml_tensor * cur;
  11527. struct ggml_tensor * inpL;
  11528. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11529. // inp_pos - contains the positions
  11530. struct ggml_tensor * inp_pos = build_inp_pos();
  11531. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11532. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11533. for (int il = 0; il < n_layer; ++il) {
  11534. struct ggml_tensor * inpSA = inpL;
  11535. cur = llm_build_norm(ctx0, inpL, hparams,
  11536. model.layers[il].attn_norm, NULL,
  11537. LLM_NORM_RMS, cb, il);
  11538. cb(cur, "attn_norm", il);
  11539. // self-attention
  11540. {
  11541. // compute Q and K and RoPE them
  11542. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11543. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  11544. cb(Qcur, "Qcur", il);
  11545. if (model.layers[il].bq) {
  11546. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  11547. cb(Qcur, "Qcur", il);
  11548. }
  11549. // B1.K
  11550. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11551. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  11552. cb(Kcur, "Kcur", il);
  11553. if (model.layers[il].bk) {
  11554. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  11555. cb(Kcur, "Kcur", il);
  11556. }
  11557. // B1.V
  11558. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11559. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  11560. cb(Vcur, "Vcur", il);
  11561. if (model.layers[il].bv) {
  11562. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  11563. cb(Vcur, "Vcur", il);
  11564. }
  11565. Qcur = ggml_rope_ext(
  11566. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11567. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11568. ext_factor, attn_factor, beta_fast, beta_slow
  11569. );
  11570. cb(Qcur, "Qcur", il);
  11571. Kcur = ggml_rope_ext(
  11572. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11573. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11574. ext_factor, attn_factor, beta_fast, beta_slow
  11575. );
  11576. cb(Kcur, "Kcur", il);
  11577. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11578. NULL, NULL,
  11579. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11580. cur = llm_build_norm(ctx0, cur, hparams,
  11581. model.layers[il].attn_sub_norm, NULL,
  11582. LLM_NORM_RMS, cb, il);
  11583. cb(cur, "attn_sub_norm", il);
  11584. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  11585. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  11586. if (model.layers[il].bo) {
  11587. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  11588. }
  11589. cb(cur, "attn_o_out", il);
  11590. }
  11591. if (il == n_layer - 1) {
  11592. // skip computing output for unused tokens
  11593. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11594. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11595. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11596. }
  11597. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11598. cb(ffn_inp, "ffn_inp", il);
  11599. // feed-forward forward
  11600. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11601. model.layers[il].ffn_norm, NULL,
  11602. LLM_NORM_RMS, cb, il);
  11603. cb(cur, "ffn_norm", il);
  11604. cur = llm_build_ffn(ctx0, lctx, cur,
  11605. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  11606. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  11607. NULL, NULL, NULL,
  11608. NULL,
  11609. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11610. cb(cur, "ffn_sub_out", il);
  11611. cur = llm_build_norm(ctx0, cur, hparams,
  11612. model.layers[il].ffn_sub_norm, NULL,
  11613. LLM_NORM_RMS, cb, il);
  11614. cb(cur, "ffn_sub_norm", il);
  11615. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  11616. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  11617. cb(cur, "ffn_down", il);
  11618. cur = ggml_add(ctx0, cur, ffn_inp);
  11619. cb(cur, "l_out", il);
  11620. // input for next layer
  11621. inpL = cur;
  11622. }
  11623. cur = inpL;
  11624. cur = llm_build_norm(ctx0, cur, hparams,
  11625. model.output_norm, NULL,
  11626. LLM_NORM_RMS, cb, -1);
  11627. cb(cur, "result_norm", -1);
  11628. // lm_head
  11629. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  11630. cb(cur, "result_output", -1);
  11631. ggml_build_forward_expand(gf, cur);
  11632. return gf;
  11633. }
  11634. struct ggml_cgraph * build_t5_encoder() {
  11635. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11636. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11637. int32_t n_tokens = this->n_tokens;
  11638. const int64_t n_embd_head = hparams.n_embd_head_v;
  11639. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11640. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11641. struct ggml_tensor * cur;
  11642. struct ggml_tensor * inpL;
  11643. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11644. GGML_ASSERT(lctx.is_encoding);
  11645. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  11646. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11647. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  11648. for (int il = 0; il < n_layer; ++il) {
  11649. struct ggml_tensor * inpSA = inpL;
  11650. // norm
  11651. cur = llm_build_norm(ctx0, inpL, hparams,
  11652. model.layers[il].attn_norm_enc, NULL,
  11653. LLM_NORM_RMS, cb, il);
  11654. cb(cur, "attn_norm", il);
  11655. // self-attention
  11656. {
  11657. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_enc, cur);
  11658. cb(Qcur, "Qcur", il);
  11659. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_enc, cur);
  11660. cb(Kcur, "Kcur", il);
  11661. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_enc, cur);
  11662. cb(Vcur, "Vcur", il);
  11663. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11664. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  11665. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11666. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  11667. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11668. cb(kq, "kq", il);
  11669. 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;
  11670. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  11671. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11672. cb(kq_b, "kq_b", il);
  11673. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  11674. cb(kq, "kq_soft_max_ext", il);
  11675. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  11676. cb(v, "v", il);
  11677. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  11678. cb(kqv, "kqv", il);
  11679. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11680. cb(kqv_merged, "kqv_merged", il);
  11681. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11682. cb(cur, "kqv_merged_cont", il);
  11683. ggml_build_forward_expand(gf, cur);
  11684. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_enc, cur);
  11685. cb(cur, "kqv_out", il);
  11686. }
  11687. if (il == n_layer - 1) {
  11688. // skip computing output for unused tokens
  11689. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11690. n_tokens = n_outputs;
  11691. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11692. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11693. }
  11694. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11695. cb(ffn_inp, "ffn_inp", il);
  11696. // feed-forward network
  11697. {
  11698. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11699. model.layers[il].ffn_norm_enc, NULL,
  11700. LLM_NORM_RMS, cb, il);
  11701. cb(cur, "ffn_norm", il);
  11702. // T5 uses relu, flan-T5 uses gelu-gated
  11703. cur = llm_build_ffn(ctx0, lctx, cur,
  11704. model.layers[il].ffn_up_enc, NULL, NULL,
  11705. model.layers[il].ffn_gate_enc, NULL, NULL,
  11706. model.layers[il].ffn_down_enc, NULL, NULL,
  11707. NULL,
  11708. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11709. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11710. cb, il);
  11711. cb(cur, "ffn_out", il);
  11712. }
  11713. cur = ggml_add(ctx0, cur, ffn_inp);
  11714. cb(cur, "ffn_out", il);
  11715. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11716. if (layer_dir != nullptr) {
  11717. cur = ggml_add(ctx0, cur, layer_dir);
  11718. }
  11719. cb(cur, "l_out", il);
  11720. // input for next layer
  11721. inpL = cur;
  11722. }
  11723. cur = inpL;
  11724. cb(cur, "result_embd", -1);
  11725. cur = llm_build_norm(ctx0, cur, hparams,
  11726. model.output_norm_enc, NULL,
  11727. LLM_NORM_RMS, cb, -1);
  11728. cb(cur, "result_norm", -1);
  11729. ggml_build_forward_expand(gf, cur);
  11730. return gf;
  11731. }
  11732. struct ggml_cgraph * build_t5_decoder() {
  11733. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11734. // mutable variable, needed during the last layer of the computation to skip unused tokens
  11735. int32_t n_tokens = this->n_tokens;
  11736. const int64_t n_embd_head = hparams.n_embd_head_v;
  11737. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11738. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11739. struct ggml_tensor * cur;
  11740. struct ggml_tensor * inpL;
  11741. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11742. GGML_ASSERT(!lctx.is_encoding);
  11743. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  11744. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  11745. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  11746. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  11747. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  11748. for (int il = 0; il < n_layer; ++il) {
  11749. struct ggml_tensor * inpSA = inpL;
  11750. // norm
  11751. cur = llm_build_norm(ctx0, inpL, hparams,
  11752. model.layers[il].attn_norm, NULL,
  11753. LLM_NORM_RMS, cb, il);
  11754. cb(cur, "attn_norm", il);
  11755. // self-attention
  11756. {
  11757. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  11758. cb(Qcur, "Qcur", il);
  11759. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  11760. cb(Kcur, "Kcur", il);
  11761. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  11762. cb(Vcur, "Vcur", il);
  11763. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  11764. struct ggml_tensor * k =
  11765. ggml_view_3d(ctx0, kv_self.k_l[il],
  11766. n_embd_head_k, n_kv, n_head_kv,
  11767. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  11768. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  11769. 0);
  11770. cb(k, "k", il);
  11771. struct ggml_tensor * v =
  11772. ggml_view_3d(ctx0, kv_self.v_l[il],
  11773. n_kv, n_embd_head_v, n_head_kv,
  11774. ggml_element_size(kv_self.v_l[il])*n_ctx,
  11775. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  11776. 0);
  11777. cb(v, "v", il);
  11778. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11779. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11780. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11781. cb(kq, "kq", il);
  11782. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  11783. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  11784. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11785. cb(kq_b, "kq_b", il);
  11786. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  11787. cb(kq, "kq_soft_max_ext", il);
  11788. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  11789. cb(kqv, "kqv", il);
  11790. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11791. cb(kqv_merged, "kqv_merged", il);
  11792. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11793. cb(cur, "kqv_merged_cont", il);
  11794. ggml_build_forward_expand(gf, cur);
  11795. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  11796. cb(cur, "kqv_out", il);
  11797. }
  11798. cur = ggml_add(ctx0, cur, inpSA);
  11799. cb(cur, "cross_inp", il);
  11800. struct ggml_tensor * inpCA = cur;
  11801. // norm
  11802. cur = llm_build_norm(ctx0, cur, hparams,
  11803. model.layers[il].attn_norm_cross, NULL,
  11804. LLM_NORM_RMS, cb, il);
  11805. cb(cur, "attn_norm_cross", il);
  11806. // cross-attention
  11807. {
  11808. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq_cross, cur);
  11809. cb(Qcur, "Qcur", il);
  11810. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk_cross, embd_enc);
  11811. cb(Kcur, "Kcur", il);
  11812. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv_cross, embd_enc);
  11813. cb(Vcur, "Vcur", il);
  11814. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11815. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  11816. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11817. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  11818. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11819. cb(kq, "kq", il);
  11820. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  11821. cb(kq, "kq_soft_max_ext", il);
  11822. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  11823. cb(v, "v", il);
  11824. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  11825. cb(kqv, "kqv", il);
  11826. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11827. cb(kqv_merged, "kqv_merged", il);
  11828. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11829. cb(cur, "kqv_merged_cont", il);
  11830. ggml_build_forward_expand(gf, cur);
  11831. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo_cross, cur);
  11832. cb(cur, "kqv_out", il);
  11833. }
  11834. if (il == n_layer - 1) {
  11835. // skip computing output for unused tokens
  11836. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11837. n_tokens = n_outputs;
  11838. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11839. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11840. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  11841. }
  11842. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  11843. cb(ffn_inp, "ffn_inp", il);
  11844. // feed-forward network
  11845. {
  11846. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11847. model.layers[il].ffn_norm, NULL,
  11848. LLM_NORM_RMS, cb, il);
  11849. cb(cur, "ffn_norm", il);
  11850. // T5 uses relu, flan-T5 uses gelu-gated
  11851. cur = llm_build_ffn(ctx0, lctx, cur,
  11852. model.layers[il].ffn_up, NULL, NULL,
  11853. model.layers[il].ffn_gate, NULL, NULL,
  11854. model.layers[il].ffn_down, NULL, NULL,
  11855. NULL,
  11856. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11857. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11858. cb, il);
  11859. cb(cur, "ffn_out", il);
  11860. }
  11861. cur = ggml_add(ctx0, cur, ffn_inp);
  11862. cb(cur, "ffn_out", il);
  11863. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11864. if (layer_dir != nullptr) {
  11865. cur = ggml_add(ctx0, cur, layer_dir);
  11866. }
  11867. cb(cur, "l_out", il);
  11868. // input for next layer
  11869. inpL = cur;
  11870. }
  11871. cur = inpL;
  11872. cb(cur, "result_embd", -1);
  11873. cur = llm_build_norm(ctx0, cur, hparams,
  11874. model.output_norm, NULL,
  11875. LLM_NORM_RMS, cb, -1);
  11876. cb(cur, "result_norm", -1);
  11877. // lm_head
  11878. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11879. cb(cur, "result_output", -1);
  11880. ggml_build_forward_expand(gf, cur);
  11881. return gf;
  11882. }
  11883. struct ggml_cgraph * build_jais() {
  11884. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11885. const int64_t n_embd_head = hparams.n_embd_head_v;
  11886. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11887. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11888. struct ggml_tensor * cur;
  11889. struct ggml_tensor * inpL;
  11890. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11891. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11892. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11893. for (int il = 0; il < n_layer; ++il) {
  11894. cur = llm_build_norm(ctx0, inpL, hparams,
  11895. model.layers[il].attn_norm,
  11896. model.layers[il].attn_norm_b,
  11897. LLM_NORM, cb, il);
  11898. cb(cur, "attn_norm", il);
  11899. // self-attention
  11900. {
  11901. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11902. cb(cur, "wqkv", il);
  11903. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11904. cb(cur, "bqkv", il);
  11905. 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)));
  11906. 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)));
  11907. 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)));
  11908. cb(Qcur, "Qcur", il);
  11909. cb(Kcur, "Kcur", il);
  11910. cb(Vcur, "Vcur", il);
  11911. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11912. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11913. model.layers[il].wo, model.layers[il].bo,
  11914. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  11915. }
  11916. if (il == n_layer - 1) {
  11917. // skip computing output for unused tokens
  11918. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11919. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11920. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11921. }
  11922. // add the input
  11923. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11924. cb(ffn_inp, "ffn_inp", il);
  11925. // FF
  11926. {
  11927. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11928. model.layers[il].ffn_norm,
  11929. model.layers[il].ffn_norm_b,
  11930. LLM_NORM, cb, il);
  11931. cb(cur, "ffn_norm", il);
  11932. cur = llm_build_ffn(ctx0, lctx, cur,
  11933. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11934. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  11935. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11936. NULL,
  11937. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11938. cb(cur, "ffn_out", il);
  11939. }
  11940. inpL = ggml_add(ctx0, cur, ffn_inp);
  11941. cb(inpL, "l_out", il);
  11942. }
  11943. cur = llm_build_norm(ctx0, inpL, hparams,
  11944. model.output_norm,
  11945. model.output_norm_b,
  11946. LLM_NORM, cb, -1);
  11947. cb(cur, "result_norm", -1);
  11948. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11949. cb(cur, "result_output", -1);
  11950. ggml_build_forward_expand(gf, cur);
  11951. return gf;
  11952. }
  11953. struct ggml_cgraph * build_chatglm() {
  11954. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11955. const int64_t n_embd_head = hparams.n_embd_head_v;
  11956. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11957. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11958. struct ggml_tensor * cur;
  11959. struct ggml_tensor * inpL;
  11960. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11961. // inp_pos - contains the positions
  11962. struct ggml_tensor * inp_pos = build_inp_pos();
  11963. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11964. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11965. for (int il = 0; il < n_layer; ++il) {
  11966. struct ggml_tensor * inpSA = inpL;
  11967. cur = llm_build_norm(ctx0, inpL, hparams,
  11968. model.layers[il].attn_norm,
  11969. NULL,
  11970. LLM_NORM_RMS, cb, il);
  11971. cb(cur, "attn_norm", il);
  11972. // self-attention
  11973. {
  11974. struct ggml_tensor * Qcur = nullptr;
  11975. struct ggml_tensor * Kcur = nullptr;
  11976. struct ggml_tensor * Vcur = nullptr;
  11977. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11978. cb(cur, "wqkv", il);
  11979. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11980. cb(cur, "bqkv", il);
  11981. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11982. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11983. 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)));
  11984. cb(Qcur, "Qcur", il);
  11985. cb(Kcur, "Kcur", il);
  11986. cb(Vcur, "Vcur", il);
  11987. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  11988. Qcur = ggml_rope_ext(
  11989. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11990. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11991. ext_factor, attn_factor, beta_fast, beta_slow
  11992. );
  11993. cb(Qcur, "Qcur_rope", il);
  11994. Kcur = ggml_rope_ext(
  11995. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11996. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11997. ext_factor, attn_factor, beta_fast, beta_slow
  11998. );
  11999. cb(Kcur, "Kcur_rope", il);
  12000. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12001. model.layers[il].wo, NULL,
  12002. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12003. }
  12004. if (il == n_layer - 1) {
  12005. // skip computing output for unused tokens
  12006. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12007. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12008. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12009. }
  12010. // Add the input
  12011. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12012. cb(ffn_inp, "ffn_inp", il);
  12013. // FF
  12014. {
  12015. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12016. model.layers[il].ffn_norm,
  12017. NULL,
  12018. LLM_NORM_RMS, cb, il);
  12019. cb(cur, "ffn_norm", il);
  12020. cur = llm_build_ffn(ctx0, lctx, cur,
  12021. model.layers[il].ffn_up, NULL, NULL,
  12022. NULL, NULL, NULL,
  12023. model.layers[il].ffn_down, NULL, NULL,
  12024. NULL,
  12025. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  12026. cb(cur, "ffn_out", il);
  12027. }
  12028. inpL = ggml_add(ctx0, cur, ffn_inp);
  12029. cb(inpL, "l_out", il);
  12030. }
  12031. cur = llm_build_norm(ctx0, inpL, hparams,
  12032. model.output_norm,
  12033. NULL,
  12034. LLM_NORM_RMS, cb, -1);
  12035. cb(cur, "result_norm", -1);
  12036. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12037. cb(cur, "result_output", -1);
  12038. ggml_build_forward_expand(gf, cur);
  12039. return gf;
  12040. }
  12041. struct ggml_cgraph * build_nemotron() {
  12042. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12043. const int64_t n_embd_head = hparams.n_embd_head_v;
  12044. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12045. //GGML_ASSERT(n_embd_head == hparams.n_rot);
  12046. struct ggml_tensor * cur;
  12047. struct ggml_tensor * inpL;
  12048. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12049. // inp_pos - contains the positions
  12050. struct ggml_tensor * inp_pos = build_inp_pos();
  12051. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12052. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12053. for (int il = 0; il < n_layer; ++il) {
  12054. struct ggml_tensor * inpSA = inpL;
  12055. // norm
  12056. cur = llm_build_norm(ctx0, inpL, hparams,
  12057. model.layers[il].attn_norm,
  12058. model.layers[il].attn_norm_b,
  12059. LLM_NORM, cb, il);
  12060. cb(cur, "attn_norm", il);
  12061. // self-attention
  12062. {
  12063. // compute Q and K and RoPE them
  12064. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12065. cb(Qcur, "Qcur", il);
  12066. if (model.layers[il].bq) {
  12067. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12068. cb(Qcur, "Qcur", il);
  12069. }
  12070. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12071. cb(Kcur, "Kcur", il);
  12072. if (model.layers[il].bk) {
  12073. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12074. cb(Kcur, "Kcur", il);
  12075. }
  12076. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12077. cb(Vcur, "Vcur", il);
  12078. if (model.layers[il].bv) {
  12079. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12080. cb(Vcur, "Vcur", il);
  12081. }
  12082. Qcur = ggml_rope_ext(
  12083. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  12084. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12085. ext_factor, attn_factor, beta_fast, beta_slow
  12086. );
  12087. cb(Qcur, "Qcur", il);
  12088. Kcur = ggml_rope_ext(
  12089. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  12090. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12091. ext_factor, attn_factor, beta_fast, beta_slow
  12092. );
  12093. cb(Kcur, "Kcur", il);
  12094. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12095. model.layers[il].wo, model.layers[il].bo,
  12096. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12097. }
  12098. if (il == n_layer - 1) {
  12099. // skip computing output for unused tokens
  12100. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12101. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12102. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12103. }
  12104. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12105. cb(ffn_inp, "ffn_inp", il);
  12106. // feed-forward network
  12107. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12108. model.layers[il].ffn_norm,
  12109. model.layers[il].ffn_norm_b,
  12110. LLM_NORM, cb, il);
  12111. cb(cur, "ffn_norm", il);
  12112. cur = llm_build_ffn(ctx0, lctx, cur,
  12113. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  12114. NULL, NULL, NULL,
  12115. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  12116. NULL,
  12117. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  12118. cur = ggml_add(ctx0, cur, ffn_inp);
  12119. cb(cur, "ffn_out", il);
  12120. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12121. cb(cur, "l_out", il);
  12122. // input for next layer
  12123. inpL = cur;
  12124. }
  12125. cur = inpL;
  12126. cur = llm_build_norm(ctx0, cur, hparams,
  12127. model.output_norm, model.output_norm_b,
  12128. LLM_NORM, cb, -1);
  12129. cb(cur, "result_norm", -1);
  12130. // lm_head
  12131. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12132. cb(cur, "result_output", -1);
  12133. ggml_build_forward_expand(gf, cur);
  12134. return gf;
  12135. }
  12136. struct ggml_cgraph * build_exaone() {
  12137. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  12138. // mutable variable, needed during the last layer of the computation to skip unused tokens
  12139. int32_t n_tokens = this->n_tokens;
  12140. const int64_t n_embd_head = hparams.n_embd_head_v;
  12141. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  12142. GGML_ASSERT(n_embd_head == hparams.n_rot);
  12143. struct ggml_tensor * cur;
  12144. struct ggml_tensor * inpL;
  12145. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  12146. // inp_pos - contains the positions
  12147. struct ggml_tensor * inp_pos = build_inp_pos();
  12148. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  12149. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  12150. for (int il = 0; il < n_layer; ++il) {
  12151. struct ggml_tensor * inpSA = inpL;
  12152. // norm
  12153. cur = llm_build_norm(ctx0, inpL, hparams,
  12154. model.layers[il].attn_norm, NULL,
  12155. LLM_NORM_RMS, cb, il);
  12156. cb(cur, "attn_norm", il);
  12157. // self-attention
  12158. {
  12159. // rope freq factors for llama3; may return nullptr for llama2 and other models
  12160. struct ggml_tensor * rope_factors = build_rope_factors(il);
  12161. // compute Q and K and RoPE them
  12162. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  12163. cb(Qcur, "Qcur", il);
  12164. if (model.layers[il].bq) {
  12165. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  12166. cb(Qcur, "Qcur", il);
  12167. }
  12168. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  12169. cb(Kcur, "Kcur", il);
  12170. if (model.layers[il].bk) {
  12171. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  12172. cb(Kcur, "Kcur", il);
  12173. }
  12174. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  12175. cb(Vcur, "Vcur", il);
  12176. if (model.layers[il].bv) {
  12177. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  12178. cb(Vcur, "Vcur", il);
  12179. }
  12180. Qcur = ggml_rope_ext(
  12181. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  12182. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12183. ext_factor, attn_factor, beta_fast, beta_slow
  12184. );
  12185. cb(Qcur, "Qcur", il);
  12186. Kcur = ggml_rope_ext(
  12187. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  12188. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  12189. ext_factor, attn_factor, beta_fast, beta_slow
  12190. );
  12191. cb(Kcur, "Kcur", il);
  12192. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  12193. model.layers[il].wo, model.layers[il].bo,
  12194. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  12195. }
  12196. if (il == n_layer - 1) {
  12197. // skip computing output for unused tokens
  12198. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  12199. n_tokens = n_outputs;
  12200. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  12201. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  12202. }
  12203. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  12204. cb(ffn_inp, "ffn_inp", il);
  12205. // feed-forward network
  12206. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  12207. model.layers[il].ffn_norm, NULL,
  12208. LLM_NORM_RMS, cb, il);
  12209. cb(cur, "ffn_norm", il);
  12210. cur = llm_build_ffn(ctx0, lctx, cur,
  12211. model.layers[il].ffn_up, NULL, NULL,
  12212. model.layers[il].ffn_gate, NULL, NULL,
  12213. model.layers[il].ffn_down, NULL, NULL,
  12214. NULL,
  12215. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  12216. cb(cur, "ffn_out", il);
  12217. cur = ggml_add(ctx0, cur, ffn_inp);
  12218. cb(cur, "ffn_out", il);
  12219. cur = lctx.cvec.apply_to(ctx0, cur, il);
  12220. cb(cur, "l_out", il);
  12221. // input for next layer
  12222. inpL = cur;
  12223. }
  12224. cur = inpL;
  12225. cur = llm_build_norm(ctx0, cur, hparams,
  12226. model.output_norm, NULL,
  12227. LLM_NORM_RMS, cb, -1);
  12228. cb(cur, "result_norm", -1);
  12229. // lm_head
  12230. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  12231. cb(cur, "result_output", -1);
  12232. ggml_build_forward_expand(gf, cur);
  12233. return gf;
  12234. }
  12235. };
  12236. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  12237. llama_ubatch dummy = {};
  12238. dummy.equal_seqs = true;
  12239. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  12240. struct llm_build_context llm(lctx, dummy, cb, false);
  12241. llm.init();
  12242. struct ggml_cgraph * result = llm.build_defrag(ids);
  12243. llm.free();
  12244. return result;
  12245. }
  12246. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  12247. llama_ubatch dummy = {};
  12248. dummy.equal_seqs = true;
  12249. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  12250. struct llm_build_context llm(lctx, dummy, cb, false);
  12251. llm.init();
  12252. struct ggml_cgraph * result = llm.build_k_shift();
  12253. llm.free();
  12254. return result;
  12255. }
  12256. static struct ggml_cgraph * llama_build_graph(
  12257. llama_context & lctx,
  12258. const llama_ubatch & batch,
  12259. bool worst_case) {
  12260. const auto & model = lctx.model;
  12261. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  12262. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  12263. if (il >= 0) {
  12264. ggml_format_name(cur, "%s-%d", name, il);
  12265. } else {
  12266. ggml_set_name(cur, name);
  12267. }
  12268. if (!lctx.cparams.offload_kqv) {
  12269. if (strcmp(name, "kqv_merged_cont") == 0) {
  12270. // all nodes between the KV store and the attention output are run on the CPU
  12271. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  12272. }
  12273. }
  12274. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  12275. // FIXME: fix in ggml_backend_sched
  12276. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  12277. if (batch.n_tokens < 32 || full_offload) {
  12278. if (il != -1 && strcmp(name, "norm") == 0) {
  12279. for (auto * backend : lctx.backends) {
  12280. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  12281. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  12282. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  12283. break;
  12284. }
  12285. }
  12286. }
  12287. }
  12288. };
  12289. struct ggml_cgraph * result = NULL;
  12290. struct llm_build_context llm(lctx, batch, cb, worst_case);
  12291. llm.init();
  12292. switch (model.arch) {
  12293. case LLM_ARCH_LLAMA:
  12294. {
  12295. result = llm.build_llama();
  12296. } break;
  12297. case LLM_ARCH_BAICHUAN:
  12298. {
  12299. result = llm.build_baichuan();
  12300. } break;
  12301. case LLM_ARCH_FALCON:
  12302. {
  12303. result = llm.build_falcon();
  12304. } break;
  12305. case LLM_ARCH_GROK:
  12306. {
  12307. result = llm.build_grok();
  12308. } break;
  12309. case LLM_ARCH_STARCODER:
  12310. {
  12311. result = llm.build_starcoder();
  12312. } break;
  12313. case LLM_ARCH_REFACT:
  12314. {
  12315. result = llm.build_refact();
  12316. } break;
  12317. case LLM_ARCH_BERT:
  12318. case LLM_ARCH_JINA_BERT_V2:
  12319. case LLM_ARCH_NOMIC_BERT:
  12320. {
  12321. result = llm.build_bert();
  12322. } break;
  12323. case LLM_ARCH_BLOOM:
  12324. {
  12325. result = llm.build_bloom();
  12326. } break;
  12327. case LLM_ARCH_MPT:
  12328. {
  12329. result = llm.build_mpt();
  12330. } break;
  12331. case LLM_ARCH_STABLELM:
  12332. {
  12333. result = llm.build_stablelm();
  12334. } break;
  12335. case LLM_ARCH_QWEN:
  12336. {
  12337. result = llm.build_qwen();
  12338. } break;
  12339. case LLM_ARCH_QWEN2:
  12340. {
  12341. result = llm.build_qwen2();
  12342. } break;
  12343. case LLM_ARCH_QWEN2MOE:
  12344. {
  12345. result = llm.build_qwen2moe();
  12346. } break;
  12347. case LLM_ARCH_PHI2:
  12348. {
  12349. result = llm.build_phi2();
  12350. } break;
  12351. case LLM_ARCH_PHI3:
  12352. {
  12353. result = llm.build_phi3();
  12354. } break;
  12355. case LLM_ARCH_PLAMO:
  12356. {
  12357. result = llm.build_plamo();
  12358. } break;
  12359. case LLM_ARCH_GPT2:
  12360. {
  12361. result = llm.build_gpt2();
  12362. } break;
  12363. case LLM_ARCH_CODESHELL:
  12364. {
  12365. result = llm.build_codeshell();
  12366. } break;
  12367. case LLM_ARCH_ORION:
  12368. {
  12369. result = llm.build_orion();
  12370. } break;
  12371. case LLM_ARCH_INTERNLM2:
  12372. {
  12373. result = llm.build_internlm2();
  12374. } break;
  12375. case LLM_ARCH_MINICPM:
  12376. {
  12377. result = llm.build_minicpm();
  12378. } break;
  12379. case LLM_ARCH_GEMMA:
  12380. {
  12381. result = llm.build_gemma();
  12382. } break;
  12383. case LLM_ARCH_GEMMA2:
  12384. {
  12385. result = llm.build_gemma2();
  12386. } break;
  12387. case LLM_ARCH_STARCODER2:
  12388. {
  12389. result = llm.build_starcoder2();
  12390. } break;
  12391. case LLM_ARCH_MAMBA:
  12392. {
  12393. result = llm.build_mamba();
  12394. } break;
  12395. case LLM_ARCH_XVERSE:
  12396. {
  12397. result = llm.build_xverse();
  12398. } break;
  12399. case LLM_ARCH_COMMAND_R:
  12400. {
  12401. result = llm.build_command_r();
  12402. } break;
  12403. case LLM_ARCH_DBRX:
  12404. {
  12405. result = llm.build_dbrx();
  12406. } break;
  12407. case LLM_ARCH_OLMO:
  12408. {
  12409. result = llm.build_olmo();
  12410. } break;
  12411. case LLM_ARCH_OPENELM:
  12412. {
  12413. result = llm.build_openelm();
  12414. } break;
  12415. case LLM_ARCH_GPTNEOX:
  12416. {
  12417. result = llm.build_gptneox();
  12418. } break;
  12419. case LLM_ARCH_ARCTIC:
  12420. {
  12421. result = llm.build_arctic();
  12422. } break;
  12423. case LLM_ARCH_DEEPSEEK2:
  12424. {
  12425. result = llm.build_deepseek2();
  12426. } break;
  12427. case LLM_ARCH_CHATGLM:
  12428. {
  12429. result = llm.build_chatglm();
  12430. } break;
  12431. case LLM_ARCH_BITNET:
  12432. {
  12433. result = llm.build_bitnet();
  12434. } break;
  12435. case LLM_ARCH_T5:
  12436. {
  12437. if (lctx.is_encoding) {
  12438. result = llm.build_t5_encoder();
  12439. } else {
  12440. result = llm.build_t5_decoder();
  12441. }
  12442. } break;
  12443. case LLM_ARCH_T5ENCODER:
  12444. {
  12445. result = llm.build_t5_encoder();
  12446. } break;
  12447. case LLM_ARCH_JAIS:
  12448. {
  12449. result = llm.build_jais();
  12450. } break;
  12451. case LLM_ARCH_NEMOTRON:
  12452. {
  12453. result = llm.build_nemotron();
  12454. } break;
  12455. case LLM_ARCH_EXAONE:
  12456. {
  12457. result = llm.build_exaone();
  12458. } break;
  12459. default:
  12460. GGML_ABORT("fatal error");
  12461. }
  12462. // add on pooling layer
  12463. if (lctx.cparams.embeddings) {
  12464. result = llm.append_pooling(result);
  12465. }
  12466. llm.free();
  12467. return result;
  12468. }
  12469. static void llama_set_k_shift(llama_context & lctx) {
  12470. const int64_t kv_size = lctx.kv_self.size;
  12471. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  12472. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  12473. for (int i = 0; i < kv_size; ++i) {
  12474. data[i] = lctx.kv_self.cells[i].delta;
  12475. }
  12476. }
  12477. static void llama_set_s_copy(llama_context & lctx) {
  12478. const int64_t kv_size = lctx.kv_self.size;
  12479. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  12480. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  12481. for (int i = 0; i < kv_size; ++i) {
  12482. data[i] = lctx.kv_self.cells[i].src;
  12483. }
  12484. }
  12485. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  12486. // TODO move to hparams if a T5 variant appears that uses a different value
  12487. const int64_t max_distance = 128;
  12488. if (bidirectional) {
  12489. n_buckets >>= 1;
  12490. }
  12491. const int64_t max_exact = n_buckets >> 1;
  12492. int32_t relative_position = x - y;
  12493. int32_t relative_bucket = 0;
  12494. if (bidirectional) {
  12495. relative_bucket += (relative_position > 0) * n_buckets;
  12496. relative_position = abs(relative_position);
  12497. } else {
  12498. relative_position = -std::min<int32_t>(relative_position, 0);
  12499. }
  12500. 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));
  12501. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  12502. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  12503. return relative_bucket;
  12504. }
  12505. static void llama_set_inputs(llama_context & lctx, const llama_ubatch & batch) {
  12506. //
  12507. // set input data
  12508. //
  12509. const auto & hparams = lctx.model.hparams;
  12510. const auto & cparams = lctx.cparams;
  12511. const auto & kv_self = lctx.kv_self;
  12512. if (batch.token) {
  12513. const int64_t n_tokens = batch.n_tokens;
  12514. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  12515. }
  12516. if (batch.embd) {
  12517. const int64_t n_embd = hparams.n_embd;
  12518. const int64_t n_tokens = batch.n_tokens;
  12519. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  12520. }
  12521. if (batch.pos && lctx.inp_pos) {
  12522. const int64_t n_tokens = batch.n_tokens;
  12523. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  12524. }
  12525. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  12526. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  12527. const int64_t n_tokens = batch.n_tokens;
  12528. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  12529. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  12530. if (lctx.n_outputs == n_tokens) {
  12531. for (int i = 0; i < n_tokens; ++i) {
  12532. data[i] = i;
  12533. }
  12534. } else if (batch.output) {
  12535. int32_t n_outputs = 0;
  12536. for (int i = 0; i < n_tokens; ++i) {
  12537. if (batch.output[i]) {
  12538. data[n_outputs++] = i;
  12539. }
  12540. }
  12541. // the graph needs to have been passed the correct number of outputs
  12542. GGML_ASSERT(lctx.n_outputs == n_outputs);
  12543. } else if (lctx.n_outputs == 1) {
  12544. // only keep last output
  12545. data[0] = n_tokens - 1;
  12546. } else {
  12547. GGML_ASSERT(lctx.n_outputs == 0);
  12548. }
  12549. }
  12550. GGML_ASSERT(
  12551. // (!a || b) is a logical implication (a -> b)
  12552. // !hparams.causal_attn -> !cparams.causal_attn
  12553. (hparams.causal_attn || !cparams.causal_attn) &&
  12554. "causal attention is not supported by this model"
  12555. );
  12556. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  12557. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  12558. if (cparams.causal_attn && !lctx.is_encoding) {
  12559. const int64_t n_kv = kv_self.n;
  12560. const int64_t n_tokens = batch.n_tokens;
  12561. const int64_t n_seq_tokens = batch.n_seq_tokens;
  12562. const int64_t n_seqs = batch.n_seqs;
  12563. float * data = nullptr;
  12564. float * data_swa = nullptr;
  12565. if (lctx.inp_KQ_mask) {
  12566. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  12567. data = (float *) lctx.inp_KQ_mask->data;
  12568. }
  12569. if (lctx.inp_KQ_mask_swa) {
  12570. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  12571. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  12572. }
  12573. // For causal attention, use only the previous KV cells
  12574. // of the correct sequence for each token of the batch.
  12575. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  12576. for (int h = 0; h < 1; ++h) {
  12577. for (int s = 0; s < n_seqs; ++s) {
  12578. const llama_seq_id seq_id = batch.seq_id[s][0];
  12579. for (int j = 0; j < n_seq_tokens; ++j) {
  12580. const llama_pos pos = batch.pos[s*n_seq_tokens + j];
  12581. for (int i = 0; i < n_kv; ++i) {
  12582. float f;
  12583. if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
  12584. f = -INFINITY;
  12585. } else {
  12586. if (hparams.use_alibi) {
  12587. f = -std::abs(kv_self.cells[i].pos - pos);
  12588. } else {
  12589. f = 0.0f;
  12590. }
  12591. }
  12592. if (data) {
  12593. data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  12594. }
  12595. // may need to cut off old tokens for sliding window
  12596. if (data_swa) {
  12597. if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  12598. f = -INFINITY;
  12599. }
  12600. data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
  12601. }
  12602. }
  12603. }
  12604. }
  12605. if (data) {
  12606. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  12607. for (int j = 0; j < n_kv; ++j) {
  12608. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  12609. }
  12610. }
  12611. }
  12612. if (data_swa) {
  12613. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  12614. for (int j = 0; j < n_kv; ++j) {
  12615. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  12616. }
  12617. }
  12618. }
  12619. }
  12620. } else {
  12621. const int64_t n_tokens = batch.n_tokens;
  12622. const int64_t n_seq_tokens = batch.n_seq_tokens;
  12623. const int64_t n_seqs = batch.n_seqs;
  12624. // when using kv cache, the mask needs to match the kv cache size
  12625. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  12626. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  12627. float * data = (float *) lctx.inp_KQ_mask->data;
  12628. for (int h = 0; h < 1; ++h) {
  12629. for (int s1 = 0; s1 < n_seqs; ++s1) {
  12630. const llama_seq_id seq_id = batch.seq_id[s1][0];
  12631. for (int j = 0; j < n_seq_tokens; ++j) {
  12632. const int32_t tj = s1*n_seq_tokens + j;
  12633. for (int s0 = 0; s0 < n_seqs; ++s0) {
  12634. for (int i = 0; i < n_seq_tokens; ++i) {
  12635. const int32_t ti = s0*n_seq_tokens + i;
  12636. float f = -INFINITY;
  12637. for (int s = 0; s < batch.n_seq_id[s0]; ++s) {
  12638. if (batch.seq_id[s0][s] == seq_id) {
  12639. if (hparams.use_alibi) {
  12640. f = -std::abs(batch.pos[ti] - batch.pos[tj]);
  12641. } else {
  12642. f = 0.0f;
  12643. }
  12644. break;
  12645. }
  12646. }
  12647. data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
  12648. }
  12649. }
  12650. for (int i = n_tokens; i < n_stride; ++i) {
  12651. data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
  12652. }
  12653. }
  12654. }
  12655. }
  12656. }
  12657. }
  12658. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  12659. const int64_t n_tokens = batch.n_tokens;
  12660. const int64_t n_seq_tokens = batch.n_seq_tokens;
  12661. const int64_t n_seqs = batch.n_seqs;
  12662. GGML_ASSERT(lctx.inp_mean);
  12663. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  12664. float * data = (float *) lctx.inp_mean->data;
  12665. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  12666. std::vector<uint64_t> sum(n_tokens, 0);
  12667. for (int s = 0; s < n_seqs; ++s) {
  12668. const llama_seq_id seq_id = batch.seq_id[s][0];
  12669. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  12670. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  12671. sum[seq_id] += batch.n_seq_tokens;
  12672. }
  12673. std::vector<float> div(n_tokens, 0.0f);
  12674. for (int i = 0; i < n_tokens; ++i) {
  12675. const uint64_t s = sum[i];
  12676. if (s > 0) {
  12677. div[i] = 1.0f/float(s);
  12678. }
  12679. }
  12680. for (int s = 0; s < n_seqs; ++s) {
  12681. const llama_seq_id seq_id = batch.seq_id[s][0];
  12682. for (int i = 0; i < n_seq_tokens; ++i) {
  12683. data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
  12684. }
  12685. }
  12686. }
  12687. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  12688. const int64_t n_tokens = batch.n_tokens;
  12689. const int64_t n_seq_tokens = batch.n_seq_tokens;
  12690. const int64_t n_seqs = batch.n_seqs;
  12691. GGML_ASSERT(lctx.inp_cls);
  12692. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  12693. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  12694. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  12695. for (int s = 0; s < n_seqs; ++s) {
  12696. const llama_seq_id seq_id = batch.seq_id[s][0];
  12697. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  12698. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  12699. for (int i = 0; i < n_seq_tokens; ++i) {
  12700. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  12701. if (pos == 0) {
  12702. data[seq_id] = s*n_seq_tokens + i;
  12703. }
  12704. }
  12705. }
  12706. }
  12707. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  12708. const int64_t n_tokens = batch.n_tokens;
  12709. const int64_t n_seq_tokens = batch.n_seq_tokens;
  12710. const int64_t n_seqs = batch.n_seqs;
  12711. GGML_ASSERT(lctx.inp_cls);
  12712. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  12713. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  12714. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  12715. std::vector<int> last_pos(n_tokens, -1);
  12716. std::vector<int> last_row(n_tokens, -1);
  12717. for (int s = 0; s < n_seqs; ++s) {
  12718. const llama_seq_id seq_id = batch.seq_id[s][0];
  12719. // TODO: adapt limits to n_seqs when batch.equal_seqs is true
  12720. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  12721. for (int i = 0; i < n_seq_tokens; ++i) {
  12722. const llama_pos pos = batch.pos[s*n_seq_tokens + i];
  12723. if (pos >= last_pos[seq_id]) {
  12724. last_pos[seq_id] = pos;
  12725. last_row[seq_id] = s*n_seq_tokens + i;
  12726. }
  12727. }
  12728. }
  12729. for (int i = 0; i < n_tokens; ++i) {
  12730. if (last_row[i] >= 0) {
  12731. data[i] = last_row[i];
  12732. }
  12733. }
  12734. }
  12735. if (kv_self.recurrent) {
  12736. const int64_t n_kv = kv_self.n;
  12737. if (lctx.inp_s_mask) {
  12738. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  12739. float * data = (float *) lctx.inp_s_mask->data;
  12740. // clear unused states
  12741. for (int i = 0; i < n_kv; ++i) {
  12742. uint32_t cell_id = i + kv_self.head;
  12743. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  12744. data[i] = (float) (kv_cell.src >= 0);
  12745. // only clear once
  12746. if (kv_cell.src < 0) {
  12747. kv_cell.src = cell_id;
  12748. }
  12749. }
  12750. }
  12751. if (lctx.inp_s_copy) {
  12752. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  12753. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  12754. // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
  12755. for (uint32_t i = 0; i < n_kv; ++i) {
  12756. const uint32_t cell_id = i + kv_self.head;
  12757. llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
  12758. // prevent out-of-bound sources
  12759. if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
  12760. kv_cell.src = cell_id;
  12761. }
  12762. data[i] = kv_cell.src;
  12763. // ensure copy only happens once
  12764. if (kv_cell.src != (int32_t) cell_id) {
  12765. kv_cell.src = cell_id;
  12766. }
  12767. }
  12768. }
  12769. }
  12770. if (lctx.inp_pos_bucket) {
  12771. const int64_t n_tokens = batch.n_tokens;
  12772. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  12773. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  12774. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  12775. if (!lctx.is_encoding) {
  12776. const int64_t n_kv = kv_self.n;
  12777. for (int h = 0; h < 1; ++h) {
  12778. for (int j = 0; j < n_tokens; ++j) {
  12779. for (int i = 0; i < n_kv; ++i) {
  12780. 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);
  12781. }
  12782. }
  12783. }
  12784. } else {
  12785. for (int h = 0; h < 1; ++h) {
  12786. for (int j = 0; j < n_tokens; ++j) {
  12787. for (int i = 0; i < n_tokens; ++i) {
  12788. 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);
  12789. }
  12790. }
  12791. }
  12792. }
  12793. }
  12794. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  12795. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  12796. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  12797. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  12798. }
  12799. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  12800. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  12801. const int64_t n_tokens = batch.n_tokens;
  12802. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  12803. GGML_ASSERT(!batch.equal_seqs); // TODO: use batch.n_seqs instead of failing
  12804. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  12805. for (int h = 0; h < 1; ++h) {
  12806. for (int j = 0; j < n_tokens; ++j) {
  12807. for (int i = 0; i < n_output_enc; ++i) {
  12808. float f = -INFINITY;
  12809. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  12810. const llama_seq_id seq_id = batch.seq_id[j][s];
  12811. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  12812. f = 0.0f;
  12813. }
  12814. }
  12815. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  12816. }
  12817. }
  12818. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  12819. for (int j = 0; j < n_output_enc; ++j) {
  12820. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  12821. }
  12822. }
  12823. }
  12824. }
  12825. }
  12826. // Make sure enough space is available for outputs.
  12827. // Returns max number of outputs for which space was reserved.
  12828. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  12829. const auto & cparams = lctx.cparams;
  12830. const auto & hparams = lctx.model.hparams;
  12831. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  12832. const auto n_batch = cparams.n_batch;
  12833. const auto n_vocab = hparams.n_vocab;
  12834. const auto n_embd = hparams.n_embd;
  12835. // TODO: use a per-batch flag for logits presence instead
  12836. const bool has_logits = !cparams.embeddings;
  12837. const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  12838. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  12839. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  12840. if (lctx.output_ids.empty()) {
  12841. // init, never resized afterwards
  12842. lctx.output_ids.resize(n_batch);
  12843. }
  12844. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  12845. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  12846. // alloc only when more than the current capacity is required
  12847. // TODO: also consider shrinking the buffer
  12848. if (!lctx.buf_output || prev_size < new_size) {
  12849. if (lctx.buf_output) {
  12850. #ifndef NDEBUG
  12851. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  12852. 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);
  12853. #endif
  12854. ggml_backend_buffer_free(lctx.buf_output);
  12855. lctx.buf_output = nullptr;
  12856. lctx.logits = nullptr;
  12857. lctx.embd = nullptr;
  12858. }
  12859. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  12860. if (lctx.buf_output == nullptr) {
  12861. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  12862. return 0;
  12863. }
  12864. }
  12865. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  12866. lctx.logits = has_logits ? output_base : nullptr;
  12867. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  12868. lctx.output_size = n_outputs_max;
  12869. lctx.logits_size = logits_size;
  12870. lctx.embd_size = embd_size;
  12871. // set all ids as invalid (negative)
  12872. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  12873. ggml_backend_buffer_clear(lctx.buf_output, 0);
  12874. lctx.n_outputs = 0;
  12875. return n_outputs_max;
  12876. }
  12877. // make the outputs have the same order they had in the user-provided batch
  12878. static void llama_output_reorder(struct llama_context * ctx) {
  12879. std::vector<size_t> & out_ids = ctx->sbatch.out_ids;
  12880. if (!out_ids.empty()) {
  12881. uint32_t n_vocab = ctx->model.hparams.n_vocab;
  12882. uint32_t n_embd = ctx->model.hparams.n_embd;
  12883. int32_t n_outputs = ctx->n_outputs;
  12884. GGML_ASSERT((size_t) n_outputs == out_ids.size());
  12885. // TODO: is there something more efficient which also minimizes swaps?
  12886. // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
  12887. for (int32_t i = 0; i < n_outputs - 1; ++i) {
  12888. int32_t j_min = i;
  12889. for (int32_t j = i + 1; j < n_outputs; ++j) {
  12890. if (out_ids[j] < out_ids[j_min]) {
  12891. j_min = j;
  12892. }
  12893. }
  12894. if (j_min == i) { continue; }
  12895. std::swap(out_ids[i], out_ids[j_min]);
  12896. if (ctx->logits_size > 0) {
  12897. for (uint32_t k = 0; k < n_vocab; k++) {
  12898. std::swap(ctx->logits[i*n_vocab + k], ctx->logits[j_min*n_vocab + k]);
  12899. }
  12900. }
  12901. if (ctx->embd_size > 0) {
  12902. for (uint32_t k = 0; k < n_embd; k++) {
  12903. std::swap(ctx->embd[i*n_embd + k], ctx->embd[j_min*n_embd + k]);
  12904. }
  12905. }
  12906. }
  12907. std::fill(ctx->output_ids.begin(), ctx->output_ids.end(), -1);
  12908. for (int32_t i = 0; i < n_outputs; ++i) {
  12909. ctx->output_ids[out_ids[i]] = i;
  12910. }
  12911. out_ids.clear();
  12912. }
  12913. }
  12914. static void llama_graph_compute(
  12915. llama_context & lctx,
  12916. ggml_cgraph * gf,
  12917. int n_threads) {
  12918. #ifdef GGML_USE_METAL
  12919. if (ggml_backend_is_metal(lctx.backend_metal)) {
  12920. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  12921. }
  12922. #endif
  12923. if (lctx.backend_cpu != nullptr) {
  12924. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  12925. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  12926. }
  12927. #ifdef GGML_USE_BLAS
  12928. if (lctx.backend_blas != nullptr) {
  12929. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  12930. }
  12931. #endif
  12932. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  12933. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  12934. }
  12935. // decode a batch of tokens by evaluating the transformer
  12936. //
  12937. // - lctx: llama context
  12938. // - batch: batch to evaluate
  12939. //
  12940. // return 0 on success
  12941. // return positive int on warning
  12942. // return negative int on error
  12943. //
  12944. static int llama_decode_internal(
  12945. llama_context & lctx,
  12946. llama_batch batch_all) { // TODO: rename back to batch
  12947. lctx.is_encoding = false;
  12948. const uint32_t n_tokens_all = batch_all.n_tokens;
  12949. if (n_tokens_all == 0) {
  12950. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  12951. return -1;
  12952. }
  12953. const auto & model = lctx.model;
  12954. const auto & hparams = model.hparams;
  12955. const auto & cparams = lctx.cparams;
  12956. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  12957. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  12958. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  12959. if (lctx.t_compute_start_us == 0) {
  12960. lctx.t_compute_start_us = ggml_time_us();
  12961. }
  12962. lctx.n_queued_tokens += n_tokens_all;
  12963. auto & kv_self = lctx.kv_self;
  12964. const int64_t n_embd = hparams.n_embd;
  12965. const int64_t n_vocab = hparams.n_vocab;
  12966. uint32_t n_outputs = 0;
  12967. uint32_t n_outputs_prev = 0;
  12968. const auto n_ubatch = cparams.n_ubatch;
  12969. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  12970. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  12971. lctx.embd_seq.clear();
  12972. // count outputs
  12973. if (batch_all.logits && !embd_pooled) {
  12974. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12975. n_outputs += batch_all.logits[i] != 0;
  12976. }
  12977. } else if (lctx.logits_all || embd_pooled) {
  12978. n_outputs = n_tokens_all;
  12979. } else {
  12980. // keep last output only
  12981. n_outputs = 1;
  12982. }
  12983. lctx.sbatch.from_batch(batch_all, n_embd,
  12984. /* simple_split */ !kv_self.recurrent,
  12985. /* logits_all */ n_outputs == n_tokens_all);
  12986. // reserve output buffer
  12987. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  12988. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  12989. return -2;
  12990. };
  12991. while (lctx.sbatch.n_tokens > 0) {
  12992. llama_ubatch ubatch;
  12993. if (kv_self.recurrent) {
  12994. if (embd_pooled) {
  12995. // Pooled embeddings cannot be split across ubatches (yet)
  12996. ubatch = lctx.sbatch.split_seq(n_ubatch);
  12997. } else {
  12998. // recurrent model architectures are easier to implement
  12999. // with equal-length sequences
  13000. ubatch = lctx.sbatch.split_equal(n_ubatch);
  13001. }
  13002. } else {
  13003. ubatch = lctx.sbatch.split_simple(n_ubatch);
  13004. }
  13005. const uint32_t n_tokens = ubatch.n_tokens;
  13006. // count the outputs in this u_batch
  13007. {
  13008. int32_t n_outputs_new = 0;
  13009. if (n_outputs == n_tokens_all) {
  13010. n_outputs_new = n_tokens;
  13011. } else {
  13012. GGML_ASSERT(ubatch.output);
  13013. for (uint32_t i = 0; i < n_tokens; i++) {
  13014. n_outputs_new += (int32_t) (ubatch.output[i] != 0);
  13015. }
  13016. }
  13017. // needs to happen before the graph is built
  13018. lctx.n_outputs = n_outputs_new;
  13019. }
  13020. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  13021. GGML_ASSERT(n_threads > 0);
  13022. // non-causal masks do not use the KV cache
  13023. if (hparams.causal_attn) {
  13024. llama_kv_cache_update(&lctx);
  13025. // if we have enough unused cells before the current head ->
  13026. // better to start searching from the beginning of the cache, hoping to fill it
  13027. if (kv_self.head > kv_self.used + 2*n_tokens) {
  13028. kv_self.head = 0;
  13029. }
  13030. if (!llama_kv_cache_find_slot(kv_self, ubatch)) {
  13031. return 1;
  13032. }
  13033. if (!kv_self.recurrent) {
  13034. // a heuristic, to avoid attending the full cache if it is not yet utilized
  13035. // after enough generations, the benefit from this heuristic disappears
  13036. // if we start defragmenting the cache, the benefit from this will be more important
  13037. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  13038. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  13039. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  13040. }
  13041. }
  13042. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  13043. ggml_backend_sched_reset(lctx.sched);
  13044. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  13045. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  13046. // the output is always the last tensor in the graph
  13047. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  13048. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  13049. if (lctx.n_outputs == 0) {
  13050. // no output
  13051. res = nullptr;
  13052. embd = nullptr;
  13053. } else if (cparams.embeddings) {
  13054. res = nullptr; // do not extract logits for embedding case
  13055. embd = nullptr;
  13056. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  13057. if (strcmp(gf->nodes[i]->name, "result_embd_pooled") == 0) {
  13058. embd = gf->nodes[i];
  13059. break;
  13060. }
  13061. }
  13062. GGML_ASSERT(embd != nullptr && "missing embeddings tensor");
  13063. } else {
  13064. embd = nullptr; // do not extract embeddings when not needed
  13065. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  13066. }
  13067. // 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);
  13068. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  13069. llama_set_inputs(lctx, ubatch);
  13070. llama_graph_compute(lctx, gf, n_threads);
  13071. // update the kv ring buffer
  13072. {
  13073. kv_self.head += n_tokens;
  13074. // Ensure kv cache head points to a valid index.
  13075. if (kv_self.head >= kv_self.size) {
  13076. kv_self.head = 0;
  13077. }
  13078. }
  13079. // plot the computation graph in dot format (for debugging purposes)
  13080. //if (n_past%100 == 0) {
  13081. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  13082. //}
  13083. // extract logits
  13084. if (res) {
  13085. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  13086. GGML_ASSERT(backend_res != nullptr);
  13087. GGML_ASSERT(lctx.logits != nullptr);
  13088. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  13089. const int32_t n_outputs_new = lctx.n_outputs;
  13090. if (n_outputs_new) {
  13091. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  13092. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  13093. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  13094. }
  13095. }
  13096. // extract embeddings
  13097. if (embd) {
  13098. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  13099. GGML_ASSERT(backend_embd != nullptr);
  13100. switch (cparams.pooling_type) {
  13101. case LLAMA_POOLING_TYPE_NONE:
  13102. {
  13103. // extract token embeddings
  13104. GGML_ASSERT(lctx.embd != nullptr);
  13105. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  13106. const int32_t n_outputs_new = lctx.n_outputs;
  13107. if (n_outputs_new) {
  13108. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  13109. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  13110. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  13111. }
  13112. } break;
  13113. case LLAMA_POOLING_TYPE_MEAN:
  13114. case LLAMA_POOLING_TYPE_CLS:
  13115. case LLAMA_POOLING_TYPE_LAST:
  13116. {
  13117. // extract sequence embeddings (cleared before processing each batch)
  13118. auto & embd_seq_out = lctx.embd_seq;
  13119. for (uint32_t s = 0; s < ubatch.n_seqs; ++s) {
  13120. const llama_seq_id seq_id = ubatch.seq_id[s][0];
  13121. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  13122. continue;
  13123. }
  13124. embd_seq_out[seq_id].resize(n_embd);
  13125. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  13126. }
  13127. } break;
  13128. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  13129. {
  13130. GGML_ABORT("unknown pooling type");
  13131. }
  13132. }
  13133. }
  13134. n_outputs_prev += lctx.n_outputs;
  13135. }
  13136. // set output mappings
  13137. {
  13138. bool sorted_output = true;
  13139. GGML_ASSERT(lctx.sbatch.out_ids.size() == n_outputs);
  13140. for (size_t i = 0; i < n_outputs; ++i) {
  13141. size_t out_id = lctx.sbatch.out_ids[i];
  13142. lctx.output_ids[out_id] = i;
  13143. if (out_id != i) {
  13144. sorted_output = false;
  13145. }
  13146. }
  13147. if (sorted_output) {
  13148. lctx.sbatch.out_ids.clear();
  13149. }
  13150. }
  13151. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  13152. lctx.n_outputs = n_outputs;
  13153. // wait for the computation to finish (automatically done when obtaining the model output)
  13154. //llama_synchronize(&lctx);
  13155. // decide if we need to defrag the kv cache
  13156. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  13157. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  13158. // queue defragmentation for next llama_kv_cache_update
  13159. if (fragmentation > cparams.defrag_thold) {
  13160. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  13161. llama_kv_cache_defrag(kv_self);
  13162. }
  13163. }
  13164. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  13165. // overlap with device computation.
  13166. ggml_backend_sched_reset(lctx.sched);
  13167. return 0;
  13168. }
  13169. // encode a batch of tokens by evaluating the encoder part of the transformer
  13170. //
  13171. // - lctx: llama context
  13172. // - batch: batch to evaluate
  13173. //
  13174. // return 0 on success
  13175. // return positive int on warning
  13176. // return negative int on error
  13177. //
  13178. static int llama_encode_internal(
  13179. llama_context & lctx,
  13180. llama_batch batch) {
  13181. lctx.is_encoding = true;
  13182. const uint32_t n_tokens = batch.n_tokens;
  13183. if (n_tokens == 0) {
  13184. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  13185. return -1;
  13186. }
  13187. const auto & model = lctx.model;
  13188. const auto & hparams = model.hparams;
  13189. const auto & cparams = lctx.cparams;
  13190. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  13191. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  13192. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  13193. if (lctx.t_compute_start_us == 0) {
  13194. lctx.t_compute_start_us = ggml_time_us();
  13195. }
  13196. lctx.n_queued_tokens += n_tokens;
  13197. const int64_t n_embd = hparams.n_embd;
  13198. lctx.sbatch.from_batch(batch, n_embd, /* simple_split */ true, /* logits_all */ true);
  13199. const llama_ubatch ubatch = lctx.sbatch.split_simple(n_tokens);
  13200. // reserve output buffer
  13201. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  13202. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  13203. return -2;
  13204. };
  13205. for (uint32_t i = 0; i < n_tokens; ++i) {
  13206. lctx.output_ids[i] = i;
  13207. }
  13208. lctx.inp_embd_enc = NULL;
  13209. lctx.n_outputs = n_tokens;
  13210. const int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  13211. GGML_ASSERT(n_threads > 0);
  13212. ggml_backend_sched_reset(lctx.sched);
  13213. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  13214. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, false);
  13215. // the output embeddings after the final encoder normalization
  13216. struct ggml_tensor * embd = nullptr;
  13217. // there are two cases here
  13218. if (llama_model_has_decoder(&lctx.model)) {
  13219. // first case is an encoder-decoder T5 model where embeddings are passed to decoder
  13220. embd = gf->nodes[gf->n_nodes - 1];
  13221. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0 && "missing result_output tensor");
  13222. } else {
  13223. // second case is an encoder-only T5 model
  13224. if (cparams.embeddings) {
  13225. // only output embeddings if required
  13226. embd = gf->nodes[gf->n_nodes - 1];
  13227. if (strcmp(embd->name, "result_embd_pooled") != 0) {
  13228. embd = gf->nodes[gf->n_nodes - 2];
  13229. }
  13230. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  13231. }
  13232. }
  13233. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  13234. llama_set_inputs(lctx, ubatch);
  13235. llama_graph_compute(lctx, gf, n_threads);
  13236. // extract embeddings
  13237. if (embd) {
  13238. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  13239. GGML_ASSERT(backend_embd != nullptr);
  13240. if (llama_model_has_decoder(&lctx.model)) {
  13241. lctx.embd_enc.resize(n_tokens*n_embd);
  13242. float * embd_out = lctx.embd_enc.data();
  13243. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  13244. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  13245. // remember the sequence ids used during the encoding - needed for cross attention later
  13246. lctx.seq_ids_enc.resize(n_tokens);
  13247. for (uint32_t i = 0; i < n_tokens; i++) {
  13248. for (int s = 0; s < ubatch.n_seq_id[i]; s++) {
  13249. llama_seq_id seq_id = ubatch.seq_id[i][s];
  13250. lctx.seq_ids_enc[i].insert(seq_id);
  13251. }
  13252. }
  13253. } else {
  13254. GGML_ASSERT(lctx.embd != nullptr);
  13255. switch (cparams.pooling_type) {
  13256. case LLAMA_POOLING_TYPE_NONE:
  13257. {
  13258. // extract token embeddings
  13259. GGML_ASSERT(lctx.embd != nullptr);
  13260. float * embd_out = lctx.embd;
  13261. GGML_ASSERT(n_tokens*n_embd <= (int64_t) lctx.embd_size);
  13262. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  13263. } break;
  13264. case LLAMA_POOLING_TYPE_MEAN:
  13265. case LLAMA_POOLING_TYPE_CLS:
  13266. case LLAMA_POOLING_TYPE_LAST:
  13267. {
  13268. // extract sequence embeddings
  13269. auto & embd_seq_out = lctx.embd_seq;
  13270. embd_seq_out.clear();
  13271. GGML_ASSERT(!ubatch.equal_seqs); // TODO: handle equal splits
  13272. for (uint32_t i = 0; i < n_tokens; i++) {
  13273. const llama_seq_id seq_id = ubatch.seq_id[i][0];
  13274. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  13275. continue;
  13276. }
  13277. embd_seq_out[seq_id].resize(n_embd);
  13278. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  13279. }
  13280. } break;
  13281. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  13282. {
  13283. GGML_ABORT("unknown pooling type");
  13284. }
  13285. }
  13286. }
  13287. }
  13288. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  13289. // overlap with device computation.
  13290. ggml_backend_sched_reset(lctx.sched);
  13291. return 0;
  13292. }
  13293. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  13294. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  13295. auto & kv_self = lctx.kv_self;
  13296. const auto & hparams = lctx.model.hparams;
  13297. const uint32_t n_layer = hparams.n_layer;
  13298. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  13299. const uint32_t n_used = kv_self.used;
  13300. assert(n_used <= n_kv);
  13301. //const int64_t t_start = ggml_time_us();
  13302. // number of cells moved
  13303. uint32_t n_moves = 0;
  13304. // each move requires 6*n_layer tensors (see build_defrag)
  13305. // - source view, destination view, copy operation
  13306. // - x2 for keys and values
  13307. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  13308. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  13309. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  13310. // determine which KV cells to move where
  13311. //
  13312. // cell i moves to ids[i]
  13313. //
  13314. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  13315. //
  13316. std::vector<uint32_t> ids(n_kv, n_kv);
  13317. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  13318. const auto & cell0 = kv_self.cells[i0];
  13319. if (!cell0.is_empty()) {
  13320. ids[i0] = i0;
  13321. continue;
  13322. }
  13323. // found a hole - fill it with data from the end of the cache
  13324. uint32_t nh = 1;
  13325. // determine the size of the hole
  13326. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  13327. nh++;
  13328. }
  13329. uint32_t nf = 0;
  13330. uint32_t is = n_kv - 1;
  13331. // starting from the end, find nh non-empty cells
  13332. for (; is > i0; --is) {
  13333. const auto & cell1 = kv_self.cells[is];
  13334. if (cell1.is_empty() || ids[is] != n_kv) {
  13335. continue;
  13336. }
  13337. // non-empty cell which is not yet moved
  13338. nf++;
  13339. if (nf == nh) {
  13340. break;
  13341. }
  13342. }
  13343. // this can only happen if `n_used` is not accurate, which would be a bug
  13344. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  13345. nf = 0;
  13346. uint32_t i1 = is;
  13347. // are we moving a continuous block of memory?
  13348. bool cont = false;
  13349. // should we stop searching for the next move?
  13350. bool stop = false;
  13351. // go back and move the nf cells to the hole
  13352. for (; i1 < n_kv; ++i1) {
  13353. auto & cell1 = kv_self.cells[i1];
  13354. if (cell1.is_empty() || ids[i1] != n_kv) {
  13355. if (n_moves == max_moves) {
  13356. stop = true;
  13357. break;
  13358. }
  13359. cont = false;
  13360. continue;
  13361. }
  13362. // this cell goes to (i0 + nf)
  13363. ids[i1] = i0 + nf;
  13364. // move the cell meta data
  13365. kv_self.cells[i0 + nf] = cell1;
  13366. // clear the old cell and move the head there
  13367. cell1 = llama_kv_cell();
  13368. kv_self.head = n_used;
  13369. if (!cont) {
  13370. n_moves++;
  13371. cont = true;
  13372. }
  13373. nf++;
  13374. if (nf == nh) {
  13375. break;
  13376. }
  13377. }
  13378. if (stop || n_moves == max_moves) {
  13379. break;
  13380. }
  13381. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  13382. i0 += nh - 1;
  13383. }
  13384. if (n_moves == 0) {
  13385. return;
  13386. }
  13387. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  13388. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  13389. #if 0
  13390. // CPU defrag
  13391. //
  13392. // TODO: optimizations are possible:
  13393. // - multiple threads
  13394. // - avoid copying to the host memory when already there
  13395. //
  13396. // likely not worth the effort, as we have ggml_graph based defrag
  13397. //
  13398. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  13399. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  13400. const uint32_t kv_size = kv_self.size;
  13401. std::vector<uint8_t> buf_k;
  13402. std::vector<uint8_t> buf_v;
  13403. for (uint32_t il = 0; il < n_layer; ++il) {
  13404. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13405. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  13406. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13407. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  13408. buf_k.resize(k_size);
  13409. buf_v.resize(v_size);
  13410. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  13411. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  13412. // batch move [i, i+nm) to [id, id+nm)
  13413. // note: cells can move only to a lower index
  13414. for (uint32_t i = 0; i < n_kv; ++i) {
  13415. const uint32_t id = ids[i];
  13416. if (i == id || id == n_kv) {
  13417. continue;
  13418. }
  13419. uint32_t nm = 1;
  13420. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  13421. nm++;
  13422. }
  13423. // move keys
  13424. {
  13425. const int64_t os = i*k_size_row;
  13426. const int64_t od = id*k_size_row;
  13427. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  13428. }
  13429. // move values (note: they are transposed)
  13430. {
  13431. const int64_t os = i;
  13432. const int64_t od = id;
  13433. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13434. 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);
  13435. }
  13436. }
  13437. i += nm - 1;
  13438. }
  13439. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  13440. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  13441. }
  13442. #else
  13443. // ggml_graph defrag
  13444. ggml_backend_sched_reset(lctx.sched);
  13445. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  13446. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  13447. #endif
  13448. //const int64_t t_end = ggml_time_us();
  13449. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  13450. }
  13451. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  13452. bool need_reserve = false;
  13453. // apply K-shift if needed
  13454. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  13455. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  13456. GGML_ABORT("Deepseek2 does not support K-shift");
  13457. }
  13458. {
  13459. ggml_backend_sched_reset(lctx.sched);
  13460. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  13461. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  13462. llama_set_k_shift(lctx);
  13463. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  13464. need_reserve = true;
  13465. }
  13466. {
  13467. auto & kv_self = lctx.kv_self;
  13468. kv_self.has_shift = false;
  13469. for (uint32_t i = 0; i < kv_self.size; ++i) {
  13470. kv_self.cells[i].delta = 0;
  13471. }
  13472. }
  13473. }
  13474. // defragment the KV cache if needed
  13475. if (lctx.kv_self.do_defrag) {
  13476. llama_kv_cache_defrag_internal(lctx);
  13477. need_reserve = true;
  13478. lctx.kv_self.do_defrag = false;
  13479. }
  13480. // reserve a worst case graph again
  13481. if (need_reserve) {
  13482. // TODO: extract to a function
  13483. // build worst-case graph
  13484. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  13485. uint32_t n_tokens = std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  13486. 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
  13487. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  13488. ggml_cgraph * gf = llama_build_graph(lctx, ubatch, true);
  13489. // initialize scheduler with the worst-case graph
  13490. ggml_backend_sched_reset(lctx.sched);
  13491. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  13492. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  13493. }
  13494. }
  13495. }
  13496. //
  13497. // quantization
  13498. //
  13499. struct quantize_state_internal {
  13500. const llama_model & model;
  13501. const llama_model_quantize_params * params;
  13502. int n_attention_wv = 0;
  13503. int n_ffn_down = 0;
  13504. int n_ffn_gate = 0;
  13505. int n_ffn_up = 0;
  13506. int i_attention_wv = 0;
  13507. int i_ffn_down = 0;
  13508. int i_ffn_gate = 0;
  13509. int i_ffn_up = 0;
  13510. int n_k_quantized = 0;
  13511. int n_fallback = 0;
  13512. bool has_imatrix = false;
  13513. // used to figure out if a model shares tok_embd with the output weight
  13514. bool has_output = false;
  13515. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  13516. : model(model)
  13517. , params(params)
  13518. {}
  13519. };
  13520. static void llama_tensor_dequantize_internal(
  13521. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  13522. const size_t nelements, const int nthread
  13523. ) {
  13524. if (output.size() < nelements) {
  13525. output.resize(nelements);
  13526. }
  13527. float * f32_output = (float *) output.data();
  13528. ggml_type_traits_t qtype;
  13529. if (ggml_is_quantized(tensor->type)) {
  13530. qtype = ggml_internal_get_type_traits(tensor->type);
  13531. if (qtype.to_float == NULL) {
  13532. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  13533. }
  13534. } else if (tensor->type != GGML_TYPE_F16 &&
  13535. tensor->type != GGML_TYPE_BF16) {
  13536. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  13537. }
  13538. if (nthread < 2) {
  13539. if (tensor->type == GGML_TYPE_F16) {
  13540. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  13541. } else if (tensor->type == GGML_TYPE_BF16) {
  13542. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  13543. } else if (ggml_is_quantized(tensor->type)) {
  13544. qtype.to_float(tensor->data, f32_output, nelements);
  13545. } else {
  13546. GGML_ABORT("fatal error"); // unreachable
  13547. }
  13548. return;
  13549. }
  13550. size_t block_size;
  13551. if (tensor->type == GGML_TYPE_F16 ||
  13552. tensor->type == GGML_TYPE_BF16) {
  13553. block_size = 1;
  13554. } else {
  13555. block_size = (size_t)ggml_blck_size(tensor->type);
  13556. }
  13557. size_t block_size_bytes = ggml_type_size(tensor->type);
  13558. GGML_ASSERT(nelements % block_size == 0);
  13559. size_t nblocks = nelements / block_size;
  13560. size_t blocks_per_thread = nblocks / nthread;
  13561. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  13562. size_t in_buff_offs = 0;
  13563. size_t out_buff_offs = 0;
  13564. for (int tnum = 0; tnum < nthread; tnum++) {
  13565. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  13566. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  13567. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  13568. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  13569. if (typ == GGML_TYPE_F16) {
  13570. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  13571. } else if (typ == GGML_TYPE_BF16) {
  13572. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  13573. } else {
  13574. qtype.to_float(inbuf, outbuf, nels);
  13575. }
  13576. };
  13577. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  13578. in_buff_offs += thr_block_bytes;
  13579. out_buff_offs += thr_elems;
  13580. }
  13581. for (auto & w : workers) { w.join(); }
  13582. workers.clear();
  13583. }
  13584. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  13585. const std::string name = ggml_get_name(tensor);
  13586. // TODO: avoid hardcoded tensor names - use the TN_* constants
  13587. const llm_arch arch = qs.model.arch;
  13588. const auto tn = LLM_TN(arch);
  13589. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  13590. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  13591. };
  13592. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  13593. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  13594. if (n_expert > 1) {
  13595. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly
  13596. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  13597. // for getting the current layer as I initially thought, and we need to resort to parsing the
  13598. // tensor name.
  13599. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  13600. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  13601. }
  13602. if (i_layer < 0 || i_layer >= n_layer) {
  13603. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  13604. }
  13605. }
  13606. return std::make_pair(i_layer, n_layer);
  13607. };
  13608. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  13609. // with the quantization of the output tensor
  13610. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  13611. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  13612. new_type = qs.params->output_tensor_type;
  13613. } else {
  13614. int nx = tensor->ne[0];
  13615. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  13616. new_type = GGML_TYPE_Q8_0;
  13617. }
  13618. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  13619. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  13620. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  13621. new_type = GGML_TYPE_Q5_K;
  13622. }
  13623. else if (new_type != GGML_TYPE_Q8_0) {
  13624. new_type = GGML_TYPE_Q6_K;
  13625. }
  13626. }
  13627. } else if (name == "token_embd.weight") {
  13628. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  13629. new_type = qs.params->token_embedding_type;
  13630. } else {
  13631. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  13632. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  13633. new_type = GGML_TYPE_Q2_K;
  13634. }
  13635. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  13636. new_type = GGML_TYPE_IQ3_S;
  13637. }
  13638. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  13639. new_type = GGML_TYPE_IQ3_S;
  13640. }
  13641. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  13642. new_type == GGML_TYPE_Q4_0_8_8) {
  13643. new_type = GGML_TYPE_Q4_0;
  13644. }
  13645. }
  13646. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  13647. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  13648. if (name.find("attn_v.weight") != std::string::npos) {
  13649. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  13650. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  13651. ++qs.i_attention_wv;
  13652. }
  13653. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  13654. new_type = GGML_TYPE_Q4_K;
  13655. }
  13656. else if (name.find("ffn_down") != std::string::npos) {
  13657. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  13658. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  13659. }
  13660. ++qs.i_ffn_down;
  13661. }
  13662. else if (name.find("attn_output.weight") != std::string::npos) {
  13663. if (qs.model.hparams.n_expert == 8) {
  13664. new_type = GGML_TYPE_Q5_K;
  13665. } else {
  13666. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  13667. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  13668. }
  13669. }
  13670. } else if (name.find("attn_v.weight") != std::string::npos) {
  13671. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  13672. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  13673. }
  13674. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  13675. new_type = GGML_TYPE_Q4_K;
  13676. }
  13677. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  13678. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  13679. }
  13680. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  13681. new_type = GGML_TYPE_Q4_K;
  13682. }
  13683. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  13684. new_type = GGML_TYPE_Q4_K;
  13685. }
  13686. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  13687. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  13688. }
  13689. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  13690. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  13691. new_type = GGML_TYPE_Q5_K;
  13692. }
  13693. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  13694. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  13695. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  13696. if (qs.model.type == MODEL_70B) {
  13697. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  13698. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  13699. // nearly negligible increase in model size by quantizing this tensor with more bits:
  13700. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  13701. }
  13702. if (qs.model.hparams.n_expert == 8) {
  13703. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  13704. // TODO: explore better strategies
  13705. new_type = GGML_TYPE_Q8_0;
  13706. }
  13707. ++qs.i_attention_wv;
  13708. } else if (name.find("attn_k.weight") != std::string::npos) {
  13709. if (qs.model.hparams.n_expert == 8) {
  13710. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  13711. // TODO: explore better strategies
  13712. new_type = GGML_TYPE_Q8_0;
  13713. }
  13714. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  13715. new_type = GGML_TYPE_IQ3_XXS;
  13716. }
  13717. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  13718. new_type = GGML_TYPE_IQ2_S;
  13719. }
  13720. } else if (name.find("attn_q.weight") != std::string::npos) {
  13721. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  13722. new_type = GGML_TYPE_IQ3_XXS;
  13723. }
  13724. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  13725. new_type = GGML_TYPE_IQ2_S;
  13726. }
  13727. } else if (name.find("ffn_down") != std::string::npos) {
  13728. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  13729. int i_layer = info.first, n_layer = info.second;
  13730. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  13731. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  13732. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  13733. }
  13734. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  13735. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  13736. }
  13737. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  13738. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  13739. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  13740. : GGML_TYPE_Q3_K;
  13741. }
  13742. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  13743. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  13744. new_type = GGML_TYPE_Q4_K;
  13745. }
  13746. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  13747. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  13748. }
  13749. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  13750. if (arch == LLM_ARCH_FALCON) {
  13751. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  13752. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  13753. } else {
  13754. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  13755. }
  13756. }
  13757. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  13758. new_type = GGML_TYPE_Q5_K;
  13759. }
  13760. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  13761. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  13762. new_type = GGML_TYPE_Q5_K;
  13763. }
  13764. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  13765. && qs.has_imatrix && i_layer < n_layer/8) {
  13766. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  13767. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  13768. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  13769. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  13770. }
  13771. ++qs.i_ffn_down;
  13772. } else if (name.find("attn_output.weight") != std::string::npos) {
  13773. if (arch != LLM_ARCH_FALCON) {
  13774. if (qs.model.hparams.n_expert == 8) {
  13775. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  13776. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  13777. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  13778. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  13779. new_type = GGML_TYPE_Q5_K;
  13780. }
  13781. } else {
  13782. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  13783. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  13784. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  13785. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  13786. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  13787. }
  13788. } else {
  13789. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  13790. }
  13791. }
  13792. else if (name.find("attn_qkv.weight") != std::string::npos) {
  13793. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  13794. new_type = GGML_TYPE_Q4_K;
  13795. }
  13796. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  13797. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  13798. }
  13799. else if (name.find("ffn_gate") != std::string::npos) {
  13800. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  13801. int i_layer = info.first, n_layer = info.second;
  13802. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  13803. new_type = GGML_TYPE_IQ3_XXS;
  13804. }
  13805. ++qs.i_ffn_gate;
  13806. }
  13807. else if (name.find("ffn_up") != std::string::npos) {
  13808. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  13809. int i_layer = info.first, n_layer = info.second;
  13810. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  13811. new_type = GGML_TYPE_IQ3_XXS;
  13812. }
  13813. ++qs.i_ffn_up;
  13814. }
  13815. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  13816. //}
  13817. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  13818. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  13819. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  13820. //}
  13821. // This can be used to reduce the size of the Q5_K_S model.
  13822. // The associated PPL increase is fully in line with the size reduction
  13823. //else {
  13824. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  13825. //}
  13826. bool convert_incompatible_tensor = false;
  13827. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  13828. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  13829. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  13830. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  13831. new_type == GGML_TYPE_IQ1_M) {
  13832. int nx = tensor->ne[0];
  13833. int ny = tensor->ne[1];
  13834. if (nx % QK_K != 0) {
  13835. 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));
  13836. convert_incompatible_tensor = true;
  13837. } else {
  13838. ++qs.n_k_quantized;
  13839. }
  13840. }
  13841. if (convert_incompatible_tensor) {
  13842. switch (new_type) {
  13843. case GGML_TYPE_IQ2_XXS:
  13844. case GGML_TYPE_IQ2_XS:
  13845. case GGML_TYPE_IQ2_S:
  13846. case GGML_TYPE_IQ3_XXS:
  13847. case GGML_TYPE_IQ3_S:
  13848. case GGML_TYPE_IQ1_S:
  13849. case GGML_TYPE_IQ1_M:
  13850. case GGML_TYPE_Q2_K:
  13851. case GGML_TYPE_Q3_K:
  13852. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  13853. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  13854. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  13855. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  13856. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  13857. }
  13858. if (tensor->ne[0] % ggml_blck_size(new_type) != 0) {
  13859. new_type = GGML_TYPE_F16;
  13860. }
  13861. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  13862. ++qs.n_fallback;
  13863. }
  13864. return new_type;
  13865. }
  13866. 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) {
  13867. if (nthread < 2) {
  13868. // single-thread
  13869. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  13870. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  13871. throw std::runtime_error("quantized data validation failed");
  13872. }
  13873. return new_size;
  13874. }
  13875. std::mutex mutex;
  13876. int64_t counter = 0;
  13877. size_t new_size = 0;
  13878. bool valid = true;
  13879. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  13880. nrows, n_per_row, imatrix]() {
  13881. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  13882. size_t local_size = 0;
  13883. while (true) {
  13884. std::unique_lock<std::mutex> lock(mutex);
  13885. int64_t first_row = counter; counter += nrows_per_chunk;
  13886. if (first_row >= nrows) {
  13887. if (local_size > 0) {
  13888. new_size += local_size;
  13889. }
  13890. break;
  13891. }
  13892. lock.unlock();
  13893. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  13894. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  13895. local_size += this_size;
  13896. // validate the quantized data
  13897. const size_t row_size = ggml_row_size(new_type, n_per_row);
  13898. void * this_data = (char *) new_data + first_row * row_size;
  13899. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  13900. std::unique_lock<std::mutex> lock(mutex);
  13901. valid = false;
  13902. break;
  13903. }
  13904. }
  13905. };
  13906. for (int it = 0; it < nthread - 1; ++it) {
  13907. workers.emplace_back(compute);
  13908. }
  13909. compute();
  13910. for (auto & w : workers) { w.join(); }
  13911. workers.clear();
  13912. if (!valid) {
  13913. throw std::runtime_error("quantized data validation failed");
  13914. }
  13915. return new_size;
  13916. }
  13917. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  13918. ggml_type default_type;
  13919. llama_ftype ftype = params->ftype;
  13920. switch (params->ftype) {
  13921. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  13922. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  13923. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  13924. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  13925. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  13926. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  13927. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  13928. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  13929. // K-quants
  13930. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  13931. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  13932. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  13933. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  13934. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  13935. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  13936. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  13937. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  13938. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  13939. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  13940. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  13941. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  13942. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  13943. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  13944. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  13945. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  13946. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  13947. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  13948. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  13949. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  13950. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  13951. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  13952. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  13953. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  13954. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  13955. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  13956. }
  13957. int nthread = params->nthread;
  13958. if (nthread <= 0) {
  13959. nthread = std::thread::hardware_concurrency();
  13960. }
  13961. // mmap consistently increases speed Linux, and also increases speed on Windows with
  13962. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  13963. #if defined(__linux__) || defined(_WIN32)
  13964. constexpr bool use_mmap = true;
  13965. #else
  13966. constexpr bool use_mmap = false;
  13967. #endif
  13968. llama_model_kv_override * kv_overrides = nullptr;
  13969. if (params->kv_overrides) {
  13970. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  13971. kv_overrides = v->data();
  13972. }
  13973. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  13974. ml.init_mappings(false); // no prefetching
  13975. llama_model model;
  13976. llm_load_arch(ml, model);
  13977. llm_load_hparams(ml, model);
  13978. struct quantize_state_internal qs(model, params);
  13979. if (params->only_copy) {
  13980. ftype = model.ftype;
  13981. }
  13982. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  13983. if (params->imatrix) {
  13984. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  13985. if (imatrix_data) {
  13986. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  13987. qs.has_imatrix = true;
  13988. // check imatrix for nans or infs
  13989. for (const auto & kv : *imatrix_data) {
  13990. for (float f : kv.second) {
  13991. if (!std::isfinite(f)) {
  13992. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  13993. }
  13994. }
  13995. }
  13996. }
  13997. }
  13998. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  13999. struct gguf_context * ctx_out = gguf_init_empty();
  14000. // copy the KV pairs from the input file
  14001. gguf_set_kv (ctx_out, ml.meta);
  14002. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  14003. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  14004. // Remove split metadata
  14005. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  14006. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  14007. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  14008. if (params->kv_overrides) {
  14009. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  14010. for (auto & o : overrides) {
  14011. if (o.key[0] == 0) break;
  14012. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  14013. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  14014. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  14015. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  14016. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  14017. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  14018. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  14019. gguf_set_val_str(ctx_out, o.key, o.val_str);
  14020. } else {
  14021. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  14022. }
  14023. }
  14024. }
  14025. for (int i = 0; i < ml.n_tensors; ++i) {
  14026. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  14027. const std::string name = ggml_get_name(meta);
  14028. // TODO: avoid hardcoded tensor names - use the TN_* constants
  14029. if (name.find("attn_v.weight") != std::string::npos ||
  14030. name.find("attn_qkv.weight") != std::string::npos) {
  14031. ++qs.n_attention_wv;
  14032. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  14033. qs.has_output = true;
  14034. }
  14035. }
  14036. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  14037. // sanity checks
  14038. {
  14039. const auto & n_head_kv_iter = model.hparams.n_head_kv_arr.begin();
  14040. // attention layers have a non-zero number of kv heads
  14041. int32_t n_attn_layer = model.hparams.n_layer - std::count(n_head_kv_iter, n_head_kv_iter + model.hparams.n_layer, 0);
  14042. if (llama_model_has_encoder(&model)) {
  14043. n_attn_layer *= 3;
  14044. }
  14045. GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
  14046. }
  14047. size_t total_size_org = 0;
  14048. size_t total_size_new = 0;
  14049. std::vector<std::thread> workers;
  14050. workers.reserve(nthread);
  14051. int idx = 0;
  14052. std::vector<no_init<uint8_t>> read_data;
  14053. std::vector<no_init<uint8_t>> work;
  14054. std::vector<no_init<float>> f32_conv_buf;
  14055. uint16_t n_split = 1;
  14056. // Assume split index is continuous
  14057. if (params->keep_split) {
  14058. for (int i = 0; i < ml.n_tensors; ++i) {
  14059. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  14060. }
  14061. }
  14062. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  14063. ctx_outs[0] = ctx_out;
  14064. // populate the original tensors so we get an initial meta data
  14065. for (int i = 0; i < ml.n_tensors; ++i) {
  14066. auto weight = ml.get_weight(i);
  14067. uint16_t i_split = params->keep_split ? weight->idx : 0;
  14068. struct ggml_tensor * tensor = weight->tensor;
  14069. if (ctx_outs[i_split] == NULL) {
  14070. ctx_outs[i_split] = gguf_init_empty();
  14071. }
  14072. gguf_add_tensor(ctx_outs[i_split], tensor);
  14073. }
  14074. // Set split info if needed
  14075. if (n_split > 1) {
  14076. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  14077. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  14078. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  14079. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  14080. }
  14081. }
  14082. int cur_split = -1;
  14083. std::ofstream fout;
  14084. auto close_ofstream = [&]() {
  14085. // Write metadata and close file handler
  14086. if (fout.is_open()) {
  14087. fout.seekp(0);
  14088. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  14089. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  14090. fout.write((const char *) data.data(), data.size());
  14091. fout.close();
  14092. }
  14093. };
  14094. auto new_ofstream = [&](int index) {
  14095. cur_split = index;
  14096. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  14097. std::string fname = fname_out;
  14098. if (params->keep_split) {
  14099. char split_path[PATH_MAX] = {0};
  14100. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  14101. fname = std::string(split_path);
  14102. }
  14103. fout = std::ofstream(fname, std::ios::binary);
  14104. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  14105. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  14106. // placeholder for the meta data
  14107. ::zeros(fout, meta_size);
  14108. };
  14109. const auto tn = LLM_TN(model.arch);
  14110. new_ofstream(0);
  14111. for (int i = 0; i < ml.n_tensors; ++i) {
  14112. auto weight = ml.get_weight(i);
  14113. struct ggml_tensor * tensor = weight->tensor;
  14114. if (weight->idx != cur_split && params->keep_split) {
  14115. close_ofstream();
  14116. new_ofstream(weight->idx);
  14117. }
  14118. const std::string name = ggml_get_name(tensor);
  14119. if (!ml.use_mmap) {
  14120. if (read_data.size() < ggml_nbytes(tensor)) {
  14121. read_data.resize(ggml_nbytes(tensor));
  14122. }
  14123. tensor->data = read_data.data();
  14124. }
  14125. ml.load_data_for(tensor);
  14126. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  14127. ++idx, ml.n_tensors,
  14128. ggml_get_name(tensor),
  14129. llama_format_tensor_shape(tensor).c_str(),
  14130. ggml_type_name(tensor->type));
  14131. // This used to be a regex, but <regex> has an extreme cost to compile times.
  14132. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  14133. // quantize only 2D and 3D tensors (experts)
  14134. quantize &= (ggml_n_dims(tensor) >= 2);
  14135. // do not quantize norm tensors
  14136. quantize &= name.find("_norm.weight") == std::string::npos;
  14137. quantize &= params->quantize_output_tensor || name != "output.weight";
  14138. quantize &= !params->only_copy;
  14139. // do not quantize expert gating tensors
  14140. // NOTE: can't use LLM_TN here because the layer number is not known
  14141. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  14142. // do not quantize positional embeddings and token types (BERT)
  14143. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  14144. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  14145. // do not quantize Mamba's small yet 2D weights
  14146. // NOTE: can't use LLM_TN here because the layer number is not known
  14147. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  14148. // do not quantize relative position bias (T5)
  14149. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  14150. enum ggml_type new_type;
  14151. void * new_data;
  14152. size_t new_size;
  14153. if (quantize) {
  14154. new_type = default_type;
  14155. // get more optimal quantization type based on the tensor shape, layer, etc.
  14156. if (!params->pure && ggml_is_quantized(default_type)) {
  14157. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  14158. }
  14159. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  14160. new_type = params->token_embedding_type;
  14161. }
  14162. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  14163. new_type = params->output_tensor_type;
  14164. }
  14165. // If we've decided to quantize to the same type the tensor is already
  14166. // in then there's nothing to do.
  14167. quantize = tensor->type != new_type;
  14168. }
  14169. if (!quantize) {
  14170. new_type = tensor->type;
  14171. new_data = tensor->data;
  14172. new_size = ggml_nbytes(tensor);
  14173. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  14174. } else {
  14175. const int64_t nelements = ggml_nelements(tensor);
  14176. const float * imatrix = nullptr;
  14177. if (imatrix_data) {
  14178. auto it = imatrix_data->find(tensor->name);
  14179. if (it == imatrix_data->end()) {
  14180. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  14181. } else {
  14182. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  14183. imatrix = it->second.data();
  14184. } else {
  14185. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  14186. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  14187. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  14188. // this is a significant error and it may be good idea to abort the process if this happens,
  14189. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  14190. // tok_embd should be ignored in this case, since it always causes this warning
  14191. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  14192. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  14193. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  14194. }
  14195. }
  14196. }
  14197. }
  14198. if ((new_type == GGML_TYPE_IQ2_XXS ||
  14199. new_type == GGML_TYPE_IQ2_XS ||
  14200. new_type == GGML_TYPE_IQ2_S ||
  14201. new_type == GGML_TYPE_IQ1_S ||
  14202. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  14203. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  14204. LLAMA_LOG_ERROR("\n\n============================================================\n");
  14205. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  14206. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  14207. LLAMA_LOG_ERROR("============================================================\n\n");
  14208. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  14209. }
  14210. float * f32_data;
  14211. if (tensor->type == GGML_TYPE_F32) {
  14212. f32_data = (float *) tensor->data;
  14213. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  14214. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  14215. } else {
  14216. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  14217. f32_data = (float *) f32_conv_buf.data();
  14218. }
  14219. int chunk_size_multiplier = 1;
  14220. 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) {
  14221. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  14222. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  14223. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  14224. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  14225. }
  14226. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  14227. fflush(stdout);
  14228. if (work.size() < (size_t)nelements * 4) {
  14229. work.resize(nelements * 4); // upper bound on size
  14230. }
  14231. new_data = work.data();
  14232. const int64_t n_per_row = tensor->ne[0];
  14233. const int64_t nrows = tensor->ne[1];
  14234. static const int64_t min_chunk_size = 32 * 512;
  14235. 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)) *
  14236. chunk_size_multiplier;
  14237. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  14238. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  14239. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  14240. // quantize each expert separately since they have different importance matrices
  14241. new_size = 0;
  14242. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  14243. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  14244. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  14245. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  14246. 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);
  14247. }
  14248. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  14249. }
  14250. total_size_org += ggml_nbytes(tensor);
  14251. total_size_new += new_size;
  14252. // update the gguf meta data as we go
  14253. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  14254. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  14255. // write tensor data + padding
  14256. fout.write((const char *) new_data, new_size);
  14257. zeros(fout, GGML_PAD(new_size, align) - new_size);
  14258. }
  14259. close_ofstream();
  14260. for (auto & c:ctx_outs) {
  14261. gguf_free(c);
  14262. }
  14263. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  14264. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  14265. if (qs.n_fallback > 0) {
  14266. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  14267. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  14268. }
  14269. }
  14270. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  14271. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  14272. ggml_context * ctx = nullptr;
  14273. struct gguf_init_params meta_gguf_params = {
  14274. /* .no_alloc = */ true,
  14275. /* .ctx = */ &ctx,
  14276. };
  14277. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  14278. if (!ctx_gguf) {
  14279. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  14280. }
  14281. // check metadata
  14282. {
  14283. auto get_kv_str = [&](const std::string & key) -> std::string {
  14284. int id = gguf_find_key(ctx_gguf, key.c_str());
  14285. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  14286. };
  14287. auto get_kv_f32 = [&](const std::string & key) -> float {
  14288. int id = gguf_find_key(ctx_gguf, key.c_str());
  14289. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  14290. };
  14291. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  14292. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  14293. if (general_type != "adapter") {
  14294. gguf_free(ctx_gguf);
  14295. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  14296. }
  14297. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  14298. auto general_arch = llm_arch_from_string(general_arch_str);
  14299. if (general_arch != model->arch) {
  14300. gguf_free(ctx_gguf);
  14301. throw std::runtime_error("model arch and LoRA arch mismatch");
  14302. }
  14303. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  14304. if (adapter_type != "lora") {
  14305. gguf_free(ctx_gguf);
  14306. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  14307. }
  14308. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  14309. }
  14310. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  14311. // contexts for each buffer type
  14312. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  14313. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  14314. auto it = ctx_map.find(buft);
  14315. if (it == ctx_map.end()) {
  14316. // add a new context
  14317. struct ggml_init_params params = {
  14318. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  14319. /*.mem_buffer =*/ NULL,
  14320. /*.no_alloc =*/ true,
  14321. };
  14322. ggml_context * buft_ctx = ggml_init(params);
  14323. ctx_map[buft] = buft_ctx;
  14324. return buft_ctx;
  14325. };
  14326. return it->second;
  14327. };
  14328. // bundle lora_a and lora_b into pairs
  14329. std::map<std::string, llama_lora_weight> ab_map;
  14330. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  14331. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  14332. };
  14333. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  14334. std::string name(cur->name);
  14335. if (str_endswith(name, ".lora_a")) {
  14336. replace_all(name, ".lora_a", "");
  14337. if (ab_map.find(name) == ab_map.end()) {
  14338. ab_map[name] = llama_lora_weight(cur, nullptr);
  14339. } else {
  14340. ab_map[name].a = cur;
  14341. }
  14342. } else if (str_endswith(name, ".lora_b")) {
  14343. replace_all(name, ".lora_b", "");
  14344. if (ab_map.find(name) == ab_map.end()) {
  14345. ab_map[name] = llama_lora_weight(nullptr, cur);
  14346. } else {
  14347. ab_map[name].b = cur;
  14348. }
  14349. } else {
  14350. gguf_free(ctx_gguf);
  14351. ggml_free(ctx);
  14352. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  14353. }
  14354. }
  14355. // add tensors
  14356. for (auto & it : ab_map) {
  14357. const std::string & name = it.first;
  14358. llama_lora_weight & w = it.second;
  14359. if (!w.a || !w.b) {
  14360. gguf_free(ctx_gguf);
  14361. ggml_free(ctx);
  14362. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  14363. }
  14364. // device buft and device ctx
  14365. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  14366. if (!model_tensor) {
  14367. gguf_free(ctx_gguf);
  14368. ggml_free(ctx);
  14369. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  14370. }
  14371. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  14372. // validate tensor shape
  14373. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  14374. gguf_free(ctx_gguf);
  14375. ggml_free(ctx);
  14376. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  14377. }
  14378. if (w.a->ne[1] != w.b->ne[0]) {
  14379. gguf_free(ctx_gguf);
  14380. ggml_free(ctx);
  14381. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  14382. }
  14383. // save tensor to adapter
  14384. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  14385. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  14386. ggml_set_name(tensor_a, w.a->name);
  14387. ggml_set_name(tensor_b, w.b->name);
  14388. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  14389. }
  14390. // allocate tensors / buffers and zero
  14391. {
  14392. adapter.ctxs.reserve(ctx_map.size());
  14393. adapter.bufs.reserve(ctx_map.size());
  14394. for (auto it : ctx_map) {
  14395. ggml_backend_buffer_type_t buft = it.first;
  14396. ggml_context * ctx_dev = it.second;
  14397. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  14398. if (!buf) {
  14399. gguf_free(ctx_gguf);
  14400. ggml_free(ctx);
  14401. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  14402. }
  14403. 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);
  14404. adapter.ctxs.push_back(ctx_dev);
  14405. adapter.bufs.push_back(buf);
  14406. }
  14407. }
  14408. // set tensor data
  14409. {
  14410. llama_file gguf_file(path_lora, "rb");
  14411. std::vector<uint8_t> read_buf;
  14412. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  14413. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  14414. size_t size = ggml_nbytes(orig);
  14415. read_buf.resize(size);
  14416. gguf_file.seek(offs, SEEK_SET);
  14417. gguf_file.read_raw(read_buf.data(), size);
  14418. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  14419. };
  14420. for (auto & it : adapter.ab_map) {
  14421. auto orig = ab_map[it.first];
  14422. auto dev = it.second;
  14423. set_tensor(orig.a, dev.a);
  14424. set_tensor(orig.b, dev.b);
  14425. }
  14426. }
  14427. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  14428. // free ctx for reading gguf
  14429. gguf_free(ctx_gguf);
  14430. ggml_free(ctx);
  14431. }
  14432. int32_t llama_lora_adapter_set(
  14433. struct llama_context * ctx,
  14434. struct llama_lora_adapter * adapter,
  14435. float scale) {
  14436. if (ctx->cparams.flash_attn) {
  14437. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  14438. return -1;
  14439. }
  14440. ctx->lora_adapters[adapter] = scale;
  14441. return 0;
  14442. }
  14443. int32_t llama_lora_adapter_remove(
  14444. struct llama_context * ctx,
  14445. struct llama_lora_adapter * adapter) {
  14446. auto pos = ctx->lora_adapters.find(adapter);
  14447. if (pos != ctx->lora_adapters.end()) {
  14448. ctx->lora_adapters.erase(pos);
  14449. return 0;
  14450. }
  14451. return -1;
  14452. }
  14453. void llama_lora_adapter_clear(struct llama_context * ctx) {
  14454. ctx->lora_adapters.clear();
  14455. }
  14456. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  14457. delete adapter;
  14458. }
  14459. //
  14460. // interface implementation
  14461. //
  14462. struct llama_model_params llama_model_default_params() {
  14463. struct llama_model_params result = {
  14464. /*.n_gpu_layers =*/ 0,
  14465. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  14466. /*.main_gpu =*/ 0,
  14467. /*.tensor_split =*/ nullptr,
  14468. /*.rpc_servers =*/ nullptr,
  14469. /*.progress_callback =*/ nullptr,
  14470. /*.progress_callback_user_data =*/ nullptr,
  14471. /*.kv_overrides =*/ nullptr,
  14472. /*.vocab_only =*/ false,
  14473. /*.use_mmap =*/ true,
  14474. /*.use_mlock =*/ false,
  14475. /*.check_tensors =*/ false,
  14476. };
  14477. #ifdef GGML_USE_METAL
  14478. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  14479. result.n_gpu_layers = 999;
  14480. #endif
  14481. return result;
  14482. }
  14483. struct llama_context_params llama_context_default_params() {
  14484. struct llama_context_params result = {
  14485. /*.seed =*/ LLAMA_DEFAULT_SEED,
  14486. /*.n_ctx =*/ 512,
  14487. /*.n_batch =*/ 2048,
  14488. /*.n_ubatch =*/ 512,
  14489. /*.n_seq_max =*/ 1,
  14490. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  14491. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  14492. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  14493. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  14494. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  14495. /*.rope_freq_base =*/ 0.0f,
  14496. /*.rope_freq_scale =*/ 0.0f,
  14497. /*.yarn_ext_factor =*/ -1.0f,
  14498. /*.yarn_attn_factor =*/ 1.0f,
  14499. /*.yarn_beta_fast =*/ 32.0f,
  14500. /*.yarn_beta_slow =*/ 1.0f,
  14501. /*.yarn_orig_ctx =*/ 0,
  14502. /*.defrag_thold =*/ -1.0f,
  14503. /*.cb_eval =*/ nullptr,
  14504. /*.cb_eval_user_data =*/ nullptr,
  14505. /*.type_k =*/ GGML_TYPE_F16,
  14506. /*.type_v =*/ GGML_TYPE_F16,
  14507. /*.logits_all =*/ false,
  14508. /*.embeddings =*/ false,
  14509. /*.offload_kqv =*/ true,
  14510. /*.flash_attn =*/ false,
  14511. /*.abort_callback =*/ nullptr,
  14512. /*.abort_callback_data =*/ nullptr,
  14513. };
  14514. return result;
  14515. }
  14516. struct llama_model_quantize_params llama_model_quantize_default_params() {
  14517. struct llama_model_quantize_params result = {
  14518. /*.nthread =*/ 0,
  14519. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  14520. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  14521. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  14522. /*.allow_requantize =*/ false,
  14523. /*.quantize_output_tensor =*/ true,
  14524. /*.only_copy =*/ false,
  14525. /*.pure =*/ false,
  14526. /*.keep_split =*/ false,
  14527. /*.imatrix =*/ nullptr,
  14528. /*.kv_overrides =*/ nullptr,
  14529. };
  14530. return result;
  14531. }
  14532. size_t llama_max_devices(void) {
  14533. #if defined(GGML_USE_RPC)
  14534. return GGML_RPC_MAX_SERVERS;
  14535. #elif defined(GGML_USE_METAL)
  14536. return 1;
  14537. #elif defined(GGML_USE_CUDA)
  14538. return GGML_CUDA_MAX_DEVICES;
  14539. #elif defined(GGML_USE_SYCL)
  14540. return GGML_SYCL_MAX_DEVICES;
  14541. #elif defined(GGML_USE_VULKAN)
  14542. return GGML_VK_MAX_DEVICES;
  14543. #elif defined(GGML_USE_CANN)
  14544. return GGML_CANN_MAX_DEVICES;
  14545. #else
  14546. return 1;
  14547. #endif
  14548. }
  14549. bool llama_supports_mmap(void) {
  14550. return llama_mmap::SUPPORTED;
  14551. }
  14552. bool llama_supports_mlock(void) {
  14553. return llama_mlock::SUPPORTED;
  14554. }
  14555. bool llama_supports_gpu_offload(void) {
  14556. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  14557. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  14558. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  14559. return true;
  14560. #else
  14561. return false;
  14562. #endif
  14563. }
  14564. void llama_backend_init(void) {
  14565. ggml_time_init();
  14566. // needed to initialize f16 tables
  14567. {
  14568. struct ggml_init_params params = { 0, NULL, false };
  14569. struct ggml_context * ctx = ggml_init(params);
  14570. ggml_free(ctx);
  14571. }
  14572. }
  14573. void llama_numa_init(enum ggml_numa_strategy numa) {
  14574. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  14575. ggml_numa_init(numa);
  14576. }
  14577. }
  14578. void llama_backend_free(void) {
  14579. ggml_quantize_free();
  14580. }
  14581. int64_t llama_time_us(void) {
  14582. return ggml_time_us();
  14583. }
  14584. struct llama_model * llama_load_model_from_file(
  14585. const char * path_model,
  14586. struct llama_model_params params) {
  14587. ggml_time_init();
  14588. llama_model * model = new llama_model;
  14589. unsigned cur_percentage = 0;
  14590. if (params.progress_callback == NULL) {
  14591. params.progress_callback_user_data = &cur_percentage;
  14592. params.progress_callback = [](float progress, void * ctx) {
  14593. unsigned * cur_percentage_p = (unsigned *) ctx;
  14594. unsigned percentage = (unsigned) (100 * progress);
  14595. while (percentage > *cur_percentage_p) {
  14596. *cur_percentage_p = percentage;
  14597. LLAMA_LOG_INFO(".");
  14598. if (percentage >= 100) {
  14599. LLAMA_LOG_INFO("\n");
  14600. }
  14601. }
  14602. return true;
  14603. };
  14604. }
  14605. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  14606. // split the servers set them into model->rpc_servers
  14607. std::string servers(params.rpc_servers);
  14608. size_t pos = 0;
  14609. while ((pos = servers.find(",")) != std::string::npos) {
  14610. std::string server = servers.substr(0, pos);
  14611. model->rpc_servers.push_back(server);
  14612. servers.erase(0, pos + 1);
  14613. }
  14614. model->rpc_servers.push_back(servers);
  14615. }
  14616. int status = llama_model_load(path_model, *model, params);
  14617. GGML_ASSERT(status <= 0);
  14618. if (status < 0) {
  14619. if (status == -1) {
  14620. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  14621. } else if (status == -2) {
  14622. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  14623. }
  14624. delete model;
  14625. return nullptr;
  14626. }
  14627. return model;
  14628. }
  14629. void llama_free_model(struct llama_model * model) {
  14630. delete model;
  14631. }
  14632. struct llama_context * llama_new_context_with_model(
  14633. struct llama_model * model,
  14634. struct llama_context_params params) {
  14635. if (!model) {
  14636. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  14637. return nullptr;
  14638. }
  14639. if (params.n_batch == 0 && params.n_ubatch == 0) {
  14640. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  14641. return nullptr;
  14642. }
  14643. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  14644. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  14645. return nullptr;
  14646. }
  14647. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  14648. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  14649. params.flash_attn = false;
  14650. }
  14651. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  14652. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  14653. params.flash_attn = false;
  14654. }
  14655. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  14656. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  14657. return nullptr;
  14658. }
  14659. llama_context * ctx = new llama_context(*model);
  14660. const auto & hparams = model->hparams;
  14661. auto & cparams = ctx->cparams;
  14662. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  14663. cparams.n_threads = params.n_threads;
  14664. cparams.n_threads_batch = params.n_threads_batch;
  14665. cparams.yarn_ext_factor = params.yarn_ext_factor;
  14666. cparams.yarn_attn_factor = params.yarn_attn_factor;
  14667. cparams.yarn_beta_fast = params.yarn_beta_fast;
  14668. cparams.yarn_beta_slow = params.yarn_beta_slow;
  14669. cparams.defrag_thold = params.defrag_thold;
  14670. cparams.embeddings = params.embeddings;
  14671. cparams.offload_kqv = params.offload_kqv;
  14672. cparams.flash_attn = params.flash_attn;
  14673. cparams.pooling_type = params.pooling_type;
  14674. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  14675. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  14676. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  14677. // this is necessary due to kv_self.n being padded later during inference
  14678. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  14679. // with causal attention, the batch size is limited by the context size
  14680. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  14681. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  14682. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  14683. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  14684. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  14685. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  14686. cparams.n_batch = GGML_KQ_MASK_PAD;
  14687. }
  14688. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  14689. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  14690. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  14691. hparams.n_ctx_train;
  14692. cparams.cb_eval = params.cb_eval;
  14693. cparams.cb_eval_user_data = params.cb_eval_user_data;
  14694. auto rope_scaling_type = params.rope_scaling_type;
  14695. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  14696. rope_scaling_type = hparams.rope_scaling_type_train;
  14697. }
  14698. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  14699. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  14700. }
  14701. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  14702. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  14703. }
  14704. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  14705. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  14706. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  14707. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  14708. } else {
  14709. cparams.pooling_type = hparams.pooling_type;
  14710. }
  14711. }
  14712. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  14713. cparams.causal_attn = hparams.causal_attn;
  14714. } else {
  14715. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  14716. }
  14717. if (params.seed == LLAMA_DEFAULT_SEED) {
  14718. params.seed = time(NULL);
  14719. }
  14720. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  14721. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  14722. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  14723. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  14724. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  14725. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  14726. ctx->abort_callback = params.abort_callback;
  14727. ctx->abort_callback_data = params.abort_callback_data;
  14728. ctx->sampling.rng = std::mt19937(params.seed);
  14729. ctx->logits_all = params.logits_all;
  14730. // build worst-case graph for encoder if a model contains encoder
  14731. ctx->is_encoding = llama_model_has_encoder(model);
  14732. uint32_t kv_size = cparams.n_ctx;
  14733. ggml_type type_k = params.type_k;
  14734. ggml_type type_v = params.type_v;
  14735. // Mamba only needs a constant number of KV cache cells per sequence
  14736. if (llama_model_is_recurrent(model)) {
  14737. // Mamba needs at least as many KV cells as there are sequences kept at any time
  14738. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  14739. // it's probably best to keep as much precision as possible for the states
  14740. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  14741. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  14742. }
  14743. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  14744. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  14745. if (!hparams.vocab_only) {
  14746. // initialize backends
  14747. #if defined(GGML_USE_METAL)
  14748. if (model->n_gpu_layers > 0) {
  14749. ctx->backend_metal = ggml_backend_metal_init();
  14750. if (ctx->backend_metal == nullptr) {
  14751. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  14752. llama_free(ctx);
  14753. return nullptr;
  14754. }
  14755. ctx->backends.push_back(ctx->backend_metal);
  14756. }
  14757. #elif defined(GGML_USE_CUDA)
  14758. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  14759. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  14760. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  14761. if (backend == nullptr) {
  14762. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  14763. llama_free(ctx);
  14764. return nullptr;
  14765. }
  14766. ctx->backends.push_back(backend);
  14767. } else {
  14768. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  14769. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  14770. ggml_backend_t backend = ggml_backend_cuda_init(device);
  14771. if (backend == nullptr) {
  14772. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  14773. llama_free(ctx);
  14774. return nullptr;
  14775. }
  14776. ctx->backends.push_back(backend);
  14777. }
  14778. }
  14779. #elif defined(GGML_USE_VULKAN)
  14780. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  14781. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  14782. llama_free(ctx);
  14783. return nullptr;
  14784. }
  14785. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  14786. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  14787. if (backend == nullptr) {
  14788. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  14789. llama_free(ctx);
  14790. return nullptr;
  14791. }
  14792. ctx->backends.push_back(backend);
  14793. } else {
  14794. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  14795. ggml_backend_t backend = ggml_backend_vk_init(device);
  14796. if (backend == nullptr) {
  14797. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  14798. llama_free(ctx);
  14799. return nullptr;
  14800. }
  14801. ctx->backends.push_back(backend);
  14802. }
  14803. }
  14804. #elif defined(GGML_USE_SYCL)
  14805. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  14806. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  14807. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  14808. if (backend == nullptr) {
  14809. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  14810. llama_free(ctx);
  14811. return nullptr;
  14812. }
  14813. ctx->backends.push_back(backend);
  14814. } else {
  14815. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  14816. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  14817. ggml_backend_t backend = ggml_backend_sycl_init(i);
  14818. if (backend == nullptr) {
  14819. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  14820. llama_free(ctx);
  14821. return nullptr;
  14822. }
  14823. ctx->backends.push_back(backend);
  14824. }
  14825. }
  14826. #elif defined(GGML_USE_KOMPUTE)
  14827. if (model->n_gpu_layers > 0) {
  14828. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  14829. if (backend == nullptr) {
  14830. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  14831. llama_free(ctx);
  14832. return nullptr;
  14833. }
  14834. ctx->backends.push_back(backend);
  14835. }
  14836. #elif defined(GGML_USE_CANN)
  14837. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  14838. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  14839. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  14840. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  14841. if (backend == nullptr) {
  14842. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  14843. llama_free(ctx);
  14844. return nullptr;
  14845. }
  14846. ctx->backends.push_back(backend);
  14847. } else {
  14848. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  14849. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  14850. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  14851. ggml_backend_t backend = ggml_backend_cann_init(device);
  14852. if (backend == nullptr) {
  14853. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  14854. llama_free(ctx);
  14855. return nullptr;
  14856. }
  14857. ctx->backends.push_back(backend);
  14858. }
  14859. }
  14860. #endif
  14861. #ifdef GGML_USE_BLAS
  14862. ctx->backend_blas = ggml_backend_blas_init();
  14863. if (ctx->backend_blas == nullptr) {
  14864. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  14865. } else {
  14866. ctx->backends.push_back(ctx->backend_blas);
  14867. }
  14868. #endif
  14869. #if defined(GGML_USE_RPC)
  14870. if (model->n_gpu_layers > 0) {
  14871. for (const auto & endpoint : model->rpc_servers) {
  14872. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  14873. if (backend == nullptr) {
  14874. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  14875. llama_free(ctx);
  14876. return nullptr;
  14877. }
  14878. ctx->backends.push_back(backend);
  14879. }
  14880. }
  14881. #endif
  14882. ctx->backend_cpu = ggml_backend_cpu_init();
  14883. if (ctx->backend_cpu == nullptr) {
  14884. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  14885. llama_free(ctx);
  14886. return nullptr;
  14887. }
  14888. ctx->backends.push_back(ctx->backend_cpu);
  14889. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  14890. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  14891. llama_free(ctx);
  14892. return nullptr;
  14893. }
  14894. {
  14895. size_t memory_size_k = 0;
  14896. size_t memory_size_v = 0;
  14897. for (auto & k : ctx->kv_self.k_l) {
  14898. memory_size_k += ggml_nbytes(k);
  14899. }
  14900. for (auto & v : ctx->kv_self.v_l) {
  14901. memory_size_v += ggml_nbytes(v);
  14902. }
  14903. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  14904. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  14905. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  14906. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  14907. }
  14908. // graph outputs buffer
  14909. {
  14910. // resized during inference when a batch uses more outputs
  14911. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  14912. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  14913. llama_free(ctx);
  14914. return nullptr;
  14915. }
  14916. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  14917. ggml_backend_buffer_name(ctx->buf_output),
  14918. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  14919. }
  14920. // scheduler and compute buffers
  14921. {
  14922. // buffer types used for the compute buffer of each backend
  14923. std::vector<ggml_backend_buffer_type_t> backend_buft;
  14924. for (auto * backend : ctx->backends) {
  14925. if (ggml_backend_is_cpu(backend)) {
  14926. // use host buffers for the CPU backend compute buffer
  14927. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  14928. } else {
  14929. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  14930. }
  14931. }
  14932. const size_t max_nodes = llama_model_max_nodes(*model);
  14933. // buffer used to store the computation graph and the tensor meta data
  14934. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  14935. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  14936. bool pipeline_parallel =
  14937. llama_get_device_count(*model) > 1 &&
  14938. model->n_gpu_layers > (int)model->hparams.n_layer &&
  14939. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  14940. params.offload_kqv;
  14941. #ifndef GGML_USE_CUDA
  14942. // pipeline parallelism requires support for async compute and events
  14943. // currently this is only implemented in the CUDA backend
  14944. pipeline_parallel = false;
  14945. #endif
  14946. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  14947. if (pipeline_parallel) {
  14948. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  14949. }
  14950. // build worst-case graph
  14951. uint32_t n_seqs = 1; // TODO: worst-case number of sequences
  14952. uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
  14953. 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
  14954. llama_ubatch ubatch = { true, n_tokens, n_tokens / n_seqs, n_seqs, &token, nullptr, nullptr, nullptr, nullptr, nullptr};
  14955. ggml_cgraph * gf = llama_build_graph(*ctx, ubatch, true);
  14956. // initialize scheduler with the worst-case graph
  14957. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  14958. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  14959. llama_free(ctx);
  14960. return nullptr;
  14961. }
  14962. for (size_t i = 0; i < ctx->backends.size(); i++) {
  14963. ggml_backend_t backend = ctx->backends[i];
  14964. ggml_backend_buffer_type_t buft = backend_buft[i];
  14965. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  14966. if (size > 1) {
  14967. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  14968. ggml_backend_buft_name(buft),
  14969. size / 1024.0 / 1024.0);
  14970. }
  14971. }
  14972. // note: the number of splits during measure is higher than during inference due to the kv shift
  14973. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  14974. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  14975. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  14976. }
  14977. }
  14978. return ctx;
  14979. }
  14980. void llama_free(struct llama_context * ctx) {
  14981. delete ctx;
  14982. }
  14983. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  14984. return &ctx->model;
  14985. }
  14986. const struct llama_vocab * llama_get_vocab(const struct llama_context * ctx) {
  14987. return &ctx->model.vocab;
  14988. }
  14989. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  14990. return ctx->cparams.n_ctx;
  14991. }
  14992. uint32_t llama_n_batch(const struct llama_context * ctx) {
  14993. return ctx->cparams.n_batch;
  14994. }
  14995. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  14996. return ctx->cparams.n_ubatch;
  14997. }
  14998. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  14999. return ctx->kv_self.size;
  15000. }
  15001. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  15002. return model->vocab.type;
  15003. }
  15004. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  15005. switch (model->arch) {
  15006. // these models do not use RoPE
  15007. case LLM_ARCH_GPT2:
  15008. case LLM_ARCH_GPTJ:
  15009. case LLM_ARCH_MPT:
  15010. case LLM_ARCH_REFACT:
  15011. case LLM_ARCH_BLOOM:
  15012. case LLM_ARCH_MAMBA:
  15013. case LLM_ARCH_JINA_BERT_V2:
  15014. case LLM_ARCH_T5:
  15015. case LLM_ARCH_T5ENCODER:
  15016. case LLM_ARCH_JAIS:
  15017. return LLAMA_ROPE_TYPE_NONE;
  15018. // use what we call a normal RoPE, operating on pairs of consecutive head values
  15019. case LLM_ARCH_LLAMA:
  15020. case LLM_ARCH_BAICHUAN:
  15021. case LLM_ARCH_STARCODER:
  15022. case LLM_ARCH_PLAMO:
  15023. case LLM_ARCH_ORION:
  15024. case LLM_ARCH_INTERNLM2:
  15025. case LLM_ARCH_MINICPM:
  15026. case LLM_ARCH_XVERSE:
  15027. case LLM_ARCH_COMMAND_R:
  15028. case LLM_ARCH_OLMO:
  15029. case LLM_ARCH_ARCTIC:
  15030. case LLM_ARCH_DEEPSEEK2:
  15031. case LLM_ARCH_CHATGLM:
  15032. return LLAMA_ROPE_TYPE_NORM;
  15033. // the pairs of head values are offset by n_rot/2
  15034. case LLM_ARCH_FALCON:
  15035. case LLM_ARCH_GROK:
  15036. case LLM_ARCH_DBRX:
  15037. case LLM_ARCH_BERT:
  15038. case LLM_ARCH_NOMIC_BERT:
  15039. case LLM_ARCH_STABLELM:
  15040. case LLM_ARCH_BITNET:
  15041. case LLM_ARCH_QWEN:
  15042. case LLM_ARCH_QWEN2:
  15043. case LLM_ARCH_QWEN2MOE:
  15044. case LLM_ARCH_PHI2:
  15045. case LLM_ARCH_PHI3:
  15046. case LLM_ARCH_GEMMA:
  15047. case LLM_ARCH_GEMMA2:
  15048. case LLM_ARCH_STARCODER2:
  15049. case LLM_ARCH_OPENELM:
  15050. case LLM_ARCH_GPTNEOX:
  15051. case LLM_ARCH_CODESHELL:
  15052. case LLM_ARCH_NEMOTRON:
  15053. case LLM_ARCH_EXAONE:
  15054. return LLAMA_ROPE_TYPE_NEOX;
  15055. // all model arches should be listed explicitly here
  15056. case LLM_ARCH_UNKNOWN:
  15057. GGML_ABORT("unknown architecture");
  15058. }
  15059. return LLAMA_ROPE_TYPE_NONE;
  15060. }
  15061. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  15062. return ctx->cparams.pooling_type;
  15063. }
  15064. int32_t llama_n_vocab(const struct llama_model * model) {
  15065. return model->hparams.n_vocab;
  15066. }
  15067. int32_t llama_n_ctx_train(const struct llama_model * model) {
  15068. return model->hparams.n_ctx_train;
  15069. }
  15070. int32_t llama_n_embd(const struct llama_model * model) {
  15071. return model->hparams.n_embd;
  15072. }
  15073. int32_t llama_n_layer(const struct llama_model * model) {
  15074. return model->hparams.n_layer;
  15075. }
  15076. float llama_rope_freq_scale_train(const struct llama_model * model) {
  15077. return model->hparams.rope_freq_scale_train;
  15078. }
  15079. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  15080. const auto & it = model->gguf_kv.find(key);
  15081. if (it == model->gguf_kv.end()) {
  15082. if (buf_size > 0) {
  15083. buf[0] = '\0';
  15084. }
  15085. return -1;
  15086. }
  15087. return snprintf(buf, buf_size, "%s", it->second.c_str());
  15088. }
  15089. int32_t llama_model_meta_count(const struct llama_model * model) {
  15090. return (int)model->gguf_kv.size();
  15091. }
  15092. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  15093. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  15094. if (buf_size > 0) {
  15095. buf[0] = '\0';
  15096. }
  15097. return -1;
  15098. }
  15099. auto it = model->gguf_kv.begin();
  15100. std::advance(it, i);
  15101. return snprintf(buf, buf_size, "%s", it->first.c_str());
  15102. }
  15103. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  15104. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  15105. if (buf_size > 0) {
  15106. buf[0] = '\0';
  15107. }
  15108. return -1;
  15109. }
  15110. auto it = model->gguf_kv.begin();
  15111. std::advance(it, i);
  15112. return snprintf(buf, buf_size, "%s", it->second.c_str());
  15113. }
  15114. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  15115. return snprintf(buf, buf_size, "%s %s %s",
  15116. llama_model_arch_name(model->arch),
  15117. llama_model_type_name(model->type),
  15118. llama_model_ftype_name(model->ftype).c_str());
  15119. }
  15120. uint64_t llama_model_size(const struct llama_model * model) {
  15121. uint64_t size = 0;
  15122. for (const auto & it : model->tensors_by_name) {
  15123. size += ggml_nbytes(it.second);
  15124. }
  15125. return size;
  15126. }
  15127. uint64_t llama_model_n_params(const struct llama_model * model) {
  15128. uint64_t nparams = 0;
  15129. for (const auto & it : model->tensors_by_name) {
  15130. nparams += ggml_nelements(it.second);
  15131. }
  15132. return nparams;
  15133. }
  15134. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  15135. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  15136. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  15137. return it.first == name;
  15138. });
  15139. if (it == model->tensors_by_name.end()) {
  15140. return nullptr;
  15141. }
  15142. return it->second;
  15143. }
  15144. bool llama_model_has_encoder(const struct llama_model * model) {
  15145. switch (model->arch) {
  15146. case LLM_ARCH_T5: return true;
  15147. case LLM_ARCH_T5ENCODER: return true;
  15148. default: return false;
  15149. }
  15150. }
  15151. bool llama_model_has_decoder(const struct llama_model * model) {
  15152. switch (model->arch) {
  15153. case LLM_ARCH_T5ENCODER: return false;
  15154. default: return true;
  15155. }
  15156. }
  15157. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  15158. return model->hparams.dec_start_token_id;
  15159. }
  15160. bool llama_model_is_recurrent(const struct llama_model * model) {
  15161. switch (model->arch) {
  15162. case LLM_ARCH_MAMBA: return true;
  15163. default: return false;
  15164. }
  15165. }
  15166. uint32_t llama_model_quantize(
  15167. const char * fname_inp,
  15168. const char * fname_out,
  15169. const llama_model_quantize_params * params) {
  15170. try {
  15171. llama_model_quantize_internal(fname_inp, fname_out, params);
  15172. return 0;
  15173. } catch (const std::exception & err) {
  15174. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  15175. return 1;
  15176. }
  15177. }
  15178. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  15179. try {
  15180. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  15181. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  15182. return adapter;
  15183. } catch (const std::exception & err) {
  15184. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  15185. return nullptr;
  15186. }
  15187. }
  15188. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  15189. GGML_ASSERT(cvec.tensors.empty());
  15190. GGML_ASSERT(cvec.ctxs.empty());
  15191. GGML_ASSERT(cvec.bufs.empty());
  15192. // count layer buffer types
  15193. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  15194. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  15195. buft_layer_count[model.buft_layer[i].buft]++;
  15196. }
  15197. // allocate contexts
  15198. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  15199. for (auto & it : buft_layer_count) {
  15200. int n_layers = it.second;
  15201. struct ggml_init_params params = {
  15202. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  15203. /*.mem_buffer =*/ NULL,
  15204. /*.no_alloc =*/ true,
  15205. };
  15206. ggml_context * ctx = ggml_init(params);
  15207. if (!ctx) {
  15208. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  15209. return 1;
  15210. }
  15211. ctx_map[it.first] = ctx;
  15212. }
  15213. // make tensors
  15214. cvec.tensors.reserve(model.hparams.n_layer);
  15215. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  15216. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  15217. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  15218. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  15219. cvec.tensors.push_back(tensor);
  15220. }
  15221. // allocate tensors / buffers and zero
  15222. cvec.ctxs.reserve(ctx_map.size());
  15223. cvec.bufs.reserve(ctx_map.size());
  15224. for (auto it : ctx_map) {
  15225. ggml_backend_buffer_type_t buft = it.first;
  15226. ggml_context * ctx = it.second;
  15227. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  15228. if (!buf) {
  15229. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  15230. return false;
  15231. }
  15232. ggml_backend_buffer_clear(buf, 0);
  15233. cvec.ctxs.push_back(ctx);
  15234. cvec.bufs.push_back(buf);
  15235. }
  15236. return true;
  15237. }
  15238. 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) {
  15239. const llama_model & model = lctx->model;
  15240. llama_control_vector & cvec = lctx->cvec;
  15241. if (data == nullptr) {
  15242. // disable the current control vector (but leave allocated for later)
  15243. cvec.layer_start = -1;
  15244. cvec.layer_end = -1;
  15245. return 0;
  15246. }
  15247. if (n_embd != (int) model.hparams.n_embd) {
  15248. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  15249. return 1;
  15250. }
  15251. if (cvec.tensors.empty()) {
  15252. if (!llama_control_vector_init(cvec, model)) {
  15253. return 1;
  15254. }
  15255. }
  15256. cvec.layer_start = il_start;
  15257. cvec.layer_end = il_end;
  15258. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  15259. assert(cvec.tensors[il] != nullptr);
  15260. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  15261. if (off + n_embd <= len) {
  15262. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  15263. }
  15264. }
  15265. return 0;
  15266. }
  15267. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  15268. struct llama_kv_cache_view result = {
  15269. /*.n_cells = */ 0,
  15270. /*.n_seq_max = */ n_seq_max,
  15271. /*.token_count = */ 0,
  15272. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  15273. /*.max_contiguous = */ 0,
  15274. /*.max_contiguous_idx = */ -1,
  15275. /*.cells = */ nullptr,
  15276. /*.cells_sequences = */ nullptr,
  15277. };
  15278. return result;
  15279. }
  15280. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  15281. if (view->cells != nullptr) {
  15282. free(view->cells);
  15283. view->cells = nullptr;
  15284. }
  15285. if (view->cells_sequences != nullptr) {
  15286. free(view->cells_sequences);
  15287. view->cells_sequences = nullptr;
  15288. }
  15289. }
  15290. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  15291. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  15292. view->n_cells = int32_t(ctx->kv_self.size);
  15293. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  15294. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  15295. view->cells = (struct llama_kv_cache_view_cell *)p;
  15296. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  15297. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  15298. view->cells_sequences = (llama_seq_id *)p;
  15299. }
  15300. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  15301. llama_kv_cache_view_cell * c_curr = view->cells;
  15302. llama_seq_id * cs_curr = view->cells_sequences;
  15303. int32_t used_cells = 0;
  15304. int32_t token_count = 0;
  15305. int32_t curr_contig_idx = -1;
  15306. uint32_t max_contig = 0;
  15307. int32_t max_contig_idx = -1;
  15308. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  15309. const size_t curr_size = kv_cells[i].seq_id.size();
  15310. token_count += curr_size;
  15311. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  15312. if (curr_size > 0) {
  15313. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  15314. max_contig = i - curr_contig_idx;
  15315. max_contig_idx = curr_contig_idx;
  15316. }
  15317. curr_contig_idx = -1;
  15318. } else if (curr_contig_idx < 0) {
  15319. curr_contig_idx = i;
  15320. }
  15321. int seq_idx = 0;
  15322. for (const llama_seq_id it : kv_cells[i].seq_id) {
  15323. if (seq_idx >= view->n_seq_max) {
  15324. break;
  15325. }
  15326. cs_curr[seq_idx] = it;
  15327. seq_idx++;
  15328. }
  15329. if (seq_idx != 0) {
  15330. used_cells++;
  15331. }
  15332. for (; seq_idx < view->n_seq_max; seq_idx++) {
  15333. cs_curr[seq_idx] = -1;
  15334. }
  15335. }
  15336. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  15337. max_contig_idx = curr_contig_idx;
  15338. max_contig = kv_cells.size() - curr_contig_idx;
  15339. }
  15340. view->max_contiguous = max_contig;
  15341. view->max_contiguous_idx = max_contig_idx;
  15342. view->token_count = token_count;
  15343. view->used_cells = used_cells;
  15344. if (uint32_t(used_cells) != ctx->kv_self.used) {
  15345. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  15346. __func__, ctx->kv_self.used, used_cells);
  15347. }
  15348. }
  15349. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  15350. int result = 0;
  15351. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  15352. result += ctx->kv_self.cells[i].seq_id.size();
  15353. }
  15354. return result;
  15355. }
  15356. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  15357. return ctx->kv_self.used;
  15358. }
  15359. void llama_kv_cache_clear(struct llama_context * ctx) {
  15360. llama_kv_cache_clear(ctx->kv_self);
  15361. }
  15362. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  15363. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  15364. }
  15365. 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) {
  15366. if (seq_id_src == seq_id_dst) {
  15367. return;
  15368. }
  15369. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  15370. }
  15371. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  15372. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  15373. }
  15374. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  15375. if (delta == 0) {
  15376. return;
  15377. }
  15378. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  15379. }
  15380. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  15381. if (d == 1) {
  15382. return;
  15383. }
  15384. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  15385. }
  15386. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  15387. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  15388. }
  15389. void llama_kv_cache_defrag(struct llama_context * ctx) {
  15390. llama_kv_cache_defrag(ctx->kv_self);
  15391. }
  15392. void llama_kv_cache_update(struct llama_context * ctx) {
  15393. llama_kv_cache_update_internal(*ctx);
  15394. }
  15395. // deprecated
  15396. size_t llama_get_state_size(struct llama_context * ctx) {
  15397. return llama_state_get_size(ctx);
  15398. }
  15399. // deprecated
  15400. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  15401. return llama_state_get_data(ctx, dst, -1);
  15402. }
  15403. // deprecated
  15404. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  15405. return llama_state_set_data(ctx, src, -1);
  15406. }
  15407. // deprecated
  15408. 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) {
  15409. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  15410. }
  15411. // deprecated
  15412. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15413. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  15414. }
  15415. // TODO: replace all non-fatal assertions with returned errors or exceptions
  15416. struct llama_data_write {
  15417. virtual void write(const void * src, size_t size) = 0;
  15418. virtual void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) = 0;
  15419. virtual size_t get_size_written() = 0;
  15420. virtual ~llama_data_write() = default;
  15421. void write_string(const std::string & str) {
  15422. uint32_t str_size = str.size();
  15423. write(&str_size, sizeof(str_size));
  15424. write(str.data(), str_size);
  15425. }
  15426. void write_model_info(const struct llama_context * ctx) {
  15427. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  15428. write_string(arch_str);
  15429. // TODO: add more model-specific info which should prevent loading the session file if not identical
  15430. }
  15431. void write_rng(const std::mt19937 & rng) {
  15432. std::ostringstream rng_ss;
  15433. rng_ss << rng;
  15434. const std::string & rng_str = rng_ss.str();
  15435. write_string(rng_str);
  15436. }
  15437. void write_output_ids(struct llama_context * ctx) {
  15438. llama_output_reorder(ctx);
  15439. const uint32_t n_outputs = ctx->n_outputs;
  15440. std::vector<int32_t> output_pos;
  15441. const size_t n_batch = ctx->cparams.n_batch;
  15442. const auto & output_ids = ctx->output_ids;
  15443. GGML_ASSERT(n_outputs <= ctx->output_size);
  15444. output_pos.resize(n_outputs);
  15445. // build a more compact representation of the output ids
  15446. for (size_t i = 0; i < n_batch; ++i) {
  15447. // map an output id to a position in the batch
  15448. int32_t pos = output_ids[i];
  15449. if (pos >= 0) {
  15450. GGML_ASSERT((uint32_t) pos < n_outputs);
  15451. output_pos[pos] = i;
  15452. }
  15453. }
  15454. write(&n_outputs, sizeof(n_outputs));
  15455. if (n_outputs) {
  15456. write(output_pos.data(), n_outputs * sizeof(int32_t));
  15457. }
  15458. }
  15459. void write_logits(const struct llama_context * ctx) {
  15460. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  15461. write(&logits_size, sizeof(logits_size));
  15462. if (logits_size) {
  15463. write(ctx->logits, logits_size * sizeof(float));
  15464. }
  15465. }
  15466. void write_embeddings(const struct llama_context * ctx) {
  15467. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  15468. write(&embeddings_size, sizeof(embeddings_size));
  15469. if (embeddings_size) {
  15470. write(ctx->embd, embeddings_size * sizeof(float));
  15471. }
  15472. }
  15473. 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) {
  15474. for (const auto & range : cell_ranges) {
  15475. for (uint32_t i = range.first; i < range.second; ++i) {
  15476. const auto & cell = kv_self.cells[i];
  15477. const llama_pos pos = cell.pos;
  15478. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  15479. write(&pos, sizeof(pos));
  15480. write(&n_seq_id, sizeof(n_seq_id));
  15481. if (n_seq_id) {
  15482. for (auto seq_id : cell.seq_id) {
  15483. write(&seq_id, sizeof(seq_id));
  15484. }
  15485. }
  15486. }
  15487. }
  15488. }
  15489. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  15490. const struct llama_kv_cache & kv_self = ctx->kv_self;
  15491. const struct llama_hparams & hparams = ctx->model.hparams;
  15492. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  15493. const uint32_t n_layer = hparams.n_layer;
  15494. write(&v_trans, sizeof(v_trans));
  15495. write(&n_layer, sizeof(n_layer));
  15496. std::vector<uint8_t> tmp_buf;
  15497. // Iterate and write all the keys first, each row is a cell
  15498. // Get whole range at a time
  15499. for (uint32_t il = 0; il < n_layer; ++il) {
  15500. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  15501. // Write key type
  15502. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  15503. write(&k_type_i, sizeof(k_type_i));
  15504. // Write row size of key
  15505. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15506. write(&k_size_row, sizeof(k_size_row));
  15507. // Read each range of cells of k_size length each into tmp_buf and write out
  15508. for (const auto & range : cell_ranges) {
  15509. const size_t range_size = range.second - range.first;
  15510. const size_t buf_size = range_size * k_size_row;
  15511. write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
  15512. }
  15513. }
  15514. if (!kv_self.v_trans) {
  15515. for (uint32_t il = 0; il < n_layer; ++il) {
  15516. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  15517. // Write value type
  15518. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  15519. write(&v_type_i, sizeof(v_type_i));
  15520. // Write row size of value
  15521. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  15522. write(&v_size_row, sizeof(v_size_row));
  15523. // Read each range of cells of v_size length each into tmp_buf and write out
  15524. for (const auto & range : cell_ranges) {
  15525. const size_t range_size = range.second - range.first;
  15526. const size_t buf_size = range_size * v_size_row;
  15527. write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
  15528. }
  15529. }
  15530. } else {
  15531. // When v is transposed, we also need the element size and get the element ranges from each row
  15532. const uint32_t kv_size = kv_self.size;
  15533. for (uint32_t il = 0; il < n_layer; ++il) {
  15534. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  15535. // Write value type
  15536. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  15537. write(&v_type_i, sizeof(v_type_i));
  15538. // Write element size
  15539. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15540. write(&v_size_el, sizeof(v_size_el));
  15541. // Write GQA embedding size
  15542. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  15543. // For each row, we get the element values of each cell
  15544. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15545. // Read each range of cells of v_size_el length each into tmp_buf and write out
  15546. for (const auto & range : cell_ranges) {
  15547. const size_t range_size = range.second - range.first;
  15548. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  15549. const size_t buf_size = range_size * v_size_el;
  15550. write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
  15551. }
  15552. }
  15553. }
  15554. }
  15555. }
  15556. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  15557. const struct llama_kv_cache & kv_self = ctx->kv_self;
  15558. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  15559. uint32_t cell_count = 0;
  15560. // Count the number of cells with the specified seq_id
  15561. // Find all the ranges of cells with this seq id (or all, when -1)
  15562. uint32_t cell_range_begin = kv_self.size;
  15563. for (uint32_t i = 0; i < kv_self.size; ++i) {
  15564. const auto & cell = kv_self.cells[i];
  15565. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  15566. ++cell_count;
  15567. if (cell_range_begin == kv_self.size) {
  15568. cell_range_begin = i;
  15569. }
  15570. } else {
  15571. if (cell_range_begin != kv_self.size) {
  15572. cell_ranges.emplace_back(cell_range_begin, i);
  15573. cell_range_begin = kv_self.size;
  15574. }
  15575. }
  15576. }
  15577. if (cell_range_begin != kv_self.size) {
  15578. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  15579. }
  15580. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  15581. uint32_t cell_count_check = 0;
  15582. for (const auto & range : cell_ranges) {
  15583. cell_count_check += range.second - range.first;
  15584. }
  15585. GGML_ASSERT(cell_count == cell_count_check);
  15586. write(&cell_count, sizeof(cell_count));
  15587. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  15588. write_kv_cache_data(ctx, cell_ranges);
  15589. }
  15590. };
  15591. struct llama_data_read {
  15592. virtual const uint8_t * read(size_t size) = 0;
  15593. virtual void read_to(void * dst, size_t size) = 0;
  15594. virtual size_t get_size_read() = 0;
  15595. virtual ~llama_data_read() = default;
  15596. void read_string(std::string & str) {
  15597. uint32_t str_size;
  15598. read_to(&str_size, sizeof(str_size));
  15599. str.assign((const char *) read(str_size), str_size);
  15600. }
  15601. // validate model information
  15602. void read_model_info(const struct llama_context * ctx) {
  15603. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  15604. std::string arch_str;
  15605. read_string(arch_str);
  15606. if (cur_arch_str != arch_str) {
  15607. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  15608. }
  15609. // TODO: add more info which needs to be identical but which is not verified otherwise
  15610. }
  15611. void read_rng(std::mt19937 & rng) {
  15612. std::string rng_str;
  15613. read_string(rng_str);
  15614. std::istringstream rng_ss(rng_str);
  15615. rng_ss >> rng;
  15616. if (rng_ss.fail()) {
  15617. throw std::runtime_error("failed to load RNG state");
  15618. }
  15619. }
  15620. void read_output_ids(struct llama_context * ctx) {
  15621. std::vector<int32_t> output_pos;
  15622. uint32_t n_outputs;
  15623. read_to(&n_outputs, sizeof(n_outputs));
  15624. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  15625. throw std::runtime_error("could not reserve outputs");
  15626. }
  15627. if (n_outputs) {
  15628. output_pos.resize(n_outputs);
  15629. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  15630. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  15631. int32_t id = output_pos[i];
  15632. if ((uint32_t) id >= ctx->cparams.n_batch) {
  15633. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  15634. }
  15635. ctx->output_ids[id] = i;
  15636. }
  15637. ctx->n_outputs = n_outputs;
  15638. }
  15639. }
  15640. void read_logits(struct llama_context * ctx) {
  15641. uint64_t logits_size;
  15642. read_to(&logits_size, sizeof(logits_size));
  15643. if (ctx->logits_size < logits_size) {
  15644. throw std::runtime_error("logits buffer too small");
  15645. }
  15646. if (logits_size) {
  15647. read_to(ctx->logits, logits_size * sizeof(float));
  15648. }
  15649. }
  15650. void read_embeddings(struct llama_context * ctx) {
  15651. uint64_t embeddings_size;
  15652. read_to(&embeddings_size, sizeof(embeddings_size));
  15653. if (ctx->embd_size < embeddings_size) {
  15654. throw std::runtime_error("embeddings buffer too small");
  15655. }
  15656. if (embeddings_size) {
  15657. read_to(ctx->embd, embeddings_size * sizeof(float));
  15658. }
  15659. }
  15660. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  15661. struct llama_kv_cache & kv_self = ctx->kv_self;
  15662. if (dest_seq_id != -1) {
  15663. // single sequence
  15664. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  15665. llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
  15666. batch.n_tokens = cell_count;
  15667. batch.n_seq_tokens = cell_count;
  15668. batch.n_seqs = 1;
  15669. for (uint32_t i = 0; i < cell_count; ++i) {
  15670. llama_pos pos;
  15671. uint32_t n_seq_id;
  15672. read_to(&pos, sizeof(pos));
  15673. read_to(&n_seq_id, sizeof(n_seq_id));
  15674. if (n_seq_id != 0) {
  15675. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  15676. return false;
  15677. }
  15678. batch.pos[i] = pos;
  15679. }
  15680. batch.n_seq_id[0] = 1;
  15681. batch.seq_id[0] = &dest_seq_id;
  15682. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  15683. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  15684. return false;
  15685. }
  15686. // 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)
  15687. // Assume that this is one contiguous block of cells
  15688. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  15689. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  15690. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  15691. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  15692. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  15693. } else {
  15694. // whole KV cache restore
  15695. if (cell_count > kv_self.size) {
  15696. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  15697. return false;
  15698. }
  15699. llama_kv_cache_clear(kv_self);
  15700. for (uint32_t i = 0; i < cell_count; ++i) {
  15701. llama_kv_cell & cell = kv_self.cells[i];
  15702. llama_pos pos;
  15703. uint32_t n_seq_id;
  15704. read_to(&pos, sizeof(pos));
  15705. read_to(&n_seq_id, sizeof(n_seq_id));
  15706. cell.pos = pos;
  15707. for (uint32_t j = 0; j < n_seq_id; ++j) {
  15708. llama_seq_id seq_id;
  15709. read_to(&seq_id, sizeof(seq_id));
  15710. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  15711. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  15712. return false;
  15713. }
  15714. cell.seq_id.insert(seq_id);
  15715. if (kv_self.recurrent) {
  15716. int32_t & tail = kv_self.cells[seq_id].tail;
  15717. if (tail != -1) {
  15718. LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
  15719. return false;
  15720. }
  15721. tail = i;
  15722. }
  15723. }
  15724. }
  15725. kv_self.head = 0;
  15726. kv_self.used = cell_count;
  15727. }
  15728. if (kv_self.recurrent) {
  15729. for (uint32_t i = 0; i < cell_count; ++i) {
  15730. uint32_t cell_id = kv_self.head + i;
  15731. // make sure the recurrent states will keep their restored state
  15732. kv_self.cells[cell_id].src = cell_id;
  15733. }
  15734. }
  15735. return true;
  15736. }
  15737. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  15738. const struct llama_hparams & hparams = ctx->model.hparams;
  15739. struct llama_kv_cache & kv_self = ctx->kv_self;
  15740. uint32_t v_trans;
  15741. uint32_t n_layer;
  15742. read_to(&v_trans, sizeof(v_trans));
  15743. read_to(&n_layer, sizeof(n_layer));
  15744. if (n_layer != hparams.n_layer) {
  15745. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  15746. return false;
  15747. }
  15748. if (cell_count > kv_self.size) {
  15749. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  15750. return false;
  15751. }
  15752. if (kv_self.v_trans != (bool) v_trans) {
  15753. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  15754. return false;
  15755. }
  15756. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  15757. for (uint32_t il = 0; il < n_layer; ++il) {
  15758. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  15759. // Read type of key
  15760. int32_t k_type_i_ref;
  15761. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  15762. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  15763. if (k_type_i != k_type_i_ref) {
  15764. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  15765. return false;
  15766. }
  15767. // Read row size of key
  15768. uint64_t k_size_row_ref;
  15769. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  15770. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  15771. if (k_size_row != k_size_row_ref) {
  15772. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  15773. return false;
  15774. }
  15775. if (cell_count) {
  15776. // Read and set the keys for the whole cell range
  15777. 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);
  15778. }
  15779. }
  15780. if (!kv_self.v_trans) {
  15781. for (uint32_t il = 0; il < n_layer; ++il) {
  15782. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  15783. // Read type of value
  15784. int32_t v_type_i_ref;
  15785. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  15786. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  15787. if (v_type_i != v_type_i_ref) {
  15788. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  15789. return false;
  15790. }
  15791. // Read row size of value
  15792. uint64_t v_size_row_ref;
  15793. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  15794. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  15795. if (v_size_row != v_size_row_ref) {
  15796. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  15797. return false;
  15798. }
  15799. if (cell_count) {
  15800. // Read and set the values for the whole cell range
  15801. 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);
  15802. }
  15803. }
  15804. } else {
  15805. // For each layer, read the values for each cell (transposed)
  15806. for (uint32_t il = 0; il < n_layer; ++il) {
  15807. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  15808. // Read type of value
  15809. int32_t v_type_i_ref;
  15810. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  15811. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  15812. if (v_type_i != v_type_i_ref) {
  15813. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  15814. return false;
  15815. }
  15816. // Read element size of value
  15817. uint32_t v_size_el_ref;
  15818. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  15819. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  15820. if (v_size_el != v_size_el_ref) {
  15821. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  15822. return false;
  15823. }
  15824. // Read GQA embedding size
  15825. uint32_t n_embd_v_gqa_ref;
  15826. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  15827. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  15828. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  15829. return false;
  15830. }
  15831. if (cell_count) {
  15832. // For each row in the transposed matrix, read the values for the whole cell range
  15833. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  15834. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  15835. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  15836. }
  15837. }
  15838. }
  15839. }
  15840. return true;
  15841. }
  15842. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  15843. uint32_t cell_count;
  15844. read_to(&cell_count, sizeof(cell_count));
  15845. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  15846. if (!res) {
  15847. if (seq_id == -1) {
  15848. llama_kv_cache_clear(ctx);
  15849. } else {
  15850. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  15851. }
  15852. throw std::runtime_error("failed to restore kv cache");
  15853. }
  15854. }
  15855. };
  15856. struct llama_data_write_dummy : llama_data_write {
  15857. size_t size_written = 0;
  15858. llama_data_write_dummy() {}
  15859. void write(const void * /* src */, size_t size) override {
  15860. size_written += size;
  15861. }
  15862. void write_tensor_data(const struct ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
  15863. size_written += size;
  15864. }
  15865. size_t get_size_written() override {
  15866. return size_written;
  15867. }
  15868. };
  15869. struct llama_data_write_buffer : llama_data_write {
  15870. uint8_t * ptr;
  15871. size_t buf_size = 0;
  15872. size_t size_written = 0;
  15873. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  15874. void write(const void * src, size_t size) override {
  15875. if (size > buf_size) {
  15876. throw std::runtime_error("unexpectedly reached end of buffer");
  15877. }
  15878. memcpy(ptr, src, size);
  15879. ptr += size;
  15880. size_written += size;
  15881. buf_size -= size;
  15882. }
  15883. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  15884. if (size > buf_size) {
  15885. throw std::runtime_error("unexpectedly reached end of buffer");
  15886. }
  15887. ggml_backend_tensor_get(tensor, ptr, offset, size);
  15888. ptr += size;
  15889. size_written += size;
  15890. buf_size -= size;
  15891. }
  15892. size_t get_size_written() override {
  15893. return size_written;
  15894. }
  15895. };
  15896. struct llama_data_read_buffer : llama_data_read {
  15897. const uint8_t * ptr;
  15898. size_t buf_size = 0;
  15899. size_t size_read = 0;
  15900. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  15901. const uint8_t * read(size_t size) override {
  15902. const uint8_t * base_ptr = ptr;
  15903. if (size > buf_size) {
  15904. throw std::runtime_error("unexpectedly reached end of buffer");
  15905. }
  15906. ptr += size;
  15907. size_read += size;
  15908. buf_size -= size;
  15909. return base_ptr;
  15910. }
  15911. void read_to(void * dst, size_t size) override {
  15912. memcpy(dst, read(size), size);
  15913. }
  15914. size_t get_size_read() override {
  15915. return size_read;
  15916. }
  15917. };
  15918. struct llama_data_write_file : llama_data_write {
  15919. llama_file * file;
  15920. size_t size_written = 0;
  15921. std::vector<uint8_t> temp_buffer;
  15922. llama_data_write_file(llama_file * f) : file(f) {}
  15923. void write(const void * src, size_t size) override {
  15924. file->write_raw(src, size);
  15925. size_written += size;
  15926. }
  15927. void write_tensor_data(const struct ggml_tensor * tensor, size_t offset, size_t size) override {
  15928. temp_buffer.resize(size);
  15929. ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
  15930. write(temp_buffer.data(), temp_buffer.size());
  15931. }
  15932. size_t get_size_written() override {
  15933. return size_written;
  15934. }
  15935. };
  15936. struct llama_data_read_file : llama_data_read {
  15937. llama_file * file;
  15938. size_t size_read = 0;
  15939. std::vector<uint8_t> temp_buffer;
  15940. llama_data_read_file(llama_file * f) : file(f) {}
  15941. void read_to(void * dst, size_t size) override {
  15942. file->read_raw(dst, size);
  15943. size_read += size;
  15944. }
  15945. const uint8_t * read(size_t size) override {
  15946. temp_buffer.resize(size);
  15947. read_to(temp_buffer.data(), size);
  15948. return temp_buffer.data();
  15949. }
  15950. size_t get_size_read() override {
  15951. return size_read;
  15952. }
  15953. };
  15954. /** copy state data into either a buffer or file depending on the passed in context
  15955. *
  15956. * file context:
  15957. * llama_file file("/path", "wb");
  15958. * llama_data_write_file data_ctx(&file);
  15959. * llama_state_get_data_internal(ctx, data_ctx);
  15960. *
  15961. * buffer context:
  15962. * std::vector<uint8_t> buf(max_size, 0);
  15963. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  15964. * llama_state_get_data_internal(ctx, data_ctx);
  15965. *
  15966. */
  15967. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  15968. llama_synchronize(ctx);
  15969. data_ctx.write_model_info(ctx);
  15970. data_ctx.write_rng(ctx->sampling.rng);
  15971. // copy outputs
  15972. data_ctx.write_output_ids(ctx);
  15973. data_ctx.write_logits(ctx);
  15974. data_ctx.write_embeddings(ctx);
  15975. data_ctx.write_kv_cache(ctx);
  15976. return data_ctx.get_size_written();
  15977. }
  15978. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  15979. llama_data_write_buffer data_ctx(dst, size);
  15980. try {
  15981. return llama_state_get_data_internal(ctx, data_ctx);
  15982. } catch (const std::exception & err) {
  15983. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  15984. return 0;
  15985. }
  15986. }
  15987. // Returns the *actual* size of the state.
  15988. // Intended to be used when saving to state to a buffer.
  15989. size_t llama_state_get_size(struct llama_context * ctx) {
  15990. llama_data_write_dummy data_ctx;
  15991. try {
  15992. return llama_state_get_data_internal(ctx, data_ctx);
  15993. } catch (const std::exception & err) {
  15994. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  15995. return 0;
  15996. }
  15997. }
  15998. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  15999. llama_synchronize(ctx);
  16000. data_ctx.read_model_info(ctx);
  16001. // set rng
  16002. data_ctx.read_rng(ctx->sampling.rng);
  16003. // set outputs
  16004. data_ctx.read_output_ids(ctx);
  16005. data_ctx.read_logits(ctx);
  16006. data_ctx.read_embeddings(ctx);
  16007. data_ctx.read_kv_cache(ctx);
  16008. return data_ctx.get_size_read();
  16009. }
  16010. // Sets the state reading from the specified source address
  16011. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  16012. llama_data_read_buffer data_ctx(src, size);
  16013. try {
  16014. return llama_state_set_data_internal(ctx, data_ctx);
  16015. } catch (const std::exception & err) {
  16016. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  16017. return 0;
  16018. }
  16019. }
  16020. 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) {
  16021. llama_file file(path_session, "rb");
  16022. // sanity checks
  16023. {
  16024. const uint32_t magic = file.read_u32();
  16025. const uint32_t version = file.read_u32();
  16026. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  16027. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  16028. return false;
  16029. }
  16030. }
  16031. // load the prompt
  16032. {
  16033. const uint32_t n_token_count = file.read_u32();
  16034. if (n_token_count > n_token_capacity) {
  16035. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  16036. return false;
  16037. }
  16038. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  16039. *n_token_count_out = n_token_count;
  16040. }
  16041. // restore the context state
  16042. {
  16043. const size_t n_state_size_cur = file.size - file.tell();
  16044. llama_data_read_file data_ctx(&file);
  16045. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  16046. if (n_read != n_state_size_cur) {
  16047. 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);
  16048. return false;
  16049. }
  16050. }
  16051. return true;
  16052. }
  16053. 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) {
  16054. try {
  16055. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  16056. } catch (const std::exception & err) {
  16057. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  16058. return false;
  16059. }
  16060. }
  16061. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  16062. llama_file file(path_session, "wb");
  16063. file.write_u32(LLAMA_SESSION_MAGIC);
  16064. file.write_u32(LLAMA_SESSION_VERSION);
  16065. // save the prompt
  16066. file.write_u32((uint32_t) n_token_count);
  16067. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  16068. // save the context state using stream saving
  16069. llama_data_write_file data_ctx(&file);
  16070. llama_state_get_data_internal(ctx, data_ctx);
  16071. return true;
  16072. }
  16073. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  16074. try {
  16075. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  16076. } catch (const std::exception & err) {
  16077. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  16078. return false;
  16079. }
  16080. }
  16081. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  16082. llama_synchronize(ctx);
  16083. data_ctx.write_kv_cache(ctx, seq_id);
  16084. return data_ctx.get_size_written();
  16085. }
  16086. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  16087. llama_data_write_dummy data_ctx;
  16088. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  16089. }
  16090. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  16091. llama_data_write_buffer data_ctx(dst, size);
  16092. try {
  16093. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  16094. } catch (const std::exception & err) {
  16095. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  16096. return 0;
  16097. }
  16098. }
  16099. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  16100. llama_synchronize(ctx);
  16101. data_ctx.read_kv_cache(ctx, dest_seq_id);
  16102. return data_ctx.get_size_read();
  16103. }
  16104. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  16105. llama_data_read_buffer data_ctx(src, size);
  16106. try {
  16107. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  16108. } catch (const std::exception & err) {
  16109. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  16110. return 0;
  16111. }
  16112. }
  16113. 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) {
  16114. llama_file file(filepath, "wb");
  16115. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  16116. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  16117. // save the prompt
  16118. file.write_u32((uint32_t) n_token_count);
  16119. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  16120. // save the context state using stream saving
  16121. llama_data_write_file data_ctx(&file);
  16122. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  16123. const size_t res = file.tell();
  16124. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  16125. return res;
  16126. }
  16127. 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) {
  16128. llama_file file(filepath, "rb");
  16129. // version checks
  16130. {
  16131. const uint32_t magic = file.read_u32();
  16132. const uint32_t version = file.read_u32();
  16133. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  16134. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  16135. return 0;
  16136. }
  16137. }
  16138. // load the prompt
  16139. {
  16140. const uint32_t n_token_count = file.read_u32();
  16141. if (n_token_count > n_token_capacity) {
  16142. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  16143. return 0;
  16144. }
  16145. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  16146. *n_token_count_out = n_token_count;
  16147. }
  16148. // restore the context state
  16149. {
  16150. const size_t state_size = file.size - file.tell();
  16151. llama_data_read_file data_ctx(&file);
  16152. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  16153. if (!nread) {
  16154. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  16155. return 0;
  16156. }
  16157. GGML_ASSERT(nread <= state_size);
  16158. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  16159. }
  16160. return file.tell();
  16161. }
  16162. 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) {
  16163. try {
  16164. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  16165. } catch (const std::exception & err) {
  16166. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  16167. return 0;
  16168. }
  16169. }
  16170. 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) {
  16171. try {
  16172. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  16173. } catch (const std::exception & err) {
  16174. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  16175. return 0;
  16176. }
  16177. }
  16178. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  16179. ctx->cparams.n_threads = n_threads;
  16180. ctx->cparams.n_threads_batch = n_threads_batch;
  16181. }
  16182. uint32_t llama_n_threads(struct llama_context * ctx) {
  16183. return ctx->cparams.n_threads;
  16184. }
  16185. uint32_t llama_n_threads_batch(struct llama_context * ctx) {
  16186. return ctx->cparams.n_threads_batch;
  16187. }
  16188. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  16189. ctx->abort_callback = abort_callback;
  16190. ctx->abort_callback_data = abort_callback_data;
  16191. }
  16192. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  16193. ctx->cparams.embeddings = embeddings;
  16194. }
  16195. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  16196. ctx->cparams.causal_attn = causal_attn;
  16197. }
  16198. struct llama_batch llama_batch_get_one(
  16199. llama_token * tokens,
  16200. int32_t n_tokens,
  16201. llama_pos pos_0,
  16202. llama_seq_id seq_id) {
  16203. return {
  16204. /*n_tokens =*/ n_tokens,
  16205. /*tokens =*/ tokens,
  16206. /*embd =*/ nullptr,
  16207. /*pos =*/ nullptr,
  16208. /*n_seq_id =*/ nullptr,
  16209. /*seq_id =*/ nullptr,
  16210. /*logits =*/ nullptr,
  16211. /*all_pos_0 =*/ pos_0,
  16212. /*all_pos_1 =*/ 1,
  16213. /*all_seq_id =*/ seq_id,
  16214. };
  16215. }
  16216. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  16217. llama_batch batch = {
  16218. /*n_tokens =*/ 0,
  16219. /*tokens =*/ nullptr,
  16220. /*embd =*/ nullptr,
  16221. /*pos =*/ nullptr,
  16222. /*n_seq_id =*/ nullptr,
  16223. /*seq_id =*/ nullptr,
  16224. /*logits =*/ nullptr,
  16225. /*all_pos_0 =*/ 0,
  16226. /*all_pos_1 =*/ 0,
  16227. /*all_seq_id =*/ 0,
  16228. };
  16229. if (embd) {
  16230. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  16231. } else {
  16232. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  16233. }
  16234. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  16235. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  16236. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  16237. for (int i = 0; i < n_tokens_alloc; ++i) {
  16238. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  16239. }
  16240. batch.seq_id[n_tokens_alloc] = nullptr;
  16241. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  16242. return batch;
  16243. }
  16244. void llama_batch_free(struct llama_batch batch) {
  16245. if (batch.token) free(batch.token);
  16246. if (batch.embd) free(batch.embd);
  16247. if (batch.pos) free(batch.pos);
  16248. if (batch.n_seq_id) free(batch.n_seq_id);
  16249. if (batch.seq_id) {
  16250. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  16251. free(batch.seq_id[i]);
  16252. }
  16253. free(batch.seq_id);
  16254. }
  16255. if (batch.logits) free(batch.logits);
  16256. }
  16257. int32_t llama_encode(
  16258. struct llama_context * ctx,
  16259. struct llama_batch batch) {
  16260. const int ret = llama_encode_internal(*ctx, batch);
  16261. if (ret < 0) {
  16262. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  16263. }
  16264. return ret;
  16265. }
  16266. int32_t llama_decode(
  16267. struct llama_context * ctx,
  16268. struct llama_batch batch) {
  16269. const int ret = llama_decode_internal(*ctx, batch);
  16270. if (ret < 0) {
  16271. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  16272. }
  16273. return ret;
  16274. }
  16275. void llama_synchronize(struct llama_context * ctx) {
  16276. ggml_backend_sched_synchronize(ctx->sched);
  16277. // FIXME: if multiple single tokens are evaluated without a synchronization,
  16278. // the stats will be added to the prompt evaluation stats
  16279. // this should only happen when using batch size 1 to evaluate a batch
  16280. // add the evaluation to the stats
  16281. if (ctx->n_queued_tokens == 1) {
  16282. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  16283. ctx->n_eval++;
  16284. } else if (ctx->n_queued_tokens > 1) {
  16285. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  16286. ctx->n_p_eval += ctx->n_queued_tokens;
  16287. }
  16288. // get a more accurate load time, upon first eval
  16289. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  16290. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  16291. ctx->has_evaluated_once = true;
  16292. }
  16293. ctx->n_queued_tokens = 0;
  16294. ctx->t_compute_start_us = 0;
  16295. }
  16296. float * llama_get_logits(struct llama_context * ctx) {
  16297. llama_synchronize(ctx);
  16298. // reorder logits for backward compatibility
  16299. // TODO: maybe deprecate this
  16300. llama_output_reorder(ctx);
  16301. return ctx->logits;
  16302. }
  16303. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  16304. int32_t j = -1;
  16305. llama_synchronize(ctx);
  16306. try {
  16307. if (ctx->logits == nullptr) {
  16308. throw std::runtime_error("no logits");
  16309. }
  16310. if (i < 0) {
  16311. j = ctx->n_outputs + i;
  16312. if (j < 0) {
  16313. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  16314. }
  16315. } else if ((size_t) i >= ctx->output_ids.size()) {
  16316. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  16317. } else {
  16318. j = ctx->output_ids[i];
  16319. }
  16320. if (j < 0) {
  16321. throw std::runtime_error(format("batch.logits[%d] != true", i));
  16322. }
  16323. if (j >= ctx->n_outputs) {
  16324. // This should not happen
  16325. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  16326. }
  16327. return ctx->logits + j*ctx->model.hparams.n_vocab;
  16328. } catch (const std::exception & err) {
  16329. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  16330. #ifndef NDEBUG
  16331. GGML_ABORT("fatal error");
  16332. #endif
  16333. return nullptr;
  16334. }
  16335. }
  16336. float * llama_get_embeddings(struct llama_context * ctx) {
  16337. llama_synchronize(ctx);
  16338. // reorder embeddings for backward compatibility
  16339. // TODO: maybe deprecate this
  16340. llama_output_reorder(ctx);
  16341. return ctx->embd;
  16342. }
  16343. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  16344. int32_t j = -1;
  16345. llama_synchronize(ctx);
  16346. try {
  16347. if (ctx->embd == nullptr) {
  16348. throw std::runtime_error("no embeddings");
  16349. }
  16350. if (i < 0) {
  16351. j = ctx->n_outputs + i;
  16352. if (j < 0) {
  16353. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  16354. }
  16355. } else if ((size_t) i >= ctx->output_ids.size()) {
  16356. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  16357. } else {
  16358. j = ctx->output_ids[i];
  16359. }
  16360. if (j < 0) {
  16361. throw std::runtime_error(format("batch.logits[%d] != true", i));
  16362. }
  16363. if (j >= ctx->n_outputs) {
  16364. // This should not happen
  16365. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  16366. }
  16367. return ctx->embd + j*ctx->model.hparams.n_embd;
  16368. } catch (const std::exception & err) {
  16369. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  16370. #ifndef NDEBUG
  16371. GGML_ABORT("fatal error");
  16372. #endif
  16373. return nullptr;
  16374. }
  16375. }
  16376. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  16377. llama_synchronize(ctx);
  16378. auto it = ctx->embd_seq.find(seq_id);
  16379. if (it == ctx->embd_seq.end()) {
  16380. return nullptr;
  16381. }
  16382. return it->second.data();
  16383. }
  16384. //
  16385. // vocab
  16386. //
  16387. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  16388. return llama_token_get_text_impl(model->vocab, token);
  16389. }
  16390. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  16391. return llama_token_get_score_impl(model->vocab, token);
  16392. }
  16393. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  16394. return llama_token_get_attr_impl(model->vocab, token);
  16395. }
  16396. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  16397. return llama_token_is_eog_impl(model->vocab, token);
  16398. }
  16399. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  16400. return llama_token_is_control_impl(model->vocab, token);
  16401. }
  16402. llama_token llama_token_bos(const struct llama_model * model) {
  16403. return llama_token_bos_impl(model->vocab);
  16404. }
  16405. llama_token llama_token_eos(const struct llama_model * model) {
  16406. return llama_token_eos_impl(model->vocab);
  16407. }
  16408. llama_token llama_token_cls(const struct llama_model * model) {
  16409. return llama_token_cls_impl(model->vocab);
  16410. }
  16411. llama_token llama_token_sep(const struct llama_model * model) {
  16412. return llama_token_sep_impl(model->vocab);
  16413. }
  16414. llama_token llama_token_nl (const struct llama_model * model) {
  16415. return llama_token_nl_impl(model->vocab);
  16416. }
  16417. llama_token llama_token_pad(const struct llama_model * model) {
  16418. return llama_token_pad_impl(model->vocab);
  16419. }
  16420. bool llama_add_bos_token(const struct llama_model * model) {
  16421. return llama_add_bos_token_impl(model->vocab);
  16422. }
  16423. bool llama_add_eos_token(const struct llama_model * model) {
  16424. return llama_add_eos_token_impl(model->vocab);
  16425. }
  16426. llama_token llama_token_prefix(const struct llama_model * model) {
  16427. return llama_token_prefix_impl(model->vocab);
  16428. }
  16429. llama_token llama_token_middle(const struct llama_model * model) {
  16430. return llama_token_middle_impl(model->vocab);
  16431. }
  16432. llama_token llama_token_suffix(const struct llama_model * model) {
  16433. return llama_token_suffix_impl(model->vocab);
  16434. }
  16435. llama_token llama_token_eot(const struct llama_model * model) {
  16436. return llama_token_eot_impl(model->vocab);
  16437. }
  16438. //
  16439. // tokenization
  16440. //
  16441. int32_t llama_tokenize(
  16442. const struct llama_model * model,
  16443. const char * text,
  16444. int32_t text_len,
  16445. llama_token * tokens,
  16446. int32_t n_tokens_max,
  16447. bool add_special,
  16448. bool parse_special) {
  16449. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  16450. }
  16451. int32_t llama_token_to_piece(
  16452. const struct llama_model * model,
  16453. llama_token token,
  16454. char * buf,
  16455. int32_t length,
  16456. int32_t lstrip,
  16457. bool special) {
  16458. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  16459. }
  16460. int32_t llama_detokenize(
  16461. const struct llama_model * model,
  16462. const llama_token * tokens,
  16463. int32_t n_tokens,
  16464. char * text,
  16465. int32_t text_len_max,
  16466. bool remove_special,
  16467. bool unparse_special) {
  16468. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  16469. }
  16470. //
  16471. // chat templates
  16472. //
  16473. // Simple version of "llama_apply_chat_template" that only works with strings
  16474. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  16475. static int32_t llama_chat_apply_template_internal(
  16476. const std::string & tmpl,
  16477. const std::vector<const llama_chat_message *> & chat,
  16478. std::string & dest, bool add_ass) {
  16479. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  16480. std::stringstream ss;
  16481. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  16482. return tmpl.find(haystack) != std::string::npos;
  16483. };
  16484. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  16485. // chatml template
  16486. for (auto message : chat) {
  16487. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  16488. }
  16489. if (add_ass) {
  16490. ss << "<|im_start|>assistant\n";
  16491. }
  16492. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  16493. // llama2 template and its variants
  16494. // [variant] support system message
  16495. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  16496. // [variant] space before + after response
  16497. bool space_around_response = tmpl_contains("' ' + eos_token");
  16498. // [variant] add BOS inside history
  16499. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  16500. // [variant] trim spaces from the input message
  16501. bool strip_message = tmpl_contains("content.strip()");
  16502. // construct the prompt
  16503. bool is_inside_turn = true; // skip BOS at the beginning
  16504. ss << "[INST] ";
  16505. for (auto message : chat) {
  16506. std::string content = strip_message ? trim(message->content) : message->content;
  16507. std::string role(message->role);
  16508. if (!is_inside_turn) {
  16509. is_inside_turn = true;
  16510. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  16511. }
  16512. if (role == "system") {
  16513. if (support_system_message) {
  16514. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  16515. } else {
  16516. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  16517. ss << content << "\n";
  16518. }
  16519. } else if (role == "user") {
  16520. ss << content << " [/INST]";
  16521. } else {
  16522. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  16523. is_inside_turn = false;
  16524. }
  16525. }
  16526. // llama2 templates seem to not care about "add_generation_prompt"
  16527. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  16528. // Phi 3
  16529. for (auto message : chat) {
  16530. std::string role(message->role);
  16531. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  16532. }
  16533. if (add_ass) {
  16534. ss << "<|assistant|>\n";
  16535. }
  16536. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  16537. // zephyr template
  16538. for (auto message : chat) {
  16539. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  16540. }
  16541. if (add_ass) {
  16542. ss << "<|assistant|>\n";
  16543. }
  16544. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  16545. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  16546. for (auto message : chat) {
  16547. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  16548. ss << bos << message->role << "\n" << message->content << "</s>\n";
  16549. }
  16550. if (add_ass) {
  16551. ss << "<s>assistant\n";
  16552. }
  16553. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  16554. // google/gemma-7b-it
  16555. std::string system_prompt = "";
  16556. for (auto message : chat) {
  16557. std::string role(message->role);
  16558. if (role == "system") {
  16559. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  16560. system_prompt = trim(message->content);
  16561. continue;
  16562. }
  16563. // in gemma, "assistant" is "model"
  16564. role = role == "assistant" ? "model" : message->role;
  16565. ss << "<start_of_turn>" << role << "\n";
  16566. if (!system_prompt.empty() && role != "model") {
  16567. ss << system_prompt << "\n\n";
  16568. system_prompt = "";
  16569. }
  16570. ss << trim(message->content) << "<end_of_turn>\n";
  16571. }
  16572. if (add_ass) {
  16573. ss << "<start_of_turn>model\n";
  16574. }
  16575. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  16576. // OrionStarAI/Orion-14B-Chat
  16577. std::string system_prompt = "";
  16578. for (auto message : chat) {
  16579. std::string role(message->role);
  16580. if (role == "system") {
  16581. // there is no system message support, we will merge it with user prompt
  16582. system_prompt = message->content;
  16583. continue;
  16584. } else if (role == "user") {
  16585. ss << "Human: ";
  16586. if (!system_prompt.empty()) {
  16587. ss << system_prompt << "\n\n";
  16588. system_prompt = "";
  16589. }
  16590. ss << message->content << "\n\nAssistant: </s>";
  16591. } else {
  16592. ss << message->content << "</s>";
  16593. }
  16594. }
  16595. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  16596. // openchat/openchat-3.5-0106,
  16597. for (auto message : chat) {
  16598. std::string role(message->role);
  16599. if (role == "system") {
  16600. ss << message->content << "<|end_of_turn|>";
  16601. } else {
  16602. role[0] = toupper(role[0]);
  16603. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  16604. }
  16605. }
  16606. if (add_ass) {
  16607. ss << "GPT4 Correct Assistant:";
  16608. }
  16609. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  16610. // eachadea/vicuna-13b-1.1 (and Orca variant)
  16611. for (auto message : chat) {
  16612. std::string role(message->role);
  16613. if (role == "system") {
  16614. // Orca-Vicuna variant uses a system prefix
  16615. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  16616. ss << "SYSTEM: " << message->content << "\n";
  16617. } else {
  16618. ss << message->content << "\n\n";
  16619. }
  16620. } else if (role == "user") {
  16621. ss << "USER: " << message->content << "\n";
  16622. } else if (role == "assistant") {
  16623. ss << "ASSISTANT: " << message->content << "</s>\n";
  16624. }
  16625. }
  16626. if (add_ass) {
  16627. ss << "ASSISTANT:";
  16628. }
  16629. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  16630. // deepseek-ai/deepseek-coder-33b-instruct
  16631. for (auto message : chat) {
  16632. std::string role(message->role);
  16633. if (role == "system") {
  16634. ss << message->content;
  16635. } else if (role == "user") {
  16636. ss << "### Instruction:\n" << message->content << "\n";
  16637. } else if (role == "assistant") {
  16638. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  16639. }
  16640. }
  16641. if (add_ass) {
  16642. ss << "### Response:\n";
  16643. }
  16644. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  16645. // CohereForAI/c4ai-command-r-plus
  16646. for (auto message : chat) {
  16647. std::string role(message->role);
  16648. if (role == "system") {
  16649. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  16650. } else if (role == "user") {
  16651. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  16652. } else if (role == "assistant") {
  16653. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  16654. }
  16655. }
  16656. if (add_ass) {
  16657. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  16658. }
  16659. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  16660. // Llama 3
  16661. for (auto message : chat) {
  16662. std::string role(message->role);
  16663. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  16664. }
  16665. if (add_ass) {
  16666. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  16667. }
  16668. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  16669. // chatglm3-6b
  16670. ss << "[gMASK]" << "sop";
  16671. for (auto message : chat) {
  16672. std::string role(message->role);
  16673. ss << "<|" << role << "|>" << "\n " << message->content;
  16674. }
  16675. if (add_ass) {
  16676. ss << "<|assistant|>";
  16677. }
  16678. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  16679. ss << "[gMASK]" << "<sop>";
  16680. for (auto message : chat) {
  16681. std::string role(message->role);
  16682. ss << "<|" << role << "|>" << "\n" << message->content;
  16683. }
  16684. if (add_ass) {
  16685. ss << "<|assistant|>";
  16686. }
  16687. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  16688. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  16689. for (auto message : chat) {
  16690. std::string role(message->role);
  16691. if (role == "user") {
  16692. ss << LU8("<用户>");
  16693. ss << trim(message->content);
  16694. ss << "<AI>";
  16695. } else {
  16696. ss << trim(message->content);
  16697. }
  16698. }
  16699. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  16700. // DeepSeek-V2
  16701. for (auto message : chat) {
  16702. std::string role(message->role);
  16703. if (role == "system") {
  16704. ss << message->content << "\n\n";
  16705. } else if (role == "user") {
  16706. ss << "User: " << message->content << "\n\n";
  16707. } else if (role == "assistant") {
  16708. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  16709. }
  16710. }
  16711. if (add_ass) {
  16712. ss << "Assistant:";
  16713. }
  16714. } else if (tmpl == "exaone3" || (tmpl_contains("[|system|]") && tmpl_contains("[|assistant|]") && tmpl_contains("[|endofturn|]"))) {
  16715. // ref: https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct/discussions/8#66bae61b1893d14ee8ed85bb
  16716. // EXAONE-3.0-7.8B-Instruct
  16717. for (auto message : chat) {
  16718. std::string role(message->role);
  16719. if (role == "system") {
  16720. ss << "[|system|]" << trim(message->content) << "[|endofturn|]\n";
  16721. } else if (role == "user") {
  16722. ss << "[|user|]" << trim(message->content) << "\n";
  16723. } else if (role == "assistant") {
  16724. ss << "[|assistant|]" << trim(message->content) << "[|endofturn|]\n";
  16725. }
  16726. }
  16727. if (add_ass) {
  16728. ss << "[|assistant|]";
  16729. }
  16730. } else {
  16731. // template not supported
  16732. return -1;
  16733. }
  16734. dest = ss.str();
  16735. return dest.size();
  16736. }
  16737. int32_t llama_chat_apply_template(
  16738. const struct llama_model * model,
  16739. const char * tmpl,
  16740. const struct llama_chat_message * chat,
  16741. size_t n_msg,
  16742. bool add_ass,
  16743. char * buf,
  16744. int32_t length) {
  16745. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  16746. if (tmpl == nullptr) {
  16747. GGML_ASSERT(model != nullptr);
  16748. // load template from model
  16749. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  16750. std::string template_key = "tokenizer.chat_template";
  16751. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  16752. if (res < 0) {
  16753. // worst case: there is no information about template, we will use chatml by default
  16754. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  16755. } else {
  16756. curr_tmpl = std::string(model_template.data(), model_template.size());
  16757. }
  16758. }
  16759. // format the chat to string
  16760. std::vector<const llama_chat_message *> chat_vec;
  16761. chat_vec.resize(n_msg);
  16762. for (size_t i = 0; i < n_msg; i++) {
  16763. chat_vec[i] = &chat[i];
  16764. }
  16765. std::string formatted_chat;
  16766. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  16767. if (res < 0) {
  16768. return res;
  16769. }
  16770. if (buf && length > 0) {
  16771. strncpy(buf, formatted_chat.c_str(), length);
  16772. }
  16773. return res;
  16774. }
  16775. //
  16776. // grammar
  16777. //
  16778. struct llama_grammar * llama_grammar_init(
  16779. const llama_grammar_element ** rules,
  16780. size_t n_rules,
  16781. size_t start_rule_index) {
  16782. return llama_grammar_init_impl(rules, n_rules, start_rule_index);
  16783. }
  16784. void llama_grammar_free(struct llama_grammar * grammar) {
  16785. llama_grammar_free_impl(grammar);
  16786. }
  16787. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  16788. return llama_grammar_copy_impl(grammar);
  16789. }
  16790. void llama_grammar_sample(
  16791. const struct llama_grammar * grammar,
  16792. const struct llama_context * ctx,
  16793. llama_token_data_array * candidates) {
  16794. llama_grammar_sample_impl(grammar, &ctx->model.vocab, &ctx->sampling, candidates);
  16795. }
  16796. void llama_sample_grammar(
  16797. struct llama_context * ctx,
  16798. llama_token_data_array * candidates,
  16799. const struct llama_grammar * grammar) {
  16800. llama_grammar_sample(grammar, ctx, candidates);
  16801. }
  16802. void llama_grammar_accept_token(
  16803. struct llama_grammar * grammar,
  16804. struct llama_context * ctx,
  16805. llama_token token) {
  16806. llama_grammar_accept_token_impl(grammar, &ctx->model.vocab, &ctx->sampling, token);
  16807. }
  16808. //
  16809. // sampling
  16810. //
  16811. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  16812. llama_set_rng_seed_impl(&ctx->sampling, seed);
  16813. }
  16814. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  16815. llama_sample_softmax_impl(ctx ? &ctx->sampling : nullptr, candidates);
  16816. }
  16817. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  16818. llama_sample_top_k_impl(ctx ? &ctx->sampling : nullptr, candidates, k, min_keep);
  16819. }
  16820. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  16821. llama_sample_top_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  16822. }
  16823. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  16824. llama_sample_min_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  16825. }
  16826. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  16827. llama_sample_tail_free_impl(ctx ? &ctx->sampling : nullptr, candidates, z, min_keep);
  16828. }
  16829. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  16830. llama_sample_typical_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  16831. }
  16832. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  16833. llama_sample_entropy_impl(ctx ? &ctx->sampling : nullptr, candidates_p, min_temp, max_temp, exponent_val);
  16834. }
  16835. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  16836. llama_sample_temp_impl(ctx ? &ctx->sampling : nullptr, candidates_p, temp);
  16837. }
  16838. void llama_sample_repetition_penalties(
  16839. struct llama_context * ctx,
  16840. llama_token_data_array * candidates,
  16841. const llama_token * last_tokens,
  16842. size_t penalty_last_n,
  16843. float penalty_repeat,
  16844. float penalty_freq,
  16845. float penalty_present) {
  16846. llama_sample_repetition_penalties_impl(ctx ? &ctx->sampling : nullptr, candidates, last_tokens, penalty_last_n, penalty_repeat, penalty_freq, penalty_present);
  16847. }
  16848. void llama_sample_apply_guidance(
  16849. struct llama_context * ctx,
  16850. float * logits,
  16851. float * logits_guidance,
  16852. float scale) {
  16853. llama_sample_apply_guidance_impl(&ctx->sampling, logits, logits_guidance, scale);
  16854. }
  16855. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  16856. return llama_sample_token_mirostat_impl(&ctx->sampling, candidates, tau, eta, m, mu);
  16857. }
  16858. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  16859. return llama_sample_token_mirostat_v2_impl(ctx ? &ctx->sampling : nullptr, candidates, tau, eta, mu);
  16860. }
  16861. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  16862. return llama_sample_token_greedy_impl(ctx ? &ctx->sampling : nullptr, candidates);
  16863. }
  16864. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  16865. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, rng);
  16866. }
  16867. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  16868. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, ctx->sampling.rng);
  16869. }
  16870. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  16871. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  16872. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  16873. return strlen(split_path);
  16874. }
  16875. return 0;
  16876. }
  16877. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  16878. std::string str_split_path(split_path);
  16879. char postfix[32];
  16880. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  16881. std::string str_postfix(postfix);
  16882. // check if dest ends with postfix
  16883. int size_prefix = str_split_path.size() - str_postfix.size();
  16884. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  16885. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  16886. return size_prefix;
  16887. }
  16888. return 0;
  16889. }
  16890. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  16891. struct llama_timings result = {
  16892. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  16893. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  16894. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  16895. /*.t_sample_ms =*/ 1e-3 * ctx->sampling.t_sample_us,
  16896. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  16897. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  16898. /*.n_sample =*/ std::max(1, ctx->sampling.n_sample),
  16899. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  16900. /*.n_eval =*/ std::max(1, ctx->n_eval),
  16901. };
  16902. return result;
  16903. }
  16904. void llama_print_timings(struct llama_context * ctx) {
  16905. const llama_timings timings = llama_get_timings(ctx);
  16906. LLAMA_LOG_INFO("\n");
  16907. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  16908. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  16909. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  16910. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  16911. __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);
  16912. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  16913. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  16914. 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));
  16915. }
  16916. void llama_reset_timings(struct llama_context * ctx) {
  16917. ctx->t_start_us = ggml_time_us();
  16918. ctx->t_eval_us = ctx->n_eval = 0;
  16919. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  16920. ctx->sampling.reset_timings();
  16921. }
  16922. const char * llama_print_system_info(void) {
  16923. static std::string s;
  16924. s = "";
  16925. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  16926. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  16927. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  16928. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  16929. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  16930. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  16931. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  16932. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  16933. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  16934. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  16935. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  16936. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  16937. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  16938. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  16939. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  16940. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  16941. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  16942. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  16943. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  16944. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  16945. return s.c_str();
  16946. }
  16947. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  16948. fprintf(stream, "\n");
  16949. fprintf(stream, "###########\n");
  16950. fprintf(stream, "# Timings #\n");
  16951. fprintf(stream, "###########\n");
  16952. fprintf(stream, "\n");
  16953. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  16954. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  16955. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  16956. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  16957. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  16958. 1.0e-3 * ctx->sampling.t_sample_us / ctx->sampling.n_sample);
  16959. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  16960. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  16961. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->sampling.n_sample);
  16962. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  16963. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  16964. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  16965. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->sampling.t_sample_us);
  16966. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  16967. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  16968. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  16969. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  16970. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  16971. 1.0e6 * ctx->sampling.n_sample / ctx->sampling.t_sample_us);
  16972. }
  16973. // For internal test use
  16974. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  16975. struct llama_context * ctx
  16976. ) {
  16977. return ctx->model.tensors_by_name;
  16978. }
  16979. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  16980. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  16981. g_state.log_callback_user_data = user_data;
  16982. #ifdef GGML_USE_METAL
  16983. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  16984. #elif defined(GGML_USE_CUDA)
  16985. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  16986. #elif defined(GGML_USE_CANN)
  16987. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  16988. #endif
  16989. }
  16990. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  16991. va_list args_copy;
  16992. va_copy(args_copy, args);
  16993. char buffer[128];
  16994. int len = vsnprintf(buffer, 128, format, args);
  16995. if (len < 128) {
  16996. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  16997. } else {
  16998. char* buffer2 = new char[len+1];
  16999. vsnprintf(buffer2, len+1, format, args_copy);
  17000. buffer2[len] = 0;
  17001. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  17002. delete[] buffer2;
  17003. }
  17004. va_end(args_copy);
  17005. }
  17006. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  17007. va_list args;
  17008. va_start(args, format);
  17009. llama_log_internal_v(level, format, args);
  17010. va_end(args);
  17011. }
  17012. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  17013. (void) level;
  17014. (void) user_data;
  17015. fputs(text, stderr);
  17016. fflush(stderr);
  17017. }