llama.cpp 799 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473
  1. /**
  2. * llama.cpp - commit 6eeaeba126ff701f3e8f79f246805b7023709972 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-impl.h"
  27. #include "llama-vocab.h"
  28. #include "llama-grammar.h"
  29. #include "llama-sampling.h"
  30. #include "unicode.h"
  31. #include "ggml.h"
  32. #include "ggml-alloc.h"
  33. #include "ggml-backend.h"
  34. #ifdef GGML_USE_RPC
  35. # include "ggml-rpc.h"
  36. #endif
  37. #ifdef GGML_USE_CUDA
  38. # include "ggml-cuda.h"
  39. #elif defined(GGML_USE_VULKAN)
  40. # include "ggml-vulkan.h"
  41. #elif defined(GGML_USE_SYCL)
  42. # include "ggml-sycl.h"
  43. #elif defined(GGML_USE_KOMPUTE)
  44. # include "ggml-kompute.h"
  45. #elif defined(GGML_USE_CANN)
  46. # include "ggml-cann.h"
  47. #endif
  48. #ifdef GGML_USE_BLAS
  49. # include "ggml-blas.h"
  50. #endif
  51. #ifdef GGML_USE_METAL
  52. # include "ggml-metal.h"
  53. #endif
  54. // TODO: replace with ggml API call
  55. #define QK_K 256
  56. #ifdef __has_include
  57. #if __has_include(<unistd.h>)
  58. #include <unistd.h>
  59. #if defined(_POSIX_MAPPED_FILES)
  60. #include <sys/mman.h>
  61. #include <fcntl.h>
  62. #endif
  63. #if defined(_POSIX_MEMLOCK_RANGE)
  64. #include <sys/resource.h>
  65. #endif
  66. #endif
  67. #endif
  68. #if defined(_WIN32)
  69. #define WIN32_LEAN_AND_MEAN
  70. #ifndef NOMINMAX
  71. #define NOMINMAX
  72. #endif
  73. #include <windows.h>
  74. #ifndef PATH_MAX
  75. #define PATH_MAX MAX_PATH
  76. #endif
  77. #include <io.h>
  78. #endif
  79. #if __cplusplus >= 202000L
  80. #define LU8(x) (const char*)(u8##x)
  81. #else
  82. #define LU8(x) u8##x
  83. #endif
  84. #include <algorithm>
  85. #include <array>
  86. #include <cassert>
  87. #include <cctype>
  88. #include <cfloat>
  89. #include <cinttypes>
  90. #include <climits>
  91. #include <cmath>
  92. #include <cstdarg>
  93. #include <cstddef>
  94. #include <cstdint>
  95. #include <cstdio>
  96. #include <cstring>
  97. #include <ctime>
  98. #include <fstream>
  99. #include <functional>
  100. #include <future>
  101. #include <initializer_list>
  102. #include <locale>
  103. #include <map>
  104. #include <memory>
  105. #include <mutex>
  106. #include <numeric>
  107. #include <set>
  108. #include <sstream>
  109. #include <thread>
  110. #include <type_traits>
  111. #include <unordered_map>
  112. #if defined(_MSC_VER)
  113. #pragma warning(disable: 4244 4267) // possible loss of data
  114. #endif
  115. // bump if necessary
  116. #define LLAMA_MAX_LAYERS 512
  117. #define LLAMA_MAX_EXPERTS 160 // DeepSeekV2
  118. //
  119. // helpers
  120. //
  121. // trim whitespace from the beginning and end of a string
  122. static std::string trim(const std::string & str) {
  123. size_t start = 0;
  124. size_t end = str.size();
  125. while (start < end && isspace(str[start])) {
  126. start += 1;
  127. }
  128. while (end > start && isspace(str[end - 1])) {
  129. end -= 1;
  130. }
  131. return str.substr(start, end - start);
  132. }
  133. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  134. std::string result;
  135. for (size_t pos = 0; ; pos += search.length()) {
  136. auto new_pos = s.find(search, pos);
  137. if (new_pos == std::string::npos) {
  138. result += s.substr(pos, s.size() - pos);
  139. break;
  140. }
  141. result += s.substr(pos, new_pos - pos) + replace;
  142. pos = new_pos;
  143. }
  144. s = std::move(result);
  145. }
  146. static bool is_float_close(float a, float b, float abs_tol) {
  147. // Check for non-negative tolerance
  148. if (abs_tol < 0.0) {
  149. throw std::invalid_argument("Tolerance must be non-negative");
  150. }
  151. // Exact equality check
  152. if (a == b) {
  153. return true;
  154. }
  155. // Check for infinities
  156. if (std::isinf(a) || std::isinf(b)) {
  157. return false;
  158. }
  159. // Regular comparison using the provided absolute tolerance
  160. return std::fabs(b - a) <= abs_tol;
  161. }
  162. static void zeros(std::ofstream & file, size_t n) {
  163. char zero = 0;
  164. for (size_t i = 0; i < n; ++i) {
  165. file.write(&zero, 1);
  166. }
  167. }
  168. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  169. static std::string format(const char * fmt, ...) {
  170. va_list ap;
  171. va_list ap2;
  172. va_start(ap, fmt);
  173. va_copy(ap2, ap);
  174. int size = vsnprintf(NULL, 0, fmt, ap);
  175. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  176. std::vector<char> buf(size + 1);
  177. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  178. GGML_ASSERT(size2 == size);
  179. va_end(ap2);
  180. va_end(ap);
  181. return std::string(buf.data(), size);
  182. }
  183. //
  184. // gguf constants (sync with gguf.py)
  185. //
  186. enum llm_arch {
  187. LLM_ARCH_LLAMA,
  188. LLM_ARCH_FALCON,
  189. LLM_ARCH_BAICHUAN,
  190. LLM_ARCH_GROK,
  191. LLM_ARCH_GPT2,
  192. LLM_ARCH_GPTJ,
  193. LLM_ARCH_GPTNEOX,
  194. LLM_ARCH_MPT,
  195. LLM_ARCH_STARCODER,
  196. LLM_ARCH_REFACT,
  197. LLM_ARCH_BERT,
  198. LLM_ARCH_NOMIC_BERT,
  199. LLM_ARCH_JINA_BERT_V2,
  200. LLM_ARCH_BLOOM,
  201. LLM_ARCH_STABLELM,
  202. LLM_ARCH_QWEN,
  203. LLM_ARCH_QWEN2,
  204. LLM_ARCH_QWEN2MOE,
  205. LLM_ARCH_PHI2,
  206. LLM_ARCH_PHI3,
  207. LLM_ARCH_PLAMO,
  208. LLM_ARCH_CODESHELL,
  209. LLM_ARCH_ORION,
  210. LLM_ARCH_INTERNLM2,
  211. LLM_ARCH_MINICPM,
  212. LLM_ARCH_GEMMA,
  213. LLM_ARCH_GEMMA2,
  214. LLM_ARCH_STARCODER2,
  215. LLM_ARCH_MAMBA,
  216. LLM_ARCH_XVERSE,
  217. LLM_ARCH_COMMAND_R,
  218. LLM_ARCH_DBRX,
  219. LLM_ARCH_OLMO,
  220. LLM_ARCH_OPENELM,
  221. LLM_ARCH_ARCTIC,
  222. LLM_ARCH_DEEPSEEK2,
  223. LLM_ARCH_CHATGLM,
  224. LLM_ARCH_BITNET,
  225. LLM_ARCH_T5,
  226. LLM_ARCH_JAIS,
  227. LLM_ARCH_UNKNOWN,
  228. };
  229. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  230. { LLM_ARCH_LLAMA, "llama" },
  231. { LLM_ARCH_FALCON, "falcon" },
  232. { LLM_ARCH_GROK, "grok" },
  233. { LLM_ARCH_GPT2, "gpt2" },
  234. { LLM_ARCH_GPTJ, "gptj" },
  235. { LLM_ARCH_GPTNEOX, "gptneox" },
  236. { LLM_ARCH_MPT, "mpt" },
  237. { LLM_ARCH_BAICHUAN, "baichuan" },
  238. { LLM_ARCH_STARCODER, "starcoder" },
  239. { LLM_ARCH_REFACT, "refact" },
  240. { LLM_ARCH_BERT, "bert" },
  241. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  242. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  243. { LLM_ARCH_BLOOM, "bloom" },
  244. { LLM_ARCH_STABLELM, "stablelm" },
  245. { LLM_ARCH_QWEN, "qwen" },
  246. { LLM_ARCH_QWEN2, "qwen2" },
  247. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  248. { LLM_ARCH_PHI2, "phi2" },
  249. { LLM_ARCH_PHI3, "phi3" },
  250. { LLM_ARCH_PLAMO, "plamo" },
  251. { LLM_ARCH_CODESHELL, "codeshell" },
  252. { LLM_ARCH_ORION, "orion" },
  253. { LLM_ARCH_INTERNLM2, "internlm2" },
  254. { LLM_ARCH_MINICPM, "minicpm" },
  255. { LLM_ARCH_GEMMA, "gemma" },
  256. { LLM_ARCH_GEMMA2, "gemma2" },
  257. { LLM_ARCH_STARCODER2, "starcoder2" },
  258. { LLM_ARCH_MAMBA, "mamba" },
  259. { LLM_ARCH_XVERSE, "xverse" },
  260. { LLM_ARCH_COMMAND_R, "command-r" },
  261. { LLM_ARCH_DBRX, "dbrx" },
  262. { LLM_ARCH_OLMO, "olmo" },
  263. { LLM_ARCH_OPENELM, "openelm" },
  264. { LLM_ARCH_ARCTIC, "arctic" },
  265. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  266. { LLM_ARCH_CHATGLM, "chatglm" },
  267. { LLM_ARCH_BITNET, "bitnet" },
  268. { LLM_ARCH_T5, "t5" },
  269. { LLM_ARCH_JAIS, "jais" },
  270. { LLM_ARCH_UNKNOWN, "(unknown)" },
  271. };
  272. enum llm_kv {
  273. LLM_KV_GENERAL_TYPE,
  274. LLM_KV_GENERAL_ARCHITECTURE,
  275. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  276. LLM_KV_GENERAL_ALIGNMENT,
  277. LLM_KV_GENERAL_NAME,
  278. LLM_KV_GENERAL_AUTHOR,
  279. LLM_KV_GENERAL_VERSION,
  280. LLM_KV_GENERAL_URL,
  281. LLM_KV_GENERAL_DESCRIPTION,
  282. LLM_KV_GENERAL_LICENSE,
  283. LLM_KV_GENERAL_SOURCE_URL,
  284. LLM_KV_GENERAL_SOURCE_HF_REPO,
  285. LLM_KV_VOCAB_SIZE,
  286. LLM_KV_CONTEXT_LENGTH,
  287. LLM_KV_EMBEDDING_LENGTH,
  288. LLM_KV_BLOCK_COUNT,
  289. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  290. LLM_KV_FEED_FORWARD_LENGTH,
  291. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  292. LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH,
  293. LLM_KV_USE_PARALLEL_RESIDUAL,
  294. LLM_KV_TENSOR_DATA_LAYOUT,
  295. LLM_KV_EXPERT_COUNT,
  296. LLM_KV_EXPERT_USED_COUNT,
  297. LLM_KV_EXPERT_SHARED_COUNT,
  298. LLM_KV_EXPERT_WEIGHTS_SCALE,
  299. LLM_KV_POOLING_TYPE,
  300. LLM_KV_LOGIT_SCALE,
  301. LLM_KV_DECODER_START_TOKEN_ID,
  302. LLM_KV_ATTN_LOGIT_SOFTCAPPING,
  303. LLM_KV_FINAL_LOGIT_SOFTCAPPING,
  304. LLM_KV_ATTENTION_HEAD_COUNT,
  305. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  306. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  307. LLM_KV_ATTENTION_CLAMP_KQV,
  308. LLM_KV_ATTENTION_KEY_LENGTH,
  309. LLM_KV_ATTENTION_VALUE_LENGTH,
  310. LLM_KV_ATTENTION_LAYERNORM_EPS,
  311. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  312. LLM_KV_ATTENTION_CAUSAL,
  313. LLM_KV_ATTENTION_Q_LORA_RANK,
  314. LLM_KV_ATTENTION_KV_LORA_RANK,
  315. LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT,
  316. LLM_KV_ATTENTION_SLIDING_WINDOW,
  317. LLM_KV_ROPE_DIMENSION_COUNT,
  318. LLM_KV_ROPE_FREQ_BASE,
  319. LLM_KV_ROPE_SCALE_LINEAR,
  320. LLM_KV_ROPE_SCALING_TYPE,
  321. LLM_KV_ROPE_SCALING_FACTOR,
  322. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  323. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  324. LLM_KV_ROPE_SCALING_FINETUNED,
  325. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  326. LLM_KV_SPLIT_NO,
  327. LLM_KV_SPLIT_COUNT,
  328. LLM_KV_SPLIT_TENSORS_COUNT,
  329. LLM_KV_SSM_INNER_SIZE,
  330. LLM_KV_SSM_CONV_KERNEL,
  331. LLM_KV_SSM_STATE_SIZE,
  332. LLM_KV_SSM_TIME_STEP_RANK,
  333. LLM_KV_TOKENIZER_MODEL,
  334. LLM_KV_TOKENIZER_PRE,
  335. LLM_KV_TOKENIZER_LIST,
  336. LLM_KV_TOKENIZER_TOKEN_TYPE,
  337. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  338. LLM_KV_TOKENIZER_SCORES,
  339. LLM_KV_TOKENIZER_MERGES,
  340. LLM_KV_TOKENIZER_BOS_ID,
  341. LLM_KV_TOKENIZER_EOS_ID,
  342. LLM_KV_TOKENIZER_UNK_ID,
  343. LLM_KV_TOKENIZER_SEP_ID,
  344. LLM_KV_TOKENIZER_PAD_ID,
  345. LLM_KV_TOKENIZER_CLS_ID,
  346. LLM_KV_TOKENIZER_MASK_ID,
  347. LLM_KV_TOKENIZER_ADD_BOS,
  348. LLM_KV_TOKENIZER_ADD_EOS,
  349. LLM_KV_TOKENIZER_ADD_PREFIX,
  350. LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,
  351. LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,
  352. LLM_KV_TOKENIZER_HF_JSON,
  353. LLM_KV_TOKENIZER_RWKV,
  354. LLM_KV_TOKENIZER_PREFIX_ID,
  355. LLM_KV_TOKENIZER_SUFFIX_ID,
  356. LLM_KV_TOKENIZER_MIDDLE_ID,
  357. LLM_KV_TOKENIZER_EOT_ID,
  358. LLM_KV_ADAPTER_TYPE,
  359. LLM_KV_ADAPTER_LORA_ALPHA,
  360. };
  361. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  362. { LLM_KV_GENERAL_TYPE, "general.type" },
  363. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  364. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  365. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  366. { LLM_KV_GENERAL_NAME, "general.name" },
  367. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  368. { LLM_KV_GENERAL_VERSION, "general.version" },
  369. { LLM_KV_GENERAL_URL, "general.url" },
  370. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  371. { LLM_KV_GENERAL_LICENSE, "general.license" },
  372. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  373. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  374. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  375. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  376. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  377. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  378. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  379. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  380. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  381. { LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, "%s.expert_shared_feed_forward_length" },
  382. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  383. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  384. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  385. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  386. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  387. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  388. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  389. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  390. { LLM_KV_DECODER_START_TOKEN_ID, "%s.decoder_start_token_id" },
  391. { LLM_KV_ATTN_LOGIT_SOFTCAPPING, "%s.attn_logit_softcapping" },
  392. { LLM_KV_FINAL_LOGIT_SOFTCAPPING, "%s.final_logit_softcapping" },
  393. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  394. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  395. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  396. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  397. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  398. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  399. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  400. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  401. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  402. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  403. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  404. { LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, "%s.attention.relative_buckets_count" },
  405. { LLM_KV_ATTENTION_SLIDING_WINDOW, "%s.attention.sliding_window" },
  406. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  407. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  408. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  409. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  410. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  411. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  412. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  413. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  414. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  415. { LLM_KV_SPLIT_NO, "split.no" },
  416. { LLM_KV_SPLIT_COUNT, "split.count" },
  417. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  418. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  419. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  420. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  421. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  422. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  423. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  424. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  425. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  426. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  427. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  428. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  429. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  430. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  431. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  432. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  433. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  434. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  435. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  436. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  437. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  438. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  439. { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, "tokenizer.ggml.remove_extra_whitespaces" },
  440. { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, "tokenizer.ggml.precompiled_charsmap" },
  441. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  442. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  443. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  444. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  445. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  446. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  447. { LLM_KV_ADAPTER_TYPE, "adapter.type" },
  448. { LLM_KV_ADAPTER_LORA_ALPHA, "adapter.lora.alpha" },
  449. };
  450. struct LLM_KV {
  451. LLM_KV(llm_arch arch) : arch(arch) {}
  452. llm_arch arch;
  453. std::string operator()(llm_kv kv) const {
  454. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  455. }
  456. };
  457. enum llm_tensor {
  458. LLM_TENSOR_TOKEN_EMBD,
  459. LLM_TENSOR_TOKEN_EMBD_NORM,
  460. LLM_TENSOR_TOKEN_TYPES,
  461. LLM_TENSOR_POS_EMBD,
  462. LLM_TENSOR_OUTPUT,
  463. LLM_TENSOR_OUTPUT_NORM,
  464. LLM_TENSOR_ROPE_FREQS,
  465. LLM_TENSOR_ROPE_FACTORS_LONG,
  466. LLM_TENSOR_ROPE_FACTORS_SHORT,
  467. LLM_TENSOR_ATTN_Q,
  468. LLM_TENSOR_ATTN_K,
  469. LLM_TENSOR_ATTN_V,
  470. LLM_TENSOR_ATTN_QKV,
  471. LLM_TENSOR_ATTN_OUT,
  472. LLM_TENSOR_ATTN_NORM,
  473. LLM_TENSOR_ATTN_NORM_2,
  474. LLM_TENSOR_ATTN_OUT_NORM,
  475. LLM_TENSOR_ATTN_POST_NORM,
  476. LLM_TENSOR_ATTN_ROT_EMBD,
  477. LLM_TENSOR_FFN_GATE_INP,
  478. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  479. LLM_TENSOR_FFN_NORM,
  480. LLM_TENSOR_FFN_POST_NORM,
  481. LLM_TENSOR_FFN_GATE,
  482. LLM_TENSOR_FFN_DOWN,
  483. LLM_TENSOR_FFN_UP,
  484. LLM_TENSOR_FFN_ACT,
  485. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  486. LLM_TENSOR_FFN_GATE_EXP,
  487. LLM_TENSOR_FFN_UP_EXP,
  488. LLM_TENSOR_FFN_NORM_EXPS,
  489. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  490. LLM_TENSOR_FFN_GATE_EXPS,
  491. LLM_TENSOR_FFN_UP_EXPS,
  492. LLM_TENSOR_FFN_DOWN_SHEXP,
  493. LLM_TENSOR_FFN_GATE_SHEXP,
  494. LLM_TENSOR_FFN_UP_SHEXP,
  495. LLM_TENSOR_ATTN_Q_NORM,
  496. LLM_TENSOR_ATTN_K_NORM,
  497. LLM_TENSOR_LAYER_OUT_NORM,
  498. LLM_TENSOR_SSM_IN,
  499. LLM_TENSOR_SSM_CONV1D,
  500. LLM_TENSOR_SSM_X,
  501. LLM_TENSOR_SSM_DT,
  502. LLM_TENSOR_SSM_A,
  503. LLM_TENSOR_SSM_D,
  504. LLM_TENSOR_SSM_OUT,
  505. LLM_TENSOR_ATTN_Q_A,
  506. LLM_TENSOR_ATTN_Q_B,
  507. LLM_TENSOR_ATTN_KV_A_MQA,
  508. LLM_TENSOR_ATTN_KV_B,
  509. LLM_TENSOR_ATTN_Q_A_NORM,
  510. LLM_TENSOR_ATTN_KV_A_NORM,
  511. LLM_TENSOR_ATTN_SUB_NORM,
  512. LLM_TENSOR_FFN_SUB_NORM,
  513. LLM_TENSOR_DEC_ATTN_NORM,
  514. LLM_TENSOR_DEC_ATTN_Q,
  515. LLM_TENSOR_DEC_ATTN_K,
  516. LLM_TENSOR_DEC_ATTN_V,
  517. LLM_TENSOR_DEC_ATTN_OUT,
  518. LLM_TENSOR_DEC_ATTN_REL_B,
  519. LLM_TENSOR_DEC_CROSS_ATTN_NORM,
  520. LLM_TENSOR_DEC_CROSS_ATTN_Q,
  521. LLM_TENSOR_DEC_CROSS_ATTN_K,
  522. LLM_TENSOR_DEC_CROSS_ATTN_V,
  523. LLM_TENSOR_DEC_CROSS_ATTN_OUT,
  524. LLM_TENSOR_DEC_CROSS_ATTN_REL_B,
  525. LLM_TENSOR_DEC_FFN_NORM,
  526. LLM_TENSOR_DEC_FFN_GATE,
  527. LLM_TENSOR_DEC_FFN_DOWN,
  528. LLM_TENSOR_DEC_FFN_UP,
  529. LLM_TENSOR_DEC_OUTPUT_NORM,
  530. LLM_TENSOR_ENC_ATTN_NORM,
  531. LLM_TENSOR_ENC_ATTN_Q,
  532. LLM_TENSOR_ENC_ATTN_K,
  533. LLM_TENSOR_ENC_ATTN_V,
  534. LLM_TENSOR_ENC_ATTN_OUT,
  535. LLM_TENSOR_ENC_ATTN_REL_B,
  536. LLM_TENSOR_ENC_FFN_NORM,
  537. LLM_TENSOR_ENC_FFN_GATE,
  538. LLM_TENSOR_ENC_FFN_DOWN,
  539. LLM_TENSOR_ENC_FFN_UP,
  540. LLM_TENSOR_ENC_OUTPUT_NORM,
  541. };
  542. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  543. {
  544. LLM_ARCH_LLAMA,
  545. {
  546. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  547. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  548. { LLM_TENSOR_OUTPUT, "output" },
  549. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  550. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  551. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  552. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  553. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  554. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  555. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  556. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  557. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  558. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  561. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  562. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  563. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  564. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  565. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  566. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  567. },
  568. },
  569. {
  570. LLM_ARCH_BAICHUAN,
  571. {
  572. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  573. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  574. { LLM_TENSOR_OUTPUT, "output" },
  575. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  576. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  577. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  578. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  579. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  580. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  581. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  582. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  583. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  584. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  585. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  586. },
  587. },
  588. {
  589. LLM_ARCH_FALCON,
  590. {
  591. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  592. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  593. { LLM_TENSOR_OUTPUT, "output" },
  594. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  595. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  596. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  597. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  598. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  599. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  600. },
  601. },
  602. {
  603. LLM_ARCH_GROK,
  604. {
  605. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  606. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  607. { LLM_TENSOR_OUTPUT, "output" },
  608. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  609. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  610. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  611. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  612. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  613. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  614. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  615. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  616. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  617. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  618. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  619. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  620. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  621. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  622. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  623. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  624. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  625. },
  626. },
  627. {
  628. LLM_ARCH_GPT2,
  629. {
  630. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  631. { LLM_TENSOR_POS_EMBD, "position_embd" },
  632. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  633. { LLM_TENSOR_OUTPUT, "output" },
  634. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  635. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  636. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  637. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  638. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  639. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  640. },
  641. },
  642. {
  643. LLM_ARCH_GPTJ,
  644. {
  645. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  646. },
  647. },
  648. {
  649. LLM_ARCH_GPTNEOX,
  650. {
  651. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  652. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  653. { LLM_TENSOR_OUTPUT, "output" },
  654. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  655. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  656. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  657. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  658. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  659. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  660. },
  661. },
  662. {
  663. LLM_ARCH_MPT,
  664. {
  665. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  666. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  667. { LLM_TENSOR_OUTPUT, "output"},
  668. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  669. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  670. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  671. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  672. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  673. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  674. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  675. { LLM_TENSOR_POS_EMBD, "position_embd" },
  676. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  677. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  678. },
  679. },
  680. {
  681. LLM_ARCH_STARCODER,
  682. {
  683. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  684. { LLM_TENSOR_POS_EMBD, "position_embd" },
  685. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  686. { LLM_TENSOR_OUTPUT, "output" },
  687. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  688. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  689. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  690. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  691. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  692. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  693. },
  694. },
  695. {
  696. LLM_ARCH_REFACT,
  697. {
  698. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  699. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  700. { LLM_TENSOR_OUTPUT, "output" },
  701. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  702. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  703. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  704. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  705. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  706. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  707. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  708. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  709. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  710. },
  711. },
  712. {
  713. LLM_ARCH_BERT,
  714. {
  715. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  716. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  717. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  718. { LLM_TENSOR_POS_EMBD, "position_embd" },
  719. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  720. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  721. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  722. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  723. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  724. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  725. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  726. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  727. },
  728. },
  729. {
  730. LLM_ARCH_NOMIC_BERT,
  731. {
  732. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  733. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  734. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  735. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  736. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  737. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  738. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  739. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  740. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  741. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  742. },
  743. },
  744. {
  745. LLM_ARCH_JINA_BERT_V2,
  746. {
  747. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  748. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  749. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  750. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  751. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  752. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  753. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  754. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  755. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  756. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  757. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  758. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  761. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  762. },
  763. },
  764. {
  765. LLM_ARCH_BLOOM,
  766. {
  767. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  768. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  769. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  770. { LLM_TENSOR_OUTPUT, "output" },
  771. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  772. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  773. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  774. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  775. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  776. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  777. },
  778. },
  779. {
  780. LLM_ARCH_STABLELM,
  781. {
  782. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  783. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  784. { LLM_TENSOR_OUTPUT, "output" },
  785. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  786. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  787. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  788. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  789. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  790. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  791. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  792. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  793. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  794. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  795. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  796. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  797. },
  798. },
  799. {
  800. LLM_ARCH_QWEN,
  801. {
  802. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  803. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  804. { LLM_TENSOR_OUTPUT, "output" },
  805. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  806. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  807. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  808. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  809. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  810. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  811. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  812. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  813. },
  814. },
  815. {
  816. LLM_ARCH_QWEN2,
  817. {
  818. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  819. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  820. { LLM_TENSOR_OUTPUT, "output" },
  821. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  822. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  823. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  824. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  825. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  826. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  827. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  828. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  829. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  830. },
  831. },
  832. {
  833. LLM_ARCH_QWEN2MOE,
  834. {
  835. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  836. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  837. { LLM_TENSOR_OUTPUT, "output" },
  838. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  839. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  840. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  841. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  842. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  843. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  844. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  845. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  846. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  847. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  848. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  849. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  850. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  851. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  852. },
  853. },
  854. {
  855. LLM_ARCH_PHI2,
  856. {
  857. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  858. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  859. { LLM_TENSOR_OUTPUT, "output" },
  860. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  861. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  862. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  863. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  864. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  865. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  866. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  867. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  868. },
  869. },
  870. {
  871. LLM_ARCH_PHI3,
  872. {
  873. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  874. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  875. { LLM_TENSOR_OUTPUT, "output" },
  876. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  877. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  878. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  879. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  880. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  881. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  882. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  883. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  884. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  885. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  886. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  887. },
  888. },
  889. {
  890. LLM_ARCH_PLAMO,
  891. {
  892. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  893. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  894. { LLM_TENSOR_OUTPUT, "output" },
  895. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  896. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  897. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  898. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  899. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  900. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  901. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  902. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  903. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  904. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  905. },
  906. },
  907. {
  908. LLM_ARCH_CODESHELL,
  909. {
  910. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  911. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  912. { LLM_TENSOR_OUTPUT, "output" },
  913. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  914. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  915. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  916. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  917. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  918. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  919. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  920. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  921. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  922. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  923. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  924. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  925. },
  926. },
  927. {
  928. LLM_ARCH_ORION,
  929. {
  930. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  931. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  932. { LLM_TENSOR_OUTPUT, "output" },
  933. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  934. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  935. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  936. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  937. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  938. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  939. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  940. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  941. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  942. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  943. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  944. },
  945. },
  946. {
  947. LLM_ARCH_INTERNLM2,
  948. {
  949. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  950. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  951. { LLM_TENSOR_OUTPUT, "output" },
  952. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  953. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  954. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  955. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  956. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  957. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  958. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  959. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  960. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  961. },
  962. },
  963. {
  964. LLM_ARCH_MINICPM,
  965. {
  966. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  967. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  968. { LLM_TENSOR_OUTPUT, "output" },
  969. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  970. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  971. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  972. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  973. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  974. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  975. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  976. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  977. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  978. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  979. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  980. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  981. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  982. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  983. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  984. },
  985. },
  986. {
  987. LLM_ARCH_GEMMA,
  988. {
  989. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  990. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  991. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  992. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  993. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  994. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  995. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  996. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  997. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  998. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  999. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1000. },
  1001. },
  1002. {
  1003. LLM_ARCH_GEMMA2,
  1004. {
  1005. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1006. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1007. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1008. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1009. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1010. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1011. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1012. { LLM_TENSOR_ATTN_POST_NORM, "blk.%d.post_attention_norm" },
  1013. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1014. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1015. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1016. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1017. { LLM_TENSOR_FFN_POST_NORM, "blk.%d.post_ffw_norm" },
  1018. },
  1019. },
  1020. {
  1021. LLM_ARCH_STARCODER2,
  1022. {
  1023. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1024. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1025. { LLM_TENSOR_OUTPUT, "output" },
  1026. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1027. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1028. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1029. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1030. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1031. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1032. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1033. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1034. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1035. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1036. },
  1037. },
  1038. {
  1039. LLM_ARCH_MAMBA,
  1040. {
  1041. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1042. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1043. { LLM_TENSOR_OUTPUT, "output" },
  1044. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1045. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  1046. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  1047. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  1048. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  1049. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  1050. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  1051. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  1052. },
  1053. },
  1054. {
  1055. LLM_ARCH_XVERSE,
  1056. {
  1057. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1058. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1059. { LLM_TENSOR_OUTPUT, "output" },
  1060. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1061. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1062. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1063. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1064. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1065. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1066. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  1067. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1068. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1069. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1070. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1071. },
  1072. },
  1073. {
  1074. LLM_ARCH_COMMAND_R,
  1075. {
  1076. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1077. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1078. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1079. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1080. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1081. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1082. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1083. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1084. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1085. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1086. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1087. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1088. },
  1089. },
  1090. {
  1091. LLM_ARCH_DBRX,
  1092. {
  1093. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1094. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1095. { LLM_TENSOR_OUTPUT, "output" },
  1096. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1097. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1098. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1099. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  1100. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1101. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1102. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1103. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1104. },
  1105. },
  1106. {
  1107. LLM_ARCH_OLMO,
  1108. {
  1109. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1110. { LLM_TENSOR_OUTPUT, "output" },
  1111. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1112. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1113. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1114. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1115. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1116. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1117. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1118. },
  1119. },
  1120. {
  1121. LLM_ARCH_OPENELM,
  1122. {
  1123. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1124. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1125. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1126. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1127. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  1128. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  1129. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1130. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1131. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1132. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1133. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1134. },
  1135. },
  1136. {
  1137. LLM_ARCH_ARCTIC,
  1138. {
  1139. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1140. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1141. { LLM_TENSOR_OUTPUT, "output" },
  1142. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1143. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1144. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1145. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1146. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1147. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1148. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1149. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1150. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1151. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1152. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1153. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1154. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1155. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1156. },
  1157. },
  1158. {
  1159. LLM_ARCH_DEEPSEEK2,
  1160. {
  1161. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1162. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1163. { LLM_TENSOR_OUTPUT, "output" },
  1164. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1165. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1166. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1167. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1168. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1169. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1170. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1171. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1172. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1173. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1174. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1175. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1176. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1177. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1178. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1179. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1180. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1181. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1182. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1183. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1184. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1185. },
  1186. },
  1187. {
  1188. LLM_ARCH_CHATGLM,
  1189. {
  1190. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1191. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  1192. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1193. { LLM_TENSOR_OUTPUT, "output" },
  1194. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1195. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1196. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1197. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1198. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1199. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1200. },
  1201. },
  1202. {
  1203. LLM_ARCH_BITNET,
  1204. {
  1205. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1206. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1207. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1208. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1209. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1210. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1211. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1212. { LLM_TENSOR_ATTN_SUB_NORM, "blk.%d.attn_sub_norm" },
  1213. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1214. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1215. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1216. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1217. { LLM_TENSOR_FFN_SUB_NORM, "blk.%d.ffn_sub_norm" },
  1218. },
  1219. },
  1220. {
  1221. LLM_ARCH_T5,
  1222. {
  1223. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1224. { LLM_TENSOR_OUTPUT, "output" },
  1225. { LLM_TENSOR_DEC_OUTPUT_NORM, "dec.output_norm" },
  1226. { LLM_TENSOR_DEC_ATTN_NORM, "dec.blk.%d.attn_norm" },
  1227. { LLM_TENSOR_DEC_ATTN_Q, "dec.blk.%d.attn_q" },
  1228. { LLM_TENSOR_DEC_ATTN_K, "dec.blk.%d.attn_k" },
  1229. { LLM_TENSOR_DEC_ATTN_V, "dec.blk.%d.attn_v" },
  1230. { LLM_TENSOR_DEC_ATTN_OUT, "dec.blk.%d.attn_o" },
  1231. { LLM_TENSOR_DEC_ATTN_REL_B, "dec.blk.%d.attn_rel_b" },
  1232. { LLM_TENSOR_DEC_CROSS_ATTN_NORM, "dec.blk.%d.cross_attn_norm" },
  1233. { LLM_TENSOR_DEC_CROSS_ATTN_Q, "dec.blk.%d.cross_attn_q" },
  1234. { LLM_TENSOR_DEC_CROSS_ATTN_K, "dec.blk.%d.cross_attn_k" },
  1235. { LLM_TENSOR_DEC_CROSS_ATTN_V, "dec.blk.%d.cross_attn_v" },
  1236. { LLM_TENSOR_DEC_CROSS_ATTN_OUT, "dec.blk.%d.cross_attn_o" },
  1237. { LLM_TENSOR_DEC_CROSS_ATTN_REL_B, "dec.blk.%d.cross_attn_rel_b" },
  1238. { LLM_TENSOR_DEC_FFN_NORM, "dec.blk.%d.ffn_norm" },
  1239. { LLM_TENSOR_DEC_FFN_GATE, "dec.blk.%d.ffn_gate" },
  1240. { LLM_TENSOR_DEC_FFN_DOWN, "dec.blk.%d.ffn_down" },
  1241. { LLM_TENSOR_DEC_FFN_UP, "dec.blk.%d.ffn_up" },
  1242. { LLM_TENSOR_ENC_OUTPUT_NORM, "enc.output_norm" },
  1243. { LLM_TENSOR_ENC_ATTN_NORM, "enc.blk.%d.attn_norm" },
  1244. { LLM_TENSOR_ENC_ATTN_Q, "enc.blk.%d.attn_q" },
  1245. { LLM_TENSOR_ENC_ATTN_K, "enc.blk.%d.attn_k" },
  1246. { LLM_TENSOR_ENC_ATTN_V, "enc.blk.%d.attn_v" },
  1247. { LLM_TENSOR_ENC_ATTN_OUT, "enc.blk.%d.attn_o" },
  1248. { LLM_TENSOR_ENC_ATTN_REL_B, "enc.blk.%d.attn_rel_b" },
  1249. { LLM_TENSOR_ENC_FFN_NORM, "enc.blk.%d.ffn_norm" },
  1250. { LLM_TENSOR_ENC_FFN_GATE, "enc.blk.%d.ffn_gate" },
  1251. { LLM_TENSOR_ENC_FFN_DOWN, "enc.blk.%d.ffn_down" },
  1252. { LLM_TENSOR_ENC_FFN_UP, "enc.blk.%d.ffn_up" },
  1253. },
  1254. },
  1255. {
  1256. LLM_ARCH_JAIS,
  1257. {
  1258. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1259. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1260. { LLM_TENSOR_OUTPUT, "output" },
  1261. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1262. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  1263. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1264. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1265. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1266. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1267. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1268. },
  1269. },
  1270. {
  1271. LLM_ARCH_UNKNOWN,
  1272. {
  1273. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1274. },
  1275. },
  1276. };
  1277. static llm_arch llm_arch_from_string(const std::string & name) {
  1278. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1279. if (kv.second == name) {
  1280. return kv.first;
  1281. }
  1282. }
  1283. return LLM_ARCH_UNKNOWN;
  1284. }
  1285. // helper to handle gguf constants
  1286. // usage:
  1287. //
  1288. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1289. //
  1290. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1291. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1292. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1293. //
  1294. struct LLM_TN {
  1295. LLM_TN(llm_arch arch) : arch(arch) {}
  1296. llm_arch arch;
  1297. std::string operator()(llm_tensor tensor) const {
  1298. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1299. return "__missing__";
  1300. }
  1301. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1302. }
  1303. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1304. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1305. return "__missing__";
  1306. }
  1307. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1308. }
  1309. std::string operator()(llm_tensor tensor, int bid) const {
  1310. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1311. return "__missing__";
  1312. }
  1313. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1314. }
  1315. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1316. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1317. return "__missing__";
  1318. }
  1319. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1320. }
  1321. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1322. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1323. return "__missing__";
  1324. }
  1325. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1326. }
  1327. };
  1328. //
  1329. // gguf helpers
  1330. //
  1331. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1332. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1333. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1334. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1335. };
  1336. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1337. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1338. if (kv.second == name) {
  1339. return (llama_rope_scaling_type) kv.first;
  1340. }
  1341. }
  1342. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1343. }
  1344. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1345. switch (type) {
  1346. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1347. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1348. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1349. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1350. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1351. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1352. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1353. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1354. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1355. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1356. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1357. default: return format("unknown type %d", type);
  1358. }
  1359. }
  1360. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1361. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1362. switch (type) {
  1363. case GGUF_TYPE_STRING:
  1364. return gguf_get_val_str(ctx_gguf, i);
  1365. case GGUF_TYPE_ARRAY:
  1366. {
  1367. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1368. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1369. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1370. std::stringstream ss;
  1371. ss << "[";
  1372. for (int j = 0; j < arr_n; j++) {
  1373. if (arr_type == GGUF_TYPE_STRING) {
  1374. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1375. // escape quotes
  1376. replace_all(val, "\\", "\\\\");
  1377. replace_all(val, "\"", "\\\"");
  1378. ss << '"' << val << '"';
  1379. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1380. ss << "???";
  1381. } else {
  1382. ss << gguf_data_to_str(arr_type, data, j);
  1383. }
  1384. if (j < arr_n - 1) {
  1385. ss << ", ";
  1386. }
  1387. }
  1388. ss << "]";
  1389. return ss.str();
  1390. }
  1391. default:
  1392. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1393. }
  1394. }
  1395. //
  1396. // llama helpers
  1397. //
  1398. #if defined(_WIN32)
  1399. static std::string llama_format_win_err(DWORD err) {
  1400. LPSTR buf;
  1401. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1402. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1403. if (!size) {
  1404. return "FormatMessageA failed";
  1405. }
  1406. std::string ret(buf, size);
  1407. LocalFree(buf);
  1408. return ret;
  1409. }
  1410. #endif
  1411. template <typename T>
  1412. struct no_init {
  1413. T value;
  1414. no_init() { /* do nothing */ }
  1415. };
  1416. struct llama_file {
  1417. #if defined(_WIN32)
  1418. // use FILE * so we don't have to re-open the file to mmap
  1419. FILE * fp;
  1420. HANDLE fp_win32;
  1421. size_t size;
  1422. private:
  1423. std::string GetErrorMessageWin32(DWORD error_code) const {
  1424. std::string ret;
  1425. LPSTR lpMsgBuf = NULL;
  1426. DWORD bufLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1427. NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL);
  1428. if (!bufLen) {
  1429. ret = format("Win32 error code: %s", error_code);
  1430. } else {
  1431. ret = lpMsgBuf;
  1432. LocalFree(lpMsgBuf);
  1433. }
  1434. return ret;
  1435. }
  1436. public:
  1437. llama_file(const char * fname, const char * mode) {
  1438. fp = ggml_fopen(fname, mode);
  1439. if (fp == NULL) {
  1440. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1441. }
  1442. fp_win32 = (HANDLE) _get_osfhandle(_fileno(fp));
  1443. seek(0, SEEK_END);
  1444. size = tell();
  1445. seek(0, SEEK_SET);
  1446. }
  1447. size_t tell() const {
  1448. // SetFilePointerEx returns the current position when seeking relative 0 bytes
  1449. LARGE_INTEGER li;
  1450. li.QuadPart = 0;
  1451. BOOL ret = SetFilePointerEx(fp_win32, li, &li, FILE_CURRENT);
  1452. if (!ret) {
  1453. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1454. }
  1455. return li.QuadPart;
  1456. }
  1457. void seek(size_t offset, int whence) const {
  1458. // no need to convert SEEK_* to FILE_*. The enums are the same.
  1459. // Still, keep static asserts to avoid failures in the future.
  1460. static_assert(SEEK_SET == FILE_BEGIN, "SEEK_SET != FILE_BEGIN");
  1461. static_assert(SEEK_CUR == FILE_CURRENT, "SEEK_CUR != FILE_CURRENT");
  1462. static_assert(SEEK_END == FILE_END, "SEEK_END != FILE_END");
  1463. LARGE_INTEGER li;
  1464. li.QuadPart = offset;
  1465. BOOL ret = SetFilePointerEx(fp_win32, li, NULL, whence);
  1466. if (!ret) {
  1467. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1468. }
  1469. }
  1470. void read_raw(void * ptr, size_t len) const {
  1471. // On Win32 ReadFile is significant faster than fread which is again significant faster than std::fstream. Thus
  1472. // use the Win32 API to do file io instead of the C/C++ library functions.
  1473. // There are conditions under which ReadFile cannot read chunks >64MB.
  1474. // Thus split the operation into smaller chunks if len exceeds this limit.
  1475. size_t bytes_read = 0;
  1476. while (bytes_read < len) {
  1477. size_t chunk_size = std::min<size_t>(len - bytes_read, 64*1024*1024);
  1478. DWORD chunk_read = 0;
  1479. BOOL result = ReadFile(fp_win32, reinterpret_cast<char*>(ptr) + bytes_read, chunk_size, &chunk_read, NULL);
  1480. if (!result) {
  1481. throw std::runtime_error(format("read error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1482. }
  1483. if (chunk_read < chunk_size || chunk_read == 0) {
  1484. throw std::runtime_error("unexpectedly reached end of file");
  1485. }
  1486. bytes_read += chunk_read;
  1487. } ;
  1488. }
  1489. uint32_t read_u32() const {
  1490. uint32_t val;
  1491. read_raw(&val, sizeof(val));
  1492. return val;
  1493. }
  1494. void write_raw(const void * ptr, size_t len) const {
  1495. // There are conditions under which WriteFile cannot write chunks >64MB.
  1496. // Thus split the operation into smaller chunks if len exceeds this limit.
  1497. size_t bytes_written = 0;
  1498. while (bytes_written < len) {
  1499. size_t chunk_size = std::min<size_t>(len - bytes_written, 64*1024*1024);
  1500. DWORD chunk_written = 0;
  1501. BOOL result = WriteFile(fp_win32, reinterpret_cast<char const*>(ptr) + bytes_written, chunk_size, &chunk_written, NULL);
  1502. if (!result) {
  1503. throw std::runtime_error(format("write error: %s", GetErrorMessageWin32(GetLastError()).c_str()));
  1504. }
  1505. if (chunk_written < chunk_size || chunk_written == 0) {
  1506. throw std::runtime_error("unexpectedly failed to write bytes");
  1507. }
  1508. bytes_written += chunk_written;
  1509. }
  1510. }
  1511. void write_u32(std::uint32_t val) const {
  1512. write_raw(&val, sizeof(val));
  1513. }
  1514. ~llama_file() {
  1515. if (fp) {
  1516. std::fclose(fp);
  1517. }
  1518. }
  1519. #else
  1520. // use FILE * so we don't have to re-open the file to mmap
  1521. FILE * fp;
  1522. size_t size;
  1523. llama_file(const char * fname, const char * mode) {
  1524. fp = ggml_fopen(fname, mode);
  1525. if (fp == NULL) {
  1526. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1527. }
  1528. seek(0, SEEK_END);
  1529. size = tell();
  1530. seek(0, SEEK_SET);
  1531. }
  1532. size_t tell() const {
  1533. #ifdef _WIN32
  1534. __int64 ret = _ftelli64(fp);
  1535. #else
  1536. long ret = std::ftell(fp);
  1537. #endif
  1538. if (ret == -1) {
  1539. throw std::runtime_error(format("ftell error: %s", strerror(errno)));
  1540. }
  1541. return (size_t) ret;
  1542. }
  1543. void seek(size_t offset, int whence) const {
  1544. #ifdef _WIN32
  1545. int ret = _fseeki64(fp, (__int64) offset, whence);
  1546. #else
  1547. int ret = std::fseek(fp, (long) offset, whence);
  1548. #endif
  1549. if (ret != 0) {
  1550. throw std::runtime_error(format("seek error: %s", strerror(errno)));
  1551. }
  1552. }
  1553. void read_raw(void * ptr, size_t len) const {
  1554. if (len == 0) {
  1555. return;
  1556. }
  1557. errno = 0;
  1558. std::size_t ret = std::fread(ptr, len, 1, fp);
  1559. if (ferror(fp)) {
  1560. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1561. }
  1562. if (ret != 1) {
  1563. throw std::runtime_error("unexpectedly reached end of file");
  1564. }
  1565. }
  1566. uint32_t read_u32() const {
  1567. uint32_t ret;
  1568. read_raw(&ret, sizeof(ret));
  1569. return ret;
  1570. }
  1571. void write_raw(const void * ptr, size_t len) const {
  1572. if (len == 0) {
  1573. return;
  1574. }
  1575. errno = 0;
  1576. size_t ret = std::fwrite(ptr, len, 1, fp);
  1577. if (ret != 1) {
  1578. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1579. }
  1580. }
  1581. void write_u32(std::uint32_t val) const {
  1582. write_raw(&val, sizeof(val));
  1583. }
  1584. ~llama_file() {
  1585. if (fp) {
  1586. std::fclose(fp);
  1587. }
  1588. }
  1589. #endif
  1590. };
  1591. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1592. struct llama_mmap {
  1593. void * addr;
  1594. size_t size;
  1595. llama_mmap(const llama_mmap &) = delete;
  1596. #ifdef _POSIX_MAPPED_FILES
  1597. static constexpr bool SUPPORTED = true;
  1598. // list of mapped fragments (first_offset, last_offset)
  1599. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1600. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1601. size = file->size;
  1602. int fd = fileno(file->fp);
  1603. int flags = MAP_SHARED;
  1604. // prefetch/readahead impairs performance on NUMA systems
  1605. if (numa) { prefetch = 0; }
  1606. #ifdef __linux__
  1607. // advise the kernel to read the file sequentially (increases readahead)
  1608. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1609. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1610. strerror(errno));
  1611. }
  1612. if (prefetch) { flags |= MAP_POPULATE; }
  1613. #endif
  1614. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1615. if (addr == MAP_FAILED) { // NOLINT
  1616. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1617. }
  1618. if (prefetch > 0) {
  1619. // advise the kernel to preload the mapped memory
  1620. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1621. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1622. strerror(errno));
  1623. }
  1624. }
  1625. if (numa) {
  1626. // advise the kernel not to use readahead
  1627. // (because the next page might not belong on the same node)
  1628. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1629. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1630. strerror(errno));
  1631. }
  1632. }
  1633. // initialize list of mapped_fragments
  1634. mapped_fragments.emplace_back(0, file->size);
  1635. }
  1636. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1637. // align first to the next page
  1638. size_t offset_in_page = *first & (page_size - 1);
  1639. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1640. *first += offset_to_page;
  1641. // align last to the previous page
  1642. *last = *last & ~(page_size - 1);
  1643. if (*last <= *first) {
  1644. *last = *first;
  1645. }
  1646. }
  1647. // partially unmap the file in the range [first, last)
  1648. void unmap_fragment(size_t first, size_t last) {
  1649. // note: this function must not be called multiple times with overlapping ranges
  1650. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1651. int page_size = sysconf(_SC_PAGESIZE);
  1652. align_range(&first, &last, page_size);
  1653. size_t len = last - first;
  1654. if (len == 0) {
  1655. return;
  1656. }
  1657. GGML_ASSERT(first % page_size == 0);
  1658. GGML_ASSERT(last % page_size == 0);
  1659. GGML_ASSERT(last > first);
  1660. void * next_page_start = (uint8_t *) addr + first;
  1661. // unmap the range
  1662. if (munmap(next_page_start, len)) {
  1663. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1664. }
  1665. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1666. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1667. for (const auto & frag : mapped_fragments) {
  1668. if (frag.first < first && frag.second > last) {
  1669. // the range is in the middle of the fragment, split it
  1670. new_mapped_fragments.emplace_back(frag.first, first);
  1671. new_mapped_fragments.emplace_back(last, frag.second);
  1672. } else if (frag.first < first && frag.second > first) {
  1673. // the range starts in the middle of the fragment
  1674. new_mapped_fragments.emplace_back(frag.first, first);
  1675. } else if (frag.first < last && frag.second > last) {
  1676. // the range ends in the middle of the fragment
  1677. new_mapped_fragments.emplace_back(last, frag.second);
  1678. } else if (frag.first >= first && frag.second <= last) {
  1679. // the range covers the entire fragment
  1680. } else {
  1681. // the range is outside the fragment
  1682. new_mapped_fragments.push_back(frag);
  1683. }
  1684. }
  1685. mapped_fragments = std::move(new_mapped_fragments);
  1686. }
  1687. ~llama_mmap() {
  1688. for (const auto & frag : mapped_fragments) {
  1689. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1690. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1691. }
  1692. }
  1693. }
  1694. #elif defined(_WIN32)
  1695. static constexpr bool SUPPORTED = true;
  1696. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1697. GGML_UNUSED(numa);
  1698. size = file->size;
  1699. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1700. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1701. if (hMapping == NULL) {
  1702. DWORD error = GetLastError();
  1703. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1704. }
  1705. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1706. DWORD error = GetLastError();
  1707. CloseHandle(hMapping);
  1708. if (addr == NULL) {
  1709. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1710. }
  1711. if (prefetch > 0) {
  1712. #if _WIN32_WINNT >= 0x602
  1713. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1714. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1715. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1716. // may fail on pre-Windows 8 systems
  1717. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1718. if (pPrefetchVirtualMemory) {
  1719. // advise the kernel to preload the mapped memory
  1720. WIN32_MEMORY_RANGE_ENTRY range;
  1721. range.VirtualAddress = addr;
  1722. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1723. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1724. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1725. llama_format_win_err(GetLastError()).c_str());
  1726. }
  1727. }
  1728. #else
  1729. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1730. #endif
  1731. }
  1732. }
  1733. void unmap_fragment(size_t first, size_t last) {
  1734. // not supported
  1735. GGML_UNUSED(first);
  1736. GGML_UNUSED(last);
  1737. }
  1738. ~llama_mmap() {
  1739. if (!UnmapViewOfFile(addr)) {
  1740. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1741. llama_format_win_err(GetLastError()).c_str());
  1742. }
  1743. }
  1744. #else
  1745. static constexpr bool SUPPORTED = false;
  1746. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1747. GGML_UNUSED(file);
  1748. GGML_UNUSED(prefetch);
  1749. GGML_UNUSED(numa);
  1750. throw std::runtime_error("mmap not supported");
  1751. }
  1752. void unmap_fragment(size_t first, size_t last) {
  1753. GGML_UNUSED(first);
  1754. GGML_UNUSED(last);
  1755. throw std::runtime_error("mmap not supported");
  1756. }
  1757. #endif
  1758. };
  1759. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1760. // Represents some region of memory being locked using mlock or VirtualLock;
  1761. // will automatically unlock on destruction.
  1762. struct llama_mlock {
  1763. void * addr = NULL;
  1764. size_t size = 0;
  1765. bool failed_already = false;
  1766. llama_mlock() {}
  1767. llama_mlock(const llama_mlock &) = delete;
  1768. ~llama_mlock() {
  1769. if (size) {
  1770. raw_unlock(addr, size);
  1771. }
  1772. }
  1773. void init(void * ptr) {
  1774. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1775. addr = ptr;
  1776. }
  1777. void grow_to(size_t target_size) {
  1778. GGML_ASSERT(addr);
  1779. if (failed_already) {
  1780. return;
  1781. }
  1782. size_t granularity = lock_granularity();
  1783. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1784. if (target_size > size) {
  1785. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1786. size = target_size;
  1787. } else {
  1788. failed_already = true;
  1789. }
  1790. }
  1791. }
  1792. #ifdef _POSIX_MEMLOCK_RANGE
  1793. static constexpr bool SUPPORTED = true;
  1794. static size_t lock_granularity() {
  1795. return (size_t) sysconf(_SC_PAGESIZE);
  1796. }
  1797. #ifdef __APPLE__
  1798. #define MLOCK_SUGGESTION \
  1799. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1800. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1801. #else
  1802. #define MLOCK_SUGGESTION \
  1803. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1804. #endif
  1805. bool raw_lock(const void * addr, size_t size) const {
  1806. if (!mlock(addr, size)) {
  1807. return true;
  1808. }
  1809. char* errmsg = std::strerror(errno);
  1810. bool suggest = (errno == ENOMEM);
  1811. // Check if the resource limit is fine after all
  1812. struct rlimit lock_limit;
  1813. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1814. suggest = false;
  1815. }
  1816. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1817. suggest = false;
  1818. }
  1819. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1820. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1821. return false;
  1822. }
  1823. #undef MLOCK_SUGGESTION
  1824. static void raw_unlock(void * addr, size_t size) {
  1825. if (munlock(addr, size)) {
  1826. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1827. }
  1828. }
  1829. #elif defined(_WIN32)
  1830. static constexpr bool SUPPORTED = true;
  1831. static size_t lock_granularity() {
  1832. SYSTEM_INFO si;
  1833. GetSystemInfo(&si);
  1834. return (size_t) si.dwPageSize;
  1835. }
  1836. bool raw_lock(void * ptr, size_t len) const {
  1837. for (int tries = 1; ; tries++) {
  1838. if (VirtualLock(ptr, len)) {
  1839. return true;
  1840. }
  1841. if (tries == 2) {
  1842. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1843. len, size, llama_format_win_err(GetLastError()).c_str());
  1844. return false;
  1845. }
  1846. // It failed but this was only the first try; increase the working
  1847. // set size and try again.
  1848. SIZE_T min_ws_size, max_ws_size;
  1849. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1850. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1851. llama_format_win_err(GetLastError()).c_str());
  1852. return false;
  1853. }
  1854. // Per MSDN: "The maximum number of pages that a process can lock
  1855. // is equal to the number of pages in its minimum working set minus
  1856. // a small overhead."
  1857. // Hopefully a megabyte is enough overhead:
  1858. size_t increment = len + 1048576;
  1859. // The minimum must be <= the maximum, so we need to increase both:
  1860. min_ws_size += increment;
  1861. max_ws_size += increment;
  1862. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1863. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1864. llama_format_win_err(GetLastError()).c_str());
  1865. return false;
  1866. }
  1867. }
  1868. }
  1869. static void raw_unlock(void * ptr, size_t len) {
  1870. if (!VirtualUnlock(ptr, len)) {
  1871. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1872. llama_format_win_err(GetLastError()).c_str());
  1873. }
  1874. }
  1875. #else
  1876. static constexpr bool SUPPORTED = false;
  1877. static size_t lock_granularity() {
  1878. return (size_t) 65536;
  1879. }
  1880. bool raw_lock(const void * addr, size_t len) const {
  1881. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1882. return false;
  1883. }
  1884. static void raw_unlock(const void * addr, size_t len) {}
  1885. #endif
  1886. };
  1887. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1888. // NOTE: avoid ever using this except for building the token_to_piece caches
  1889. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  1890. std::string piece;
  1891. piece.resize(piece.capacity()); // using string internal cache
  1892. const int n_chars = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1893. if (n_chars < 0) {
  1894. piece.resize(-n_chars);
  1895. int check = llama_token_to_piece(model, token, &piece[0], piece.size(), 0, special);
  1896. GGML_ASSERT(check == -n_chars);
  1897. }
  1898. else {
  1899. piece.resize(n_chars);
  1900. }
  1901. return piece;
  1902. }
  1903. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1904. ggml_backend_buffer_type_t buft = nullptr;
  1905. #if defined(GGML_USE_CUDA)
  1906. // host buffers should only be used when data is expected to be copied to/from the GPU
  1907. if (host_buffer) {
  1908. buft = ggml_backend_cuda_host_buffer_type();
  1909. }
  1910. #elif defined(GGML_USE_SYCL)
  1911. if (host_buffer) {
  1912. buft = ggml_backend_sycl_host_buffer_type();
  1913. }
  1914. #elif defined(GGML_USE_CPU_HBM)
  1915. buft = ggml_backend_cpu_hbm_buffer_type();
  1916. #elif defined(GGML_USE_VULKAN)
  1917. if (host_buffer) {
  1918. buft = ggml_backend_vk_host_buffer_type();
  1919. }
  1920. #endif
  1921. if (buft == nullptr) {
  1922. buft = ggml_backend_cpu_buffer_type();
  1923. }
  1924. return buft;
  1925. GGML_UNUSED(host_buffer);
  1926. }
  1927. //
  1928. // globals
  1929. //
  1930. struct llama_state {
  1931. llama_state() {
  1932. #ifdef GGML_USE_METAL
  1933. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1934. #elif defined(GGML_USE_CUDA)
  1935. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1936. #elif defined(GGML_USE_CANN)
  1937. ggml_backend_cann_log_set_callback(log_callback, log_callback_user_data);
  1938. #endif
  1939. }
  1940. // We save the log callback globally
  1941. ggml_log_callback log_callback = llama_log_callback_default;
  1942. void * log_callback_user_data = nullptr;
  1943. };
  1944. static llama_state g_state;
  1945. // available llama models
  1946. enum e_model {
  1947. MODEL_UNKNOWN,
  1948. MODEL_14M,
  1949. MODEL_17M,
  1950. MODEL_22M,
  1951. MODEL_33M,
  1952. MODEL_60M,
  1953. MODEL_70M,
  1954. MODEL_80M,
  1955. MODEL_109M,
  1956. MODEL_137M,
  1957. MODEL_160M,
  1958. MODEL_220M,
  1959. MODEL_250M,
  1960. MODEL_270M,
  1961. MODEL_335M,
  1962. MODEL_410M,
  1963. MODEL_450M,
  1964. MODEL_770M,
  1965. MODEL_780M,
  1966. MODEL_0_5B,
  1967. MODEL_1B,
  1968. MODEL_1_3B,
  1969. MODEL_1_4B,
  1970. MODEL_2B,
  1971. MODEL_2_8B,
  1972. MODEL_3B,
  1973. MODEL_4B,
  1974. MODEL_6B,
  1975. MODEL_6_9B,
  1976. MODEL_7B,
  1977. MODEL_8B,
  1978. MODEL_9B,
  1979. MODEL_11B,
  1980. MODEL_12B,
  1981. MODEL_13B,
  1982. MODEL_14B,
  1983. MODEL_15B,
  1984. MODEL_16B,
  1985. MODEL_20B,
  1986. MODEL_30B,
  1987. MODEL_34B,
  1988. MODEL_35B,
  1989. MODEL_40B,
  1990. MODEL_65B,
  1991. MODEL_70B,
  1992. MODEL_236B,
  1993. MODEL_314B,
  1994. MODEL_SMALL,
  1995. MODEL_MEDIUM,
  1996. MODEL_LARGE,
  1997. MODEL_XL,
  1998. MODEL_A2_7B,
  1999. MODEL_8x7B,
  2000. MODEL_8x22B,
  2001. MODEL_16x12B,
  2002. MODEL_10B_128x3_66B,
  2003. MODEL_57B_A14B,
  2004. MODEL_27B,
  2005. };
  2006. static const size_t kiB = 1024;
  2007. static const size_t MiB = 1024*kiB;
  2008. static const size_t GiB = 1024*MiB;
  2009. struct llama_hparams {
  2010. bool vocab_only;
  2011. bool rope_finetuned;
  2012. bool use_par_res;
  2013. uint32_t n_vocab;
  2014. uint32_t n_ctx_train; // context size the model was trained on
  2015. uint32_t n_embd;
  2016. uint32_t n_layer;
  2017. uint32_t n_rot;
  2018. uint32_t n_swa = 0; // sliding window attention (SWA)
  2019. 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
  2020. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  2021. uint32_t n_expert = 0;
  2022. uint32_t n_expert_used = 0;
  2023. uint32_t n_vocab_type = 0; // for BERT-style token types
  2024. uint32_t n_rel_attn_bkts = 0;
  2025. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_arr;
  2026. std::array<uint32_t, LLAMA_MAX_LAYERS> n_head_kv_arr;
  2027. std::array<uint32_t, LLAMA_MAX_LAYERS> n_ff_arr;
  2028. uint32_t n_layer_dense_lead = 0;
  2029. uint32_t n_lora_q = 0;
  2030. uint32_t n_lora_kv = 0;
  2031. uint32_t n_ff_exp = 0;
  2032. uint32_t n_ff_shexp = 0;
  2033. uint32_t n_expert_shared = 0;
  2034. float expert_weights_scale = 0.0;
  2035. float f_norm_eps;
  2036. float f_norm_rms_eps;
  2037. float f_attn_logit_softcapping = 50.0f;
  2038. float f_final_logit_softcapping = 30.0f;
  2039. float rope_attn_factor = 1.0f;
  2040. float rope_freq_base_train;
  2041. float rope_freq_scale_train;
  2042. uint32_t n_ctx_orig_yarn;
  2043. float rope_yarn_log_mul;
  2044. // for State Space Models
  2045. uint32_t ssm_d_conv = 0;
  2046. uint32_t ssm_d_inner = 0;
  2047. uint32_t ssm_d_state = 0;
  2048. uint32_t ssm_dt_rank = 0;
  2049. float f_clamp_kqv = 0.0f;
  2050. float f_max_alibi_bias = 0.0f;
  2051. float f_logit_scale = 0.0f;
  2052. bool causal_attn = true;
  2053. bool use_alibi = false;
  2054. bool attn_soft_cap = false;
  2055. // needed by encoder-decoder models (e.g. T5, FLAN-T5)
  2056. // ref: https://github.com/ggerganov/llama.cpp/pull/8141
  2057. llama_token dec_start_token_id = -1;
  2058. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  2059. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  2060. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  2061. bool operator!=(const llama_hparams & other) const {
  2062. if (this->vocab_only != other.vocab_only) return true;
  2063. if (this->n_vocab != other.n_vocab) return true;
  2064. if (this->n_ctx_train != other.n_ctx_train) return true;
  2065. if (this->n_embd != other.n_embd) return true;
  2066. if (this->n_layer != other.n_layer) return true;
  2067. if (this->n_rot != other.n_rot) return true;
  2068. if (this->n_swa != other.n_swa) return true;
  2069. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  2070. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  2071. if (this->n_expert != other.n_expert) return true;
  2072. if (this->n_expert_used != other.n_expert_used) return true;
  2073. if (this->n_head_arr != other.n_head_arr) return true;
  2074. if (this->n_head_kv_arr != other.n_head_kv_arr) return true;
  2075. if (this->n_ff_arr != other.n_ff_arr) return true;
  2076. if (this->n_rel_attn_bkts != other.n_rel_attn_bkts) return true;
  2077. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  2078. if (this->n_lora_q != other.n_lora_q) return true;
  2079. if (this->n_lora_kv != other.n_lora_kv) return true;
  2080. if (this->n_ff_exp != other.n_ff_exp) return true;
  2081. if (this->n_ff_shexp != other.n_ff_shexp) return true;
  2082. if (this->n_expert_shared != other.n_expert_shared) return true;
  2083. if (this->rope_finetuned != other.rope_finetuned) return true;
  2084. if (this->n_ctx_orig_yarn != other.n_ctx_orig_yarn) return true;
  2085. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  2086. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  2087. if (this->ssm_d_state != other.ssm_d_state) return true;
  2088. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  2089. if (this->dec_start_token_id != other.dec_start_token_id) return true;
  2090. const float EPSILON = 1e-9f;
  2091. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  2092. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  2093. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  2094. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  2095. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  2096. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  2097. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  2098. return false;
  2099. }
  2100. uint32_t n_head(uint32_t il = 0) const {
  2101. if (il < n_layer) {
  2102. return n_head_arr[il];
  2103. }
  2104. GGML_ABORT("fatal error");
  2105. }
  2106. uint32_t n_head_kv(uint32_t il = 0) const {
  2107. if (il < n_layer) {
  2108. return n_head_kv_arr[il];
  2109. }
  2110. GGML_ABORT("fatal error");
  2111. }
  2112. uint32_t n_ff(uint32_t il = 0) const {
  2113. if (il < n_layer) {
  2114. return n_ff_arr[il];
  2115. }
  2116. GGML_ABORT("fatal error");
  2117. }
  2118. uint32_t n_gqa(uint32_t il = 0) const {
  2119. const uint32_t n_head = this->n_head(il);
  2120. const uint32_t n_head_kv = this->n_head_kv(il);
  2121. if (n_head_kv == 0) {
  2122. return 0;
  2123. }
  2124. return n_head/n_head_kv;
  2125. }
  2126. uint32_t n_embd_k_gqa(uint32_t il = 0) const { // dimension of key embeddings across all k-v heads
  2127. const uint32_t n_head_kv = this->n_head_kv(il);
  2128. return n_embd_head_k * n_head_kv;
  2129. }
  2130. uint32_t n_embd_v_gqa(uint32_t il = 0) const { // dimension of value embeddings across all k-v heads
  2131. const uint32_t n_head_kv = this->n_head_kv(il);
  2132. return n_embd_head_v * n_head_kv;
  2133. }
  2134. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  2135. // corresponds to Mamba's conv_states size
  2136. // TODO: maybe support other convolution strides than 1
  2137. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  2138. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  2139. }
  2140. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  2141. // corresponds to Mamba's ssm_states size
  2142. return ssm_d_state * ssm_d_inner;
  2143. }
  2144. };
  2145. static_assert(std::is_trivially_copyable<llama_hparams>::value, "llama_hparams must be trivially copyable");
  2146. struct llama_cparams {
  2147. uint32_t n_ctx; // context size used during inference
  2148. uint32_t n_batch;
  2149. uint32_t n_ubatch;
  2150. uint32_t n_seq_max;
  2151. uint32_t n_threads; // number of threads to use for generation
  2152. uint32_t n_threads_batch; // number of threads to use for batch processing
  2153. float rope_freq_base;
  2154. float rope_freq_scale;
  2155. uint32_t n_ctx_orig_yarn;
  2156. // These hyperparameters are not exposed in GGUF, because all
  2157. // existing YaRN models use the same values for them.
  2158. float yarn_ext_factor;
  2159. float yarn_attn_factor;
  2160. float yarn_beta_fast;
  2161. float yarn_beta_slow;
  2162. float defrag_thold;
  2163. bool embeddings;
  2164. bool causal_attn;
  2165. bool offload_kqv;
  2166. bool flash_attn;
  2167. enum llama_pooling_type pooling_type;
  2168. ggml_backend_sched_eval_callback cb_eval;
  2169. void * cb_eval_user_data;
  2170. };
  2171. // TODO: separate into "llama_layer_enc" and "llama_layer_dec"
  2172. struct llama_layer {
  2173. // normalization
  2174. struct ggml_tensor * attn_norm;
  2175. struct ggml_tensor * attn_norm_b;
  2176. struct ggml_tensor * attn_norm_2;
  2177. struct ggml_tensor * attn_norm_2_b;
  2178. struct ggml_tensor * attn_q_norm;
  2179. struct ggml_tensor * attn_q_norm_b;
  2180. struct ggml_tensor * attn_k_norm;
  2181. struct ggml_tensor * attn_k_norm_b;
  2182. struct ggml_tensor * attn_out_norm;
  2183. struct ggml_tensor * attn_out_norm_b;
  2184. struct ggml_tensor * attn_q_a_norm;
  2185. struct ggml_tensor * attn_kv_a_norm;
  2186. struct ggml_tensor * attn_sub_norm;
  2187. struct ggml_tensor * attn_post_norm;
  2188. struct ggml_tensor * ffn_sub_norm;
  2189. struct ggml_tensor * attn_norm_cross;
  2190. struct ggml_tensor * attn_norm_enc;
  2191. // attention
  2192. struct ggml_tensor * wq;
  2193. struct ggml_tensor * wk;
  2194. struct ggml_tensor * wv;
  2195. struct ggml_tensor * wo;
  2196. struct ggml_tensor * wqkv;
  2197. struct ggml_tensor * wq_a;
  2198. struct ggml_tensor * wq_b;
  2199. struct ggml_tensor * wkv_a_mqa;
  2200. struct ggml_tensor * wkv_b;
  2201. struct ggml_tensor * wq_cross;
  2202. struct ggml_tensor * wk_cross;
  2203. struct ggml_tensor * wv_cross;
  2204. struct ggml_tensor * wo_cross;
  2205. struct ggml_tensor * wq_enc;
  2206. struct ggml_tensor * wk_enc;
  2207. struct ggml_tensor * wv_enc;
  2208. struct ggml_tensor * wo_enc;
  2209. // attention bias
  2210. struct ggml_tensor * bq;
  2211. struct ggml_tensor * bk;
  2212. struct ggml_tensor * bv;
  2213. struct ggml_tensor * bo;
  2214. struct ggml_tensor * bqkv;
  2215. // relative position bias
  2216. struct ggml_tensor * attn_rel_b;
  2217. struct ggml_tensor * attn_rel_b_enc;
  2218. struct ggml_tensor * attn_rel_b_cross;
  2219. // normalization
  2220. struct ggml_tensor * ffn_norm;
  2221. struct ggml_tensor * ffn_norm_b;
  2222. struct ggml_tensor * ffn_post_norm;
  2223. struct ggml_tensor * layer_out_norm;
  2224. struct ggml_tensor * layer_out_norm_b;
  2225. struct ggml_tensor * ffn_norm_exps;
  2226. struct ggml_tensor * ffn_norm_enc;
  2227. // ff
  2228. struct ggml_tensor * ffn_gate; // w1
  2229. struct ggml_tensor * ffn_down; // w2
  2230. struct ggml_tensor * ffn_up; // w3
  2231. struct ggml_tensor * ffn_gate_enc;
  2232. struct ggml_tensor * ffn_down_enc;
  2233. struct ggml_tensor * ffn_up_enc;
  2234. // ff MoE
  2235. struct ggml_tensor * ffn_gate_inp;
  2236. struct ggml_tensor * ffn_gate_exps;
  2237. struct ggml_tensor * ffn_down_exps;
  2238. struct ggml_tensor * ffn_up_exps ;
  2239. // ff shared expert (shexp)
  2240. struct ggml_tensor * ffn_gate_inp_shexp;
  2241. struct ggml_tensor * ffn_gate_shexp;
  2242. struct ggml_tensor * ffn_down_shexp;
  2243. struct ggml_tensor * ffn_up_shexp;
  2244. // ff bias
  2245. struct ggml_tensor * ffn_gate_b = nullptr;
  2246. struct ggml_tensor * ffn_down_b = nullptr; // b2
  2247. struct ggml_tensor * ffn_up_b = nullptr; // b3
  2248. struct ggml_tensor * ffn_act;
  2249. // mamba proj
  2250. struct ggml_tensor * ssm_in;
  2251. struct ggml_tensor * ssm_x;
  2252. struct ggml_tensor * ssm_dt;
  2253. struct ggml_tensor * ssm_out;
  2254. // mamba
  2255. struct ggml_tensor * ssm_conv1d;
  2256. struct ggml_tensor * ssm_a;
  2257. struct ggml_tensor * ssm_d;
  2258. // mamba bias
  2259. struct ggml_tensor * ssm_conv1d_b;
  2260. struct ggml_tensor * ssm_dt_b;
  2261. // long rope factors
  2262. struct ggml_tensor * rope_long = nullptr;
  2263. struct ggml_tensor * rope_short = nullptr;
  2264. struct ggml_tensor * rope_freqs = nullptr;
  2265. // bitnet scale
  2266. struct ggml_tensor * wq_scale;
  2267. struct ggml_tensor * wk_scale;
  2268. struct ggml_tensor * wv_scale;
  2269. struct ggml_tensor * wo_scale;
  2270. struct ggml_tensor * ffn_gate_scale;
  2271. struct ggml_tensor * ffn_up_scale;
  2272. struct ggml_tensor * ffn_down_scale;
  2273. };
  2274. struct llama_kv_cell {
  2275. llama_pos pos = -1;
  2276. llama_pos delta = 0;
  2277. int32_t src = 0; // used by recurrent state models to copy states
  2278. std::set<llama_seq_id> seq_id;
  2279. bool has_seq_id(const llama_seq_id & id) const {
  2280. return seq_id.find(id) != seq_id.end();
  2281. }
  2282. bool is_empty() const {
  2283. return seq_id.empty();
  2284. }
  2285. bool is_same_seq(const llama_kv_cell & other) const {
  2286. return seq_id == other.seq_id;
  2287. }
  2288. };
  2289. // ring-buffer of cached KV data
  2290. struct llama_kv_cache {
  2291. bool has_shift = false;
  2292. bool do_defrag = false;
  2293. bool do_copy = false;
  2294. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  2295. bool v_trans = true; // the value tensor is transposed
  2296. // Note: The value of head isn't only used to optimize searching
  2297. // for a free KV slot. llama_decode_internal also uses it, so it
  2298. // cannot be freely changed after a slot has been allocated.
  2299. uint32_t head = 0;
  2300. uint32_t size = 0;
  2301. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  2302. // computed before each graph build
  2303. uint32_t n = 0;
  2304. ggml_type type_k = GGML_TYPE_F16;
  2305. ggml_type type_v = GGML_TYPE_F16;
  2306. std::vector<llama_kv_cell> cells;
  2307. std::vector<struct ggml_tensor *> k_l; // per layer
  2308. std::vector<struct ggml_tensor *> v_l;
  2309. std::vector<struct ggml_context *> ctxs;
  2310. std::vector<ggml_backend_buffer_t> bufs;
  2311. size_t total_size() const {
  2312. size_t size = 0;
  2313. for (ggml_backend_buffer_t buf : bufs) {
  2314. size += ggml_backend_buffer_get_size(buf);
  2315. }
  2316. return size;
  2317. }
  2318. ~llama_kv_cache() {
  2319. for (struct ggml_context * ctx : ctxs) {
  2320. ggml_free(ctx);
  2321. }
  2322. for (ggml_backend_buffer_t buf : bufs) {
  2323. ggml_backend_buffer_free(buf);
  2324. }
  2325. }
  2326. };
  2327. struct llama_control_vector {
  2328. std::vector<struct ggml_tensor *> tensors; // per layer
  2329. std::vector<struct ggml_context *> ctxs;
  2330. std::vector<ggml_backend_buffer_t> bufs;
  2331. int32_t layer_start = -1;
  2332. int32_t layer_end = -1;
  2333. struct ggml_tensor * tensor_for(int il) const {
  2334. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  2335. return nullptr;
  2336. }
  2337. return tensors[il];
  2338. }
  2339. struct ggml_tensor * apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  2340. ggml_tensor * layer_dir = tensor_for(il);
  2341. if (layer_dir != nullptr) {
  2342. cur = ggml_add(ctx, cur, layer_dir);
  2343. }
  2344. return cur;
  2345. }
  2346. ~llama_control_vector() {
  2347. for (struct ggml_context * ctx : ctxs) {
  2348. ggml_free(ctx);
  2349. }
  2350. for (ggml_backend_buffer_t buf : bufs) {
  2351. ggml_backend_buffer_free(buf);
  2352. }
  2353. }
  2354. };
  2355. struct llama_model {
  2356. e_model type = MODEL_UNKNOWN;
  2357. llm_arch arch = LLM_ARCH_UNKNOWN;
  2358. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  2359. std::string name = "n/a";
  2360. llama_hparams hparams = {};
  2361. llama_vocab vocab;
  2362. struct ggml_tensor * tok_embd;
  2363. struct ggml_tensor * type_embd;
  2364. struct ggml_tensor * pos_embd;
  2365. struct ggml_tensor * tok_norm;
  2366. struct ggml_tensor * tok_norm_b;
  2367. struct ggml_tensor * output_norm;
  2368. struct ggml_tensor * output_norm_b;
  2369. struct ggml_tensor * output;
  2370. struct ggml_tensor * output_b;
  2371. struct ggml_tensor * output_norm_enc;
  2372. std::vector<llama_layer> layers;
  2373. llama_split_mode split_mode;
  2374. int main_gpu;
  2375. int n_gpu_layers;
  2376. std::vector<std::string> rpc_servers;
  2377. // gguf metadata
  2378. std::unordered_map<std::string, std::string> gguf_kv;
  2379. // layer -> buffer type mapping
  2380. struct layer_buft {
  2381. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2382. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2383. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2384. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2385. ggml_backend_buffer_type_t buft; // everything else
  2386. };
  2387. layer_buft buft_input;
  2388. layer_buft buft_output;
  2389. std::vector<layer_buft> buft_layer;
  2390. // contexts where the model tensors metadata is stored
  2391. std::vector<struct ggml_context *> ctxs;
  2392. // the model memory buffers for the tensor data
  2393. std::vector<ggml_backend_buffer_t> bufs;
  2394. // model memory mapped files
  2395. llama_mmaps mappings;
  2396. // objects representing data potentially being locked in memory
  2397. llama_mlocks mlock_bufs;
  2398. llama_mlocks mlock_mmaps;
  2399. // for quantize-stats only
  2400. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2401. int64_t t_load_us = 0;
  2402. int64_t t_start_us = 0;
  2403. // keep track of loaded lora adapters
  2404. std::set<struct llama_lora_adapter *> lora_adapters;
  2405. ~llama_model() {
  2406. for (struct ggml_context * ctx : ctxs) {
  2407. ggml_free(ctx);
  2408. }
  2409. for (ggml_backend_buffer_t buf : bufs) {
  2410. #ifdef GGML_USE_CUDA
  2411. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2412. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2413. }
  2414. #endif
  2415. ggml_backend_buffer_free(buf);
  2416. }
  2417. while (!lora_adapters.empty()) {
  2418. llama_lora_adapter_free(*lora_adapters.begin());
  2419. }
  2420. }
  2421. };
  2422. struct llama_context {
  2423. llama_context(const llama_model & model)
  2424. : model(model)
  2425. , sampling(llama_n_vocab(&model))
  2426. , t_start_us(model.t_start_us)
  2427. , t_load_us(model.t_load_us) {}
  2428. ~llama_context() {
  2429. ggml_backend_sched_free(sched);
  2430. for (ggml_backend_t backend : backends) {
  2431. ggml_backend_free(backend);
  2432. }
  2433. ggml_backend_buffer_free(buf_output);
  2434. }
  2435. const struct llama_model & model;
  2436. struct llama_cparams cparams;
  2437. struct llama_sampling sampling;
  2438. struct llama_kv_cache kv_self;
  2439. struct llama_control_vector cvec;
  2440. std::unordered_map<struct llama_lora_adapter *, float> lora_adapters;
  2441. std::vector<ggml_backend_t> backends;
  2442. #ifdef GGML_USE_METAL
  2443. ggml_backend_t backend_metal = nullptr;
  2444. #endif
  2445. #ifdef GGML_USE_BLAS
  2446. ggml_backend_t backend_blas = nullptr;
  2447. #endif
  2448. ggml_backend_t backend_cpu = nullptr;
  2449. bool has_evaluated_once = false;
  2450. int64_t t_start_us;
  2451. int64_t t_load_us;
  2452. int64_t t_p_eval_us = 0;
  2453. int64_t t_eval_us = 0;
  2454. int64_t t_compute_start_us = 0;
  2455. int64_t n_queued_tokens = 0;
  2456. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  2457. int32_t n_eval = 0; // number of eval calls
  2458. // host buffer for the model output (logits and embeddings)
  2459. ggml_backend_buffer_t buf_output = nullptr;
  2460. // decode output (2-dimensional array: [n_outputs][n_vocab])
  2461. size_t logits_size = 0; // capacity (of floats) for logits
  2462. float * logits = nullptr;
  2463. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  2464. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  2465. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  2466. bool logits_all = false;
  2467. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  2468. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  2469. size_t embd_size = 0; // capacity (of floats) for embeddings
  2470. float * embd = nullptr;
  2471. // sequence embeddings output (map of [n_embd] vectors)
  2472. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2473. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2474. // whether we are computing encoder output or decoder output
  2475. bool is_encoding = false;
  2476. // output of the encoder part of the encoder-decoder models
  2477. std::vector<float> embd_enc;
  2478. std::vector<std::set<llama_seq_id>> seq_ids_enc;
  2479. // memory buffers used to evaluate the model
  2480. std::vector<uint8_t> buf_compute_meta;
  2481. ggml_backend_sched_t sched = nullptr;
  2482. ggml_abort_callback abort_callback = nullptr;
  2483. void * abort_callback_data = nullptr;
  2484. // input tensors
  2485. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2486. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2487. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2488. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2489. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2490. struct ggml_tensor * inp_KQ_mask_swa; // F32 [kv_size, n_batch]
  2491. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2492. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2493. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2494. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2495. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2496. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2497. struct ggml_tensor * inp_pos_bucket; // I32 [n_batch|n_kv, n_batch]
  2498. struct ggml_tensor * inp_embd_enc; // F32 [n_embd, n_outputs_enc]
  2499. struct ggml_tensor * inp_KQ_mask_cross; // F32 [n_outputs_enc, n_batch]
  2500. };
  2501. struct llama_lora_weight {
  2502. struct ggml_tensor * a = nullptr;
  2503. struct ggml_tensor * b = nullptr;
  2504. llama_lora_weight() = default;
  2505. llama_lora_weight(struct ggml_tensor * a, struct ggml_tensor * b): a(a), b(b) {}
  2506. };
  2507. struct llama_lora_adapter {
  2508. struct llama_model * base_model;
  2509. // map tensor name to lora_a_b
  2510. std::unordered_map<std::string, struct llama_lora_weight> ab_map;
  2511. std::vector<struct ggml_context *> ctxs;
  2512. std::vector<ggml_backend_buffer_t> bufs;
  2513. float alpha;
  2514. llama_lora_adapter(struct llama_model * base_model): base_model(base_model) {
  2515. base_model->lora_adapters.insert(this);
  2516. }
  2517. llama_lora_weight * get_weight(struct ggml_tensor * w) {
  2518. std::string name(w->name);
  2519. auto pos = ab_map.find(name);
  2520. if (ab_map.find(name) != ab_map.end()) {
  2521. return &pos->second;
  2522. }
  2523. return nullptr;
  2524. }
  2525. ~llama_lora_adapter() {
  2526. for (struct ggml_context * ctx : ctxs) {
  2527. ggml_free(ctx);
  2528. }
  2529. for (ggml_backend_buffer_t buf : bufs) {
  2530. ggml_backend_buffer_free(buf);
  2531. }
  2532. auto pos = base_model->lora_adapters.find(this);
  2533. if (pos != base_model->lora_adapters.end()) {
  2534. base_model->lora_adapters.erase(pos);
  2535. }
  2536. }
  2537. };
  2538. static size_t llama_get_device_count(const llama_model & model) {
  2539. size_t count = 1;
  2540. #if defined(GGML_USE_CUDA)
  2541. count = ggml_backend_cuda_get_device_count();
  2542. #elif defined(GGML_USE_SYCL)
  2543. count = ggml_backend_sycl_get_device_count();
  2544. #elif defined(GGML_USE_VULKAN)
  2545. count = ggml_backend_vk_get_device_count();
  2546. #elif defined(GGML_USE_CANN)
  2547. return ggml_backend_cann_get_device_count();
  2548. #endif
  2549. #if defined(GGML_USE_RPC)
  2550. count += model.rpc_servers.size();
  2551. #endif
  2552. return count;
  2553. GGML_UNUSED(model);
  2554. }
  2555. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2556. ggml_backend_buffer_type_t buft = nullptr;
  2557. #if defined(GGML_USE_RPC)
  2558. int dev_count = (int)llama_get_device_count(model);
  2559. int rpc_count = (int)model.rpc_servers.size();
  2560. if (gpu >= dev_count - rpc_count) {
  2561. const char * endpoint = model.rpc_servers[gpu - dev_count + rpc_count].c_str();
  2562. return ggml_backend_rpc_buffer_type(endpoint);
  2563. }
  2564. #endif
  2565. #if defined(GGML_USE_METAL)
  2566. buft = ggml_backend_metal_buffer_type();
  2567. #elif defined(GGML_USE_CUDA)
  2568. buft = ggml_backend_cuda_buffer_type(gpu);
  2569. #elif defined(GGML_USE_VULKAN)
  2570. buft = ggml_backend_vk_buffer_type(gpu);
  2571. #elif defined(GGML_USE_SYCL)
  2572. buft = ggml_backend_sycl_buffer_type(gpu);
  2573. #elif defined(GGML_USE_KOMPUTE)
  2574. buft = ggml_backend_kompute_buffer_type(gpu);
  2575. if (buft == nullptr) {
  2576. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2577. }
  2578. #elif defined(GGML_USE_CANN)
  2579. buft = ggml_backend_cann_buffer_type(gpu);
  2580. #endif
  2581. if (buft == nullptr) {
  2582. buft = llama_default_buffer_type_cpu(true);
  2583. }
  2584. return buft;
  2585. GGML_UNUSED(model);
  2586. GGML_UNUSED(gpu);
  2587. }
  2588. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2589. ggml_backend_buffer_type_t buft = nullptr;
  2590. #ifdef GGML_USE_CUDA
  2591. if (ggml_backend_cuda_get_device_count() > 1) {
  2592. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2593. }
  2594. #endif
  2595. #ifdef GGML_USE_SYCL
  2596. if (ggml_backend_sycl_get_device_count() > 1) {
  2597. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2598. }
  2599. #endif
  2600. if (buft == nullptr) {
  2601. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2602. }
  2603. return buft;
  2604. GGML_UNUSED(tensor_split);
  2605. }
  2606. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2607. #if defined(GGML_USE_RPC)
  2608. int dev_count = (int)llama_get_device_count(model);
  2609. int rpc_count = (int)model.rpc_servers.size();
  2610. if (device >= dev_count - rpc_count) {
  2611. size_t total;
  2612. size_t free;
  2613. const char * endpoint = model.rpc_servers[device - dev_count + rpc_count].c_str();
  2614. ggml_backend_rpc_get_device_memory(endpoint, &free, &total);
  2615. return free;
  2616. }
  2617. #endif
  2618. #if defined(GGML_USE_CUDA)
  2619. size_t total;
  2620. size_t free;
  2621. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2622. return free;
  2623. #elif defined(GGML_USE_SYCL)
  2624. size_t total;
  2625. size_t free;
  2626. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2627. return free;
  2628. #elif defined(GGML_USE_VULKAN)
  2629. size_t total;
  2630. size_t free;
  2631. ggml_backend_vk_get_device_memory(device, &free, &total);
  2632. return free;
  2633. #elif defined(GGML_USE_CANN)
  2634. size_t total;
  2635. size_t free;
  2636. ggml_backend_cann_get_device_memory(device, &free, &total);
  2637. return free;
  2638. #else
  2639. return 1;
  2640. #endif
  2641. GGML_UNUSED(model);
  2642. GGML_UNUSED(device);
  2643. }
  2644. //
  2645. // kv cache helpers
  2646. //
  2647. static bool llama_kv_cache_init(
  2648. struct llama_kv_cache & cache,
  2649. const llama_context * ctx,
  2650. ggml_type type_k,
  2651. ggml_type type_v,
  2652. uint32_t kv_size,
  2653. bool offload) {
  2654. const llama_model & model = ctx->model;
  2655. const llama_cparams & cparams = ctx->cparams;
  2656. const struct llama_hparams & hparams = model.hparams;
  2657. const int64_t n_layer = hparams.n_layer;
  2658. cache.has_shift = false;
  2659. // TODO: find a nicer way to add other recurrent model architectures
  2660. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2661. cache.v_trans = !cache.recurrent && !cparams.flash_attn;
  2662. cache.head = 0;
  2663. cache.size = kv_size;
  2664. cache.used = 0;
  2665. cache.type_k = type_k;
  2666. cache.type_v = type_v;
  2667. cache.cells.clear();
  2668. cache.cells.resize(kv_size);
  2669. if (cache.recurrent) {
  2670. // init state copy sources
  2671. for (uint32_t i = 0; i < cache.size; ++i) {
  2672. cache.cells[i].src = i;
  2673. }
  2674. }
  2675. // count used buffer types
  2676. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2677. if (offload) {
  2678. for (int64_t i = 0; i < n_layer; ++i) {
  2679. buft_layer_count[model.buft_layer[i].buft]++;
  2680. }
  2681. } else {
  2682. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2683. }
  2684. // create a context for each buffer type
  2685. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2686. for (auto & it : buft_layer_count) {
  2687. int n_layers = it.second;
  2688. struct ggml_init_params params = {
  2689. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2690. /*.mem_buffer =*/ NULL,
  2691. /*.no_alloc =*/ true,
  2692. };
  2693. ggml_context * ctx = ggml_init(params);
  2694. if (!ctx) {
  2695. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2696. return false;
  2697. }
  2698. ctx_map[it.first] = ctx;
  2699. cache.ctxs.push_back(ctx);
  2700. }
  2701. cache.k_l.reserve(n_layer);
  2702. cache.v_l.reserve(n_layer);
  2703. for (int i = 0; i < (int) n_layer; i++) {
  2704. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(i) + hparams.n_embd_k_s();
  2705. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(i) + hparams.n_embd_v_s();
  2706. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2707. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2708. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2709. ggml_format_name(k, "cache_k_l%d", i);
  2710. ggml_format_name(v, "cache_v_l%d", i);
  2711. cache.k_l.push_back(k);
  2712. cache.v_l.push_back(v);
  2713. }
  2714. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2715. for (auto it : ctx_map) {
  2716. ggml_backend_buffer_type_t buft = it.first;
  2717. ggml_context * ctx = it.second;
  2718. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2719. if (!buf) {
  2720. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2721. return false;
  2722. }
  2723. ggml_backend_buffer_clear(buf, 0);
  2724. 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);
  2725. cache.bufs.push_back(buf);
  2726. }
  2727. return true;
  2728. }
  2729. // find an empty slot of size "n_tokens" in the cache
  2730. // updates the cache head
  2731. // Note: On success, it's important that cache.head points
  2732. // to the first cell of the slot.
  2733. static bool llama_kv_cache_find_slot(
  2734. struct llama_kv_cache & cache,
  2735. const struct llama_batch & batch) {
  2736. const uint32_t n_tokens = batch.n_tokens;
  2737. if (cache.recurrent) {
  2738. // For recurrent state architectures (like Mamba),
  2739. // each KV cache cell can store the state for a whole sequence.
  2740. llama_seq_id min = cache.size - 1;
  2741. llama_seq_id max = 0;
  2742. for (uint32_t i = 0; i < n_tokens; ++i) {
  2743. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2744. llama_seq_id seq_id = batch.seq_id[i][j];
  2745. // make sure it's a valid seq_id
  2746. if ((uint32_t) seq_id < cache.size) {
  2747. if (seq_id > max) {
  2748. max = seq_id;
  2749. }
  2750. if (seq_id < min) {
  2751. min = seq_id;
  2752. }
  2753. // Assuming the tokens are in-order
  2754. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2755. // What should happen when the pos backtracks or skips a value?
  2756. // Clearing the state mid-batch would require special-casing which isn't done.
  2757. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2758. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2759. }
  2760. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2761. cache.used += 1;
  2762. }
  2763. cache.cells[seq_id].pos = batch.pos[i];
  2764. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2765. } else {
  2766. // too big seq_id
  2767. // TODO: would it be possible to resize the KV cache size instead?
  2768. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2769. return false;
  2770. }
  2771. }
  2772. }
  2773. // allow getting the range of used cells, from head to head + n
  2774. cache.head = min;
  2775. cache.n = max - min + 1;
  2776. // sanity check
  2777. return max >= min;
  2778. }
  2779. // otherwise, one cell per token.
  2780. if (n_tokens > cache.size) {
  2781. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  2782. return false;
  2783. }
  2784. uint32_t n_tested = 0;
  2785. while (true) {
  2786. if (cache.head + n_tokens > cache.size) {
  2787. n_tested += cache.size - cache.head;
  2788. cache.head = 0;
  2789. continue;
  2790. }
  2791. bool found = true;
  2792. for (uint32_t i = 0; i < n_tokens; i++) {
  2793. if (cache.cells[cache.head + i].pos >= 0) {
  2794. found = false;
  2795. cache.head += i + 1;
  2796. n_tested += i + 1;
  2797. break;
  2798. }
  2799. }
  2800. if (found) {
  2801. break;
  2802. }
  2803. if (n_tested >= cache.size) {
  2804. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2805. return false;
  2806. }
  2807. }
  2808. for (uint32_t i = 0; i < n_tokens; i++) {
  2809. cache.cells[cache.head + i].pos = batch.pos[i];
  2810. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2811. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2812. }
  2813. }
  2814. cache.used += n_tokens;
  2815. return true;
  2816. }
  2817. // find how many cells are currently in use
  2818. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2819. for (uint32_t i = cache.size; i > 0; --i) {
  2820. const llama_kv_cell & cell = cache.cells[i - 1];
  2821. if (cell.pos >= 0 && !cell.is_empty()) {
  2822. return i;
  2823. }
  2824. }
  2825. return 0;
  2826. }
  2827. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2828. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2829. cache.cells[i].pos = -1;
  2830. cache.cells[i].seq_id.clear();
  2831. }
  2832. cache.head = 0;
  2833. cache.used = 0;
  2834. for (auto & buf : cache.bufs) {
  2835. ggml_backend_buffer_clear(buf, 0);
  2836. }
  2837. }
  2838. static bool llama_kv_cache_seq_rm(
  2839. struct llama_kv_cache & cache,
  2840. llama_seq_id seq_id,
  2841. llama_pos p0,
  2842. llama_pos p1) {
  2843. uint32_t new_head = cache.size;
  2844. if (p0 < 0) p0 = 0;
  2845. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2846. // models like Mamba can't have a state partially erased
  2847. if (cache.recurrent) {
  2848. if (seq_id >= (int64_t) cache.size) {
  2849. // could be fatal
  2850. return false;
  2851. }
  2852. if (0 <= seq_id) {
  2853. // partial intersection is invalid
  2854. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2855. return false;
  2856. }
  2857. } else {
  2858. // seq_id is negative, then the range should include everything or nothing
  2859. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2860. return false;
  2861. }
  2862. }
  2863. }
  2864. for (uint32_t i = 0; i < cache.size; ++i) {
  2865. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2866. if (seq_id < 0) {
  2867. cache.cells[i].seq_id.clear();
  2868. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2869. cache.cells[i].seq_id.erase(seq_id);
  2870. } else {
  2871. continue;
  2872. }
  2873. if (cache.cells[i].is_empty()) {
  2874. // keep count of the number of used cells
  2875. if (cache.cells[i].pos >= 0) cache.used--;
  2876. cache.cells[i].pos = -1;
  2877. if (new_head == cache.size) new_head = i;
  2878. }
  2879. }
  2880. }
  2881. // If we freed up a slot, set head to it so searching can start there.
  2882. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2883. return true;
  2884. }
  2885. static void llama_kv_cache_seq_cp(
  2886. struct llama_kv_cache & cache,
  2887. llama_seq_id seq_id_src,
  2888. llama_seq_id seq_id_dst,
  2889. llama_pos p0,
  2890. llama_pos p1) {
  2891. if (p0 < 0) p0 = 0;
  2892. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2893. if (cache.recurrent) {
  2894. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2895. seq_id_src = cache.cells[seq_id_src].src;
  2896. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2897. // intent to "copy from"
  2898. // supports copy chains thanks to taking the source of the source
  2899. cache.cells[seq_id_dst].src = seq_id_src;
  2900. // preserve the "keep or clear" status of the copied sequence
  2901. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2902. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2903. } else {
  2904. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2905. }
  2906. cache.do_copy = true;
  2907. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2908. }
  2909. return;
  2910. }
  2911. // otherwise, this is the KV cache of a Transformer-like model
  2912. cache.head = 0;
  2913. for (uint32_t i = 0; i < cache.size; ++i) {
  2914. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2915. cache.cells[i].seq_id.insert(seq_id_dst);
  2916. }
  2917. }
  2918. }
  2919. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2920. uint32_t new_head = cache.size;
  2921. for (uint32_t i = 0; i < cache.size; ++i) {
  2922. if (!cache.cells[i].has_seq_id(seq_id)) {
  2923. if (cache.cells[i].pos >= 0) cache.used--;
  2924. cache.cells[i].pos = -1;
  2925. cache.cells[i].seq_id.clear();
  2926. if (new_head == cache.size) new_head = i;
  2927. } else {
  2928. cache.cells[i].seq_id.clear();
  2929. cache.cells[i].seq_id.insert(seq_id);
  2930. }
  2931. }
  2932. // If we freed up a slot, set head to it so searching can start there.
  2933. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2934. }
  2935. static void llama_kv_cache_seq_add(
  2936. struct llama_kv_cache & cache,
  2937. llama_seq_id seq_id,
  2938. llama_pos p0,
  2939. llama_pos p1,
  2940. llama_pos delta) {
  2941. uint32_t new_head = cache.size;
  2942. if (p0 < 0) p0 = 0;
  2943. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2944. // If there is no range then return early to avoid looping over the cache.
  2945. if (p0 == p1) return;
  2946. if (cache.recurrent) {
  2947. // for Mamba-like models, only the pos needs to be shifted
  2948. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2949. llama_kv_cell & cell = cache.cells[seq_id];
  2950. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2951. cell.pos += delta;
  2952. }
  2953. }
  2954. return;
  2955. }
  2956. for (uint32_t i = 0; i < cache.size; ++i) {
  2957. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2958. cache.has_shift = true;
  2959. cache.cells[i].pos += delta;
  2960. cache.cells[i].delta += delta;
  2961. if (cache.cells[i].pos < 0) {
  2962. if (!cache.cells[i].is_empty()) {
  2963. cache.used--;
  2964. }
  2965. cache.cells[i].pos = -1;
  2966. cache.cells[i].seq_id.clear();
  2967. if (new_head == cache.size) {
  2968. new_head = i;
  2969. }
  2970. }
  2971. }
  2972. }
  2973. // If we freed up a slot, set head to it so searching can start there.
  2974. // Otherwise we just start the next search from the beginning.
  2975. cache.head = new_head != cache.size ? new_head : 0;
  2976. }
  2977. static void llama_kv_cache_seq_div(
  2978. struct llama_kv_cache & cache,
  2979. llama_seq_id seq_id,
  2980. llama_pos p0,
  2981. llama_pos p1,
  2982. int d) {
  2983. if (p0 < 0) p0 = 0;
  2984. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2985. // If there is no range then return early to avoid looping over the cache.
  2986. if (p0 == p1) return;
  2987. if (cache.recurrent) {
  2988. // for Mamba-like models, only the pos needs to be changed
  2989. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2990. llama_kv_cell & cell = cache.cells[seq_id];
  2991. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2992. cell.pos /= d;
  2993. }
  2994. }
  2995. return;
  2996. }
  2997. for (uint32_t i = 0; i < cache.size; ++i) {
  2998. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2999. cache.has_shift = true;
  3000. {
  3001. llama_pos p_old = cache.cells[i].pos;
  3002. cache.cells[i].pos /= d;
  3003. cache.cells[i].delta += cache.cells[i].pos - p_old;
  3004. }
  3005. }
  3006. }
  3007. }
  3008. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  3009. llama_pos result = 0;
  3010. for (uint32_t i = 0; i < cache.size; ++i) {
  3011. if (cache.cells[i].has_seq_id(seq_id)) {
  3012. result = std::max(result, cache.cells[i].pos);
  3013. }
  3014. }
  3015. return result;
  3016. }
  3017. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  3018. cache.do_defrag = true;
  3019. }
  3020. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  3021. // the FA kernels require padding to avoid extra runtime boundary checks
  3022. return cparams.flash_attn ? 256u : 32u;
  3023. }
  3024. //
  3025. // model loading and saving
  3026. //
  3027. enum llama_fver {
  3028. GGUF_FILE_VERSION_V1 = 1,
  3029. GGUF_FILE_VERSION_V2 = 2,
  3030. GGUF_FILE_VERSION_V3 = 3,
  3031. };
  3032. static const char * llama_file_version_name(llama_fver version) {
  3033. switch (version) {
  3034. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  3035. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  3036. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  3037. }
  3038. return "unknown";
  3039. }
  3040. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  3041. char buf[256];
  3042. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  3043. for (size_t i = 1; i < ne.size(); i++) {
  3044. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  3045. }
  3046. return buf;
  3047. }
  3048. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  3049. char buf[256];
  3050. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  3051. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3052. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  3053. }
  3054. return buf;
  3055. }
  3056. namespace GGUFMeta {
  3057. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  3058. struct GKV_Base_Type {
  3059. static constexpr gguf_type gt = gt_;
  3060. static T getter(const gguf_context * ctx, const int kid) {
  3061. return gfun(ctx, kid);
  3062. }
  3063. };
  3064. template<typename T> struct GKV_Base;
  3065. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  3066. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  3067. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  3068. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  3069. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  3070. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  3071. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  3072. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  3073. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  3074. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  3075. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  3076. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  3077. template<> struct GKV_Base<std::string> {
  3078. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  3079. static std::string getter(const gguf_context * ctx, const int kid) {
  3080. return gguf_get_val_str(ctx, kid);
  3081. }
  3082. };
  3083. struct ArrayInfo {
  3084. const gguf_type gt;
  3085. const size_t length;
  3086. const void * data;
  3087. };
  3088. template<> struct GKV_Base<ArrayInfo> {
  3089. public:
  3090. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  3091. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  3092. return ArrayInfo {
  3093. gguf_get_arr_type(ctx, k),
  3094. size_t(gguf_get_arr_n(ctx, k)),
  3095. gguf_get_arr_data(ctx, k),
  3096. };
  3097. }
  3098. };
  3099. template<typename T>
  3100. class GKV : public GKV_Base<T> {
  3101. GKV() = delete;
  3102. public:
  3103. static T get_kv(const gguf_context * ctx, const int k) {
  3104. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  3105. if (kt != GKV::gt) {
  3106. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  3107. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  3108. }
  3109. return GKV::getter(ctx, k);
  3110. }
  3111. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  3112. switch (ty) {
  3113. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  3114. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  3115. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  3116. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  3117. }
  3118. return "unknown";
  3119. }
  3120. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  3121. if (!ovrd) { return false; }
  3122. if (ovrd->tag == expected_type) {
  3123. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  3124. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  3125. switch (ovrd->tag) {
  3126. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  3127. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  3128. } break;
  3129. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  3130. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  3131. } break;
  3132. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  3133. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  3134. } break;
  3135. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  3136. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  3137. } break;
  3138. default:
  3139. // Shouldn't be possible to end up here, but just in case...
  3140. throw std::runtime_error(
  3141. format("Unsupported attempt to override %s type for metadata key %s\n",
  3142. override_type_to_str(ovrd->tag), ovrd->key));
  3143. }
  3144. return true;
  3145. }
  3146. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  3147. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  3148. return false;
  3149. }
  3150. template<typename OT>
  3151. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  3152. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3153. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  3154. target = ovrd->val_bool;
  3155. return true;
  3156. }
  3157. return false;
  3158. }
  3159. template<typename OT>
  3160. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  3161. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  3162. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  3163. target = ovrd->val_i64;
  3164. return true;
  3165. }
  3166. return false;
  3167. }
  3168. template<typename OT>
  3169. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  3170. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3171. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  3172. target = ovrd->val_f64;
  3173. return true;
  3174. }
  3175. return false;
  3176. }
  3177. template<typename OT>
  3178. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  3179. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  3180. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  3181. target = ovrd->val_str;
  3182. return true;
  3183. }
  3184. return false;
  3185. }
  3186. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3187. if (try_override<T>(target, ovrd)) {
  3188. return true;
  3189. }
  3190. if (k < 0) { return false; }
  3191. target = get_kv(ctx, k);
  3192. return true;
  3193. }
  3194. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3195. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  3196. }
  3197. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  3198. return set(ctx, key.c_str(), target, ovrd);
  3199. }
  3200. };
  3201. }
  3202. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  3203. // TODO: update when needed or think of some clever automatic way to do this
  3204. static size_t llama_model_max_nodes(const llama_model & /*model*/) {
  3205. //if (model.arch == LLM_ARCH_LLAMA && model.hparams.n_layer > ??) { // llama-3 405B
  3206. // return 32768;
  3207. //}
  3208. return 8192;
  3209. }
  3210. struct llama_model_loader {
  3211. int n_kv = 0;
  3212. int n_tensors = 0;
  3213. int n_created = 0;
  3214. int64_t n_elements = 0;
  3215. size_t n_bytes = 0;
  3216. bool use_mmap = false;
  3217. bool check_tensors;
  3218. llama_files files;
  3219. llama_ftype ftype;
  3220. llama_fver fver;
  3221. llama_mmaps mappings;
  3222. // Holds information on a model weight
  3223. struct llama_tensor_weight {
  3224. uint16_t idx; // source file index
  3225. size_t offs; // tensor data offset in the original file
  3226. ggml_tensor * tensor;
  3227. 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) {
  3228. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  3229. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  3230. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  3231. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  3232. }
  3233. }
  3234. };
  3235. std::vector<llama_tensor_weight> weights;
  3236. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  3237. struct gguf_context * meta = NULL;
  3238. std::vector<ggml_context *> contexts;
  3239. std::string arch_name;
  3240. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  3241. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  3242. int trace = 0;
  3243. if (getenv("LLAMA_TRACE")) {
  3244. trace = atoi(getenv("LLAMA_TRACE"));
  3245. }
  3246. if (param_overrides_p != nullptr) {
  3247. for (const struct llama_model_kv_override * p = param_overrides_p; p->key[0] != 0; p++) {
  3248. kv_overrides.insert({std::string(p->key), *p});
  3249. }
  3250. }
  3251. struct ggml_context * ctx = NULL;
  3252. struct gguf_init_params params = {
  3253. /*.no_alloc = */ true,
  3254. /*.ctx = */ &ctx,
  3255. };
  3256. meta = gguf_init_from_file(fname.c_str(), params);
  3257. if (!meta) {
  3258. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  3259. }
  3260. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  3261. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  3262. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  3263. contexts.emplace_back(ctx);
  3264. // Save tensors data offset of the main file.
  3265. // For subsidiary files, `meta` tensor data offset must not be used,
  3266. // so we build a unified tensors index for weights.
  3267. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3268. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  3269. }
  3270. uint16_t n_split = 0;
  3271. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  3272. // Load additional GGML contexts
  3273. if (n_split > 1) {
  3274. uint16_t idx = 0;
  3275. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  3276. if (idx != 0) {
  3277. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  3278. }
  3279. char split_prefix[PATH_MAX] = {0};
  3280. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  3281. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  3282. }
  3283. if (trace > 0) {
  3284. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  3285. }
  3286. char split_path[PATH_MAX] = {0};
  3287. for (idx = 1; idx < n_split; idx++) {
  3288. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  3289. struct gguf_init_params split_params = {
  3290. /*.no_alloc = */ true,
  3291. /*.ctx = */ &ctx,
  3292. };
  3293. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  3294. if (!ctx_gguf) {
  3295. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  3296. }
  3297. files.emplace_back(new llama_file(split_path, "rb"));
  3298. contexts.emplace_back(ctx);
  3299. // Save tensors data offset info of the shard.
  3300. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  3301. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  3302. }
  3303. gguf_free(ctx_gguf);
  3304. }
  3305. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  3306. // sanity check
  3307. {
  3308. const int n_tensors_loaded = (int) weights.size();
  3309. if (n_tensors != n_tensors_loaded) {
  3310. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  3311. }
  3312. }
  3313. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  3314. }
  3315. n_kv = gguf_get_n_kv(meta);
  3316. n_tensors = weights.size();
  3317. fver = (enum llama_fver) gguf_get_version(meta);
  3318. std::set<std::string> tensor_names;
  3319. for (auto & w : weights) {
  3320. n_elements += ggml_nelements(w.tensor);
  3321. n_bytes += ggml_nbytes(w.tensor);
  3322. // make sure there is no duplicated tensor names
  3323. const std::string name(w.tensor->name);
  3324. auto found = tensor_names.find(name);
  3325. if (found != tensor_names.end()) {
  3326. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  3327. }
  3328. tensor_names.insert(name);
  3329. }
  3330. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  3331. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  3332. // determine file type based on the number of tensors for each quantization and print meta data
  3333. // TODO: make optional
  3334. {
  3335. std::map<enum ggml_type, uint32_t> n_type;
  3336. uint32_t n_type_max = 0;
  3337. enum ggml_type type_max = GGML_TYPE_F32;
  3338. for (int i = 0; i < n_tensors; i++) {
  3339. const ggml_tensor * tensor = weights.at(i).tensor;
  3340. enum ggml_type type = tensor->type;
  3341. n_type[type]++;
  3342. if (n_type_max < n_type[type]) {
  3343. n_type_max = n_type[type];
  3344. type_max = type;
  3345. }
  3346. if (trace > 0) {
  3347. const uint16_t sid = weights.at(i).idx;
  3348. 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());
  3349. }
  3350. }
  3351. switch (type_max) {
  3352. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  3353. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  3354. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  3355. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  3356. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  3357. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  3358. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  3359. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  3360. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  3361. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  3362. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  3363. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  3364. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  3365. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  3366. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  3367. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  3368. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  3369. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  3370. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  3371. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  3372. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  3373. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  3374. case GGML_TYPE_Q4_0_4_4: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_4; break;
  3375. case GGML_TYPE_Q4_0_4_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_4_8; break;
  3376. case GGML_TYPE_Q4_0_8_8: ftype = LLAMA_FTYPE_MOSTLY_Q4_0_8_8; break;
  3377. default:
  3378. {
  3379. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  3380. ftype = LLAMA_FTYPE_ALL_F32;
  3381. } break;
  3382. }
  3383. // this is a way to mark that we have "guessed" the file type
  3384. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  3385. {
  3386. const int kid = gguf_find_key(meta, "general.file_type"); // TODO: use LLM_KV
  3387. if (kid >= 0) {
  3388. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  3389. }
  3390. }
  3391. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  3392. for (int i = 0; i < n_kv; i++) {
  3393. const char * name = gguf_get_key(meta, i);
  3394. const enum gguf_type type = gguf_get_kv_type(meta, i);
  3395. const std::string type_name =
  3396. type == GGUF_TYPE_ARRAY
  3397. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  3398. : gguf_type_name(type);
  3399. std::string value = gguf_kv_to_str(meta, i);
  3400. const size_t MAX_VALUE_LEN = 40;
  3401. if (value.size() > MAX_VALUE_LEN) {
  3402. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  3403. }
  3404. replace_all(value, "\n", "\\n");
  3405. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  3406. }
  3407. // print type counts
  3408. for (auto & kv : n_type) {
  3409. if (kv.second == 0) {
  3410. continue;
  3411. }
  3412. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  3413. }
  3414. }
  3415. if (!llama_mmap::SUPPORTED) {
  3416. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  3417. use_mmap = false;
  3418. }
  3419. this->use_mmap = use_mmap;
  3420. this->check_tensors = check_tensors;
  3421. }
  3422. ~llama_model_loader() {
  3423. if (meta) {
  3424. gguf_free(meta);
  3425. }
  3426. for (auto * ctx : contexts) {
  3427. ggml_free(ctx);
  3428. }
  3429. }
  3430. template<typename T>
  3431. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3432. get_arr_n(const std::string & key, T & result, const bool required = true) {
  3433. const int kid = gguf_find_key(meta, key.c_str());
  3434. if (kid < 0) {
  3435. if (required) {
  3436. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3437. }
  3438. return false;
  3439. }
  3440. struct GGUFMeta::ArrayInfo arr_info =
  3441. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3442. result = arr_info.length;
  3443. return true;
  3444. }
  3445. template<typename T>
  3446. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3447. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  3448. return get_arr_n(llm_kv(kid), result, required);
  3449. }
  3450. template<typename T>
  3451. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  3452. const int kid = gguf_find_key(meta, key.c_str());
  3453. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3454. if (required) {
  3455. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3456. }
  3457. return false;
  3458. }
  3459. struct GGUFMeta::ArrayInfo arr_info =
  3460. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3461. switch (arr_info.gt) {
  3462. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3463. case GGUF_TYPE_INT32: GGML_ASSERT(
  3464. (std::is_same<T, int32_t>::value) ||
  3465. (std::is_same<T, uint32_t>::value)); break;
  3466. default:
  3467. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3468. }
  3469. result.resize(arr_info.length);
  3470. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  3471. return true;
  3472. }
  3473. template<typename T, size_t N_MAX>
  3474. bool get_arr(const std::string & key, std::array<T, N_MAX> & result, const bool required = true) {
  3475. const int kid = gguf_find_key(meta, key.c_str());
  3476. if (kid < 0 || gguf_get_kv_type(meta, kid) != GGUF_TYPE_ARRAY) {
  3477. if (required) {
  3478. throw std::runtime_error(format("array key not found in model: %s", key.c_str()));
  3479. }
  3480. return false;
  3481. }
  3482. struct GGUFMeta::ArrayInfo arr_info =
  3483. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3484. switch (arr_info.gt) {
  3485. case GGUF_TYPE_FLOAT32: GGML_ASSERT((std::is_same<T, float>::value)); break;
  3486. case GGUF_TYPE_INT32: GGML_ASSERT(
  3487. (std::is_same<T, int32_t>::value) ||
  3488. (std::is_same<T, uint32_t>::value)); break;
  3489. default:
  3490. throw std::runtime_error(format("%s is not a float32, int32 array", key.c_str()));
  3491. }
  3492. if (arr_info.length > N_MAX) {
  3493. 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));
  3494. }
  3495. std::copy((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length, result.begin());
  3496. return true;
  3497. }
  3498. template<typename T>
  3499. bool get_arr(const enum llm_kv kid, T & result, const bool required = true) {
  3500. return get_arr(llm_kv(kid), result, required);
  3501. }
  3502. template<typename T>
  3503. bool get_key(const std::string & key, T & result, const bool required = true) {
  3504. auto it = kv_overrides.find(key);
  3505. const struct llama_model_kv_override * override =
  3506. it != kv_overrides.end() ? &it->second : nullptr;
  3507. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  3508. if (required && !found) {
  3509. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3510. }
  3511. return found;
  3512. }
  3513. template<typename T>
  3514. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  3515. return get_key(llm_kv(kid), result, required);
  3516. }
  3517. // get array of n <= N_MAX elements, or a single element repeated n times
  3518. template<typename T, size_t N_MAX>
  3519. bool get_key_or_arr(const std::string & key, std::array<T, N_MAX> & result, uint32_t n, const bool required = true) {
  3520. const int kid = gguf_find_key(meta, key.c_str());
  3521. if (kid < 0) {
  3522. if (required) {
  3523. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3524. }
  3525. return false;
  3526. }
  3527. if (n > N_MAX) {
  3528. throw std::runtime_error(format("n > N_MAX: %u > %u for key %s", (uint32_t) n, (uint32_t) N_MAX, key.c_str()));
  3529. }
  3530. if (gguf_get_kv_type(meta, kid) == GGUF_TYPE_ARRAY) {
  3531. struct GGUFMeta::ArrayInfo arr_info =
  3532. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3533. if (n != arr_info.length) {
  3534. throw std::runtime_error(format("key %s has wrong array length; expected %u, got %u", key.c_str(), n, (uint32_t) arr_info.length));
  3535. }
  3536. return get_arr(key, result, required);
  3537. } else {
  3538. T value;
  3539. bool ok = get_key(key, value, required);
  3540. if (!ok) {
  3541. return false;
  3542. }
  3543. for (uint32_t i = 0; i < n; i++) {
  3544. result[i] = value;
  3545. }
  3546. return true;
  3547. }
  3548. }
  3549. template<typename T>
  3550. bool get_key_or_arr(const enum llm_kv kid, T & result, uint32_t n, const bool required = true) {
  3551. return get_key_or_arr(llm_kv(kid), result, n, required);
  3552. }
  3553. std::string get_arch_name() const {
  3554. return arch_name;
  3555. }
  3556. enum llm_arch get_arch() const {
  3557. return llm_kv.arch;
  3558. }
  3559. const char * get_tensor_name(int i) const {
  3560. return weights.at(i).tensor->name;
  3561. }
  3562. const llama_tensor_weight * get_weight(const char * name) const {
  3563. for (const auto & weight : weights) {
  3564. if (strcmp(name, weight.tensor->name) == 0) {
  3565. return &weight;
  3566. }
  3567. }
  3568. return nullptr;
  3569. }
  3570. const llama_tensor_weight * get_weight(int i) const {
  3571. return get_weight(get_tensor_name(i));
  3572. }
  3573. const llama_tensor_weight & require_weight(const char * name) const {
  3574. const llama_tensor_weight * weight = get_weight(name);
  3575. if (!weight) {
  3576. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3577. }
  3578. return *weight;
  3579. }
  3580. struct ggml_tensor * get_tensor_meta(const char * name) const {
  3581. const auto * weight = get_weight(name);
  3582. if (!weight) {
  3583. return nullptr;
  3584. }
  3585. return weight->tensor;
  3586. }
  3587. struct ggml_tensor * require_tensor_meta(const char * name) const {
  3588. struct ggml_tensor * tensor = get_tensor_meta(name);
  3589. if (!tensor) {
  3590. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3591. }
  3592. return tensor;
  3593. }
  3594. struct ggml_tensor * get_tensor_meta(int i) const {
  3595. return get_tensor_meta(get_tensor_name(i));
  3596. }
  3597. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  3598. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  3599. ggml_set_name(tensor, ggml_get_name(cur));
  3600. if (duplicated) {
  3601. size_data += ggml_nbytes(cur);
  3602. } else {
  3603. n_created++;
  3604. }
  3605. return tensor;
  3606. }
  3607. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  3608. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  3609. if (cur == NULL) {
  3610. if (!required) {
  3611. return NULL;
  3612. }
  3613. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  3614. }
  3615. {
  3616. bool is_ok = true;
  3617. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3618. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  3619. is_ok = false;
  3620. break;
  3621. }
  3622. }
  3623. if (!is_ok) {
  3624. throw std::runtime_error(
  3625. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  3626. __func__, name.c_str(),
  3627. llama_format_tensor_shape(ne).c_str(),
  3628. llama_format_tensor_shape(cur).c_str()));
  3629. }
  3630. }
  3631. return cur;
  3632. }
  3633. static const int TENSOR_NOT_REQUIRED = 1;
  3634. static const int TENSOR_DUPLICATED = 2;
  3635. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  3636. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  3637. if (cur == NULL) {
  3638. return NULL;
  3639. }
  3640. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  3641. }
  3642. 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) {
  3643. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3644. if (cur == NULL) {
  3645. return NULL;
  3646. }
  3647. if (cur->type != base->type) {
  3648. 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)));
  3649. }
  3650. std::array<int64_t, GGML_MAX_DIMS> dims;
  3651. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3652. dims[i] = i < ne.size() ? ne[i] : 1;
  3653. }
  3654. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  3655. dims[0], dims[1], dims[2], dims[3],
  3656. cur->nb[1], cur->nb[2], cur->nb[3],
  3657. offset);
  3658. ggml_set_name(tensor, name.c_str());
  3659. n_created++;
  3660. return tensor;
  3661. }
  3662. void done_getting_tensors() const {
  3663. if (n_created != n_tensors) {
  3664. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  3665. }
  3666. }
  3667. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  3668. if (use_mmap) {
  3669. mappings.reserve(files.size());
  3670. mmaps_used.reserve(files.size());
  3671. for (const auto & file : files) {
  3672. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  3673. mmaps_used.emplace_back(mapping->size, 0);
  3674. if (mlock_mmaps) {
  3675. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  3676. mlock_mmap->init(mapping->addr);
  3677. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  3678. }
  3679. mappings.emplace_back(std::move(mapping));
  3680. }
  3681. }
  3682. // compute the total size of all tensors for progress reporting
  3683. for (auto & w : weights) {
  3684. size_data += ggml_nbytes(w.tensor);
  3685. }
  3686. }
  3687. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  3688. GGML_ASSERT(!mappings.empty());
  3689. const auto & mapping = mappings.at(idx);
  3690. *first = mapping->size;
  3691. *last = 0;
  3692. *addr = mapping->addr;
  3693. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3694. try {
  3695. const auto * weight = get_weight(ggml_get_name(tensor));
  3696. if (!weight) {
  3697. continue;
  3698. }
  3699. if (weight->idx != idx) {
  3700. continue;
  3701. }
  3702. *first = std::min(*first, weight->offs);
  3703. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  3704. } catch(...) {
  3705. // the tensor is not in the model
  3706. }
  3707. }
  3708. }
  3709. // for backwards compatibility, does not support ggml-backend
  3710. void load_data_for(struct ggml_tensor * cur) const {
  3711. const auto & w = require_weight(ggml_get_name(cur));
  3712. if (use_mmap) {
  3713. const auto & mapping = mappings.at(w.idx);
  3714. if (cur->data == nullptr) {
  3715. cur->data = (uint8_t *)mapping->addr + w.offs;
  3716. } else {
  3717. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  3718. }
  3719. } else {
  3720. GGML_ASSERT(cur->data != nullptr);
  3721. GGML_ASSERT(w.idx < files.size());
  3722. const auto & file = files.at(w.idx);
  3723. file->seek(w.offs, SEEK_SET);
  3724. file->read_raw(cur->data, ggml_nbytes(cur));
  3725. }
  3726. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  3727. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3728. }
  3729. }
  3730. size_t size_done = 0;
  3731. size_t size_data = 0;
  3732. std::vector<std::pair<size_t, size_t>> mmaps_used;
  3733. // Returns false if cancelled by progress_callback
  3734. bool load_all_data(
  3735. struct ggml_context * ctx,
  3736. llama_buf_map & bufs_mmap,
  3737. llama_mlocks * lmlocks,
  3738. llama_progress_callback progress_callback,
  3739. void * progress_callback_user_data) {
  3740. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  3741. std::vector<no_init<uint8_t>> read_buf;
  3742. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  3743. #if defined(GGML_USE_CUDA)
  3744. // 4 staging buffers for async uploads, each sized 1MB seems to be a good default for single NVMe drives.
  3745. // NVMe raid configurations might require more / larger buffers.
  3746. constexpr size_t n_buffers = 4;
  3747. constexpr size_t buffer_size = 1 * 1024 * 1024; // 1MB
  3748. std::vector<ggml_backend_buffer_t> host_buffers;
  3749. std::vector<void*> host_ptrs;
  3750. std::vector<ggml_backend_event_t> events;
  3751. size_t buffer_idx = 0; // buffer to use for async loads
  3752. ggml_backend_t cuda_backend = nullptr;
  3753. if (!use_mmap && !check_tensors) {
  3754. // When not using mmaped io use async uploads from pinned memory to GPU memory.
  3755. // First determine if the CUDA backend is active, and if so, determine the device ID.
  3756. ggml_backend_buffer_t buf = bufs_mmap.count(0) ? bufs_mmap.at(0) : nullptr;
  3757. if (buf) {
  3758. ggml_backend_buffer_type_t buffer_type = ggml_backend_buffer_get_type(buf);
  3759. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  3760. auto * cuda_buffer_type = ggml_backend_cuda_buffer_type(i);
  3761. if (buffer_type == cuda_buffer_type) {
  3762. cuda_backend = ggml_backend_cuda_init(i);
  3763. break;
  3764. }
  3765. }
  3766. }
  3767. // If the cuda backend is active create pinned memory buffers and events for synchronisation.
  3768. if (cuda_backend) {
  3769. for (size_t idx = 0; idx < n_buffers; ++idx) {
  3770. host_buffers.emplace_back(ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buffer_size));
  3771. host_ptrs.emplace_back(ggml_backend_buffer_get_base(host_buffers[idx]));
  3772. events.emplace_back(ggml_backend_event_new(cuda_backend));
  3773. }
  3774. }
  3775. }
  3776. #endif
  3777. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3778. const auto * weight = get_weight(ggml_get_name(cur));
  3779. if (weight == nullptr) {
  3780. // this can happen with split experts models
  3781. continue;
  3782. }
  3783. if (progress_callback) {
  3784. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  3785. return false;
  3786. }
  3787. }
  3788. size_t n_size = ggml_nbytes(cur);
  3789. if (use_mmap) {
  3790. const auto & mapping = mappings.at(weight->idx);
  3791. ggml_backend_buffer_t buf_mmap = nullptr;
  3792. if (bufs_mmap.count(weight->idx)) {
  3793. buf_mmap = bufs_mmap.at(weight->idx);
  3794. }
  3795. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  3796. if (check_tensors) {
  3797. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  3798. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  3799. }));
  3800. }
  3801. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  3802. if (buf_mmap && cur->data == nullptr) {
  3803. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  3804. if (lmlocks) {
  3805. const auto & lmlock = lmlocks->at(weight->idx);
  3806. lmlock->grow_to(weight->offs + n_size);
  3807. }
  3808. auto & mmap_used = mmaps_used[weight->idx];
  3809. mmap_used.first = std::min(mmap_used.first, weight->offs);
  3810. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  3811. } else {
  3812. ggml_backend_tensor_set(cur, data, 0, n_size);
  3813. }
  3814. } else {
  3815. GGML_ASSERT(weight->idx < files.size());
  3816. const auto & file = files.at(weight->idx);
  3817. if (ggml_backend_buffer_is_host(cur->buffer)) {
  3818. file->seek(weight->offs, SEEK_SET);
  3819. file->read_raw(cur->data, n_size);
  3820. if (check_tensors) {
  3821. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  3822. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  3823. }));
  3824. }
  3825. } else {
  3826. #if defined(GGML_USE_CUDA)
  3827. // If cuda_backend is valid load the tensor in chunks to pinned memory and upload the buffers asynchronously to the GPU.
  3828. if (cuda_backend) {
  3829. file->seek(weight->offs, SEEK_SET);
  3830. size_t bytes_read = 0;
  3831. while (bytes_read < n_size) {
  3832. size_t read_iteration = std::min<size_t>(buffer_size, n_size - bytes_read);
  3833. ggml_backend_event_synchronize(events[buffer_idx]);
  3834. file->read_raw(host_ptrs[buffer_idx], read_iteration);
  3835. ggml_backend_tensor_set_async(cuda_backend, cur, host_ptrs[buffer_idx], bytes_read, read_iteration);
  3836. ggml_backend_event_record(events[buffer_idx]);
  3837. bytes_read += read_iteration;
  3838. ++buffer_idx;
  3839. buffer_idx %= n_buffers;
  3840. }
  3841. }
  3842. else
  3843. #endif
  3844. {
  3845. read_buf.resize(n_size);
  3846. file->seek(weight->offs, SEEK_SET);
  3847. file->read_raw(read_buf.data(), n_size);
  3848. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3849. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  3850. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3851. }
  3852. }
  3853. }
  3854. }
  3855. size_done += n_size;
  3856. }
  3857. #if defined(GGML_USE_CUDA)
  3858. // free temporary resources used for async cuda uploads
  3859. if (cuda_backend) {
  3860. for (size_t idx = 0; idx < n_buffers;++idx) {
  3861. ggml_backend_event_synchronize(events[idx]);
  3862. ggml_backend_event_free(events[idx]);
  3863. ggml_backend_buffer_free(host_buffers[idx]);
  3864. }
  3865. ggml_backend_free(cuda_backend);
  3866. }
  3867. #endif
  3868. // check validation results
  3869. bool validation_failed = false;
  3870. for (auto & future : validation_result) {
  3871. auto result = future.get();
  3872. if (!result.second) {
  3873. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  3874. validation_failed = true;
  3875. }
  3876. }
  3877. if (validation_failed) {
  3878. throw std::runtime_error("found tensors with invalid data");
  3879. }
  3880. // check if this is the last call and do final cleanup
  3881. if (size_done >= size_data) {
  3882. // unmap offloaded tensors and metadata
  3883. if (use_mmap) {
  3884. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3885. const auto & mmap_used = mmaps_used.at(idx);
  3886. auto & mapping = mappings.at(idx);
  3887. mapping->unmap_fragment(0, mmap_used.first);
  3888. if (mmap_used.second != 0) {
  3889. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3890. }
  3891. }
  3892. }
  3893. if (progress_callback) {
  3894. // Even though the model is done loading, we still honor
  3895. // cancellation since we need to free allocations.
  3896. return progress_callback(1.0f, progress_callback_user_data);
  3897. }
  3898. }
  3899. return true;
  3900. }
  3901. };
  3902. template<>
  3903. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3904. uint32_t tmp;
  3905. const bool found = get_key(kid, tmp, required);
  3906. if (found) {
  3907. result = (enum llama_pooling_type) tmp;
  3908. } else {
  3909. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3910. }
  3911. return found;
  3912. }
  3913. //
  3914. // load LLaMA models
  3915. //
  3916. static const char * llama_model_arch_name(llm_arch arch) {
  3917. auto it = LLM_ARCH_NAMES.find(arch);
  3918. if (it == LLM_ARCH_NAMES.end()) {
  3919. return "unknown";
  3920. }
  3921. return it->second;
  3922. }
  3923. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3924. if (ftype & LLAMA_FTYPE_GUESSED) {
  3925. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3926. }
  3927. switch (ftype) {
  3928. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3929. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3930. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  3931. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3932. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3933. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3934. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3935. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3936. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3937. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3938. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3939. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3940. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3941. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3942. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3943. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3944. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3945. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3946. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return "IQ2_XXS - 2.0625 bpw";
  3947. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3948. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3949. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3950. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3951. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return "IQ3_XXS - 3.0625 bpw";
  3952. case LLAMA_FTYPE_MOSTLY_IQ1_S: return "IQ1_S - 1.5625 bpw";
  3953. case LLAMA_FTYPE_MOSTLY_IQ1_M: return "IQ1_M - 1.75 bpw";
  3954. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3955. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3956. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3957. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3958. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: return "Q4_0_4_4";
  3959. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: return "Q4_0_4_8";
  3960. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: return "Q4_0_8_8";
  3961. default: return "unknown, may not work";
  3962. }
  3963. }
  3964. static const char * llama_model_type_name(e_model type) {
  3965. switch (type) {
  3966. case MODEL_14M: return "14M";
  3967. case MODEL_17M: return "17M";
  3968. case MODEL_22M: return "22M";
  3969. case MODEL_33M: return "33M";
  3970. case MODEL_60M: return "60M";
  3971. case MODEL_70M: return "70M";
  3972. case MODEL_80M: return "80M";
  3973. case MODEL_109M: return "109M";
  3974. case MODEL_137M: return "137M";
  3975. case MODEL_160M: return "160M";
  3976. case MODEL_220M: return "220M";
  3977. case MODEL_250M: return "250M";
  3978. case MODEL_270M: return "270M";
  3979. case MODEL_335M: return "335M";
  3980. case MODEL_410M: return "410M";
  3981. case MODEL_450M: return "450M";
  3982. case MODEL_770M: return "770M";
  3983. case MODEL_780M: return "780M";
  3984. case MODEL_0_5B: return "0.5B";
  3985. case MODEL_1B: return "1B";
  3986. case MODEL_1_3B: return "1.3B";
  3987. case MODEL_1_4B: return "1.4B";
  3988. case MODEL_2B: return "2B";
  3989. case MODEL_2_8B: return "2.8B";
  3990. case MODEL_3B: return "3B";
  3991. case MODEL_4B: return "4B";
  3992. case MODEL_6B: return "6B";
  3993. case MODEL_6_9B: return "6.9B";
  3994. case MODEL_7B: return "7B";
  3995. case MODEL_8B: return "8B";
  3996. case MODEL_9B: return "9B";
  3997. case MODEL_11B: return "11B";
  3998. case MODEL_12B: return "12B";
  3999. case MODEL_13B: return "13B";
  4000. case MODEL_14B: return "14B";
  4001. case MODEL_15B: return "15B";
  4002. case MODEL_16B: return "16B";
  4003. case MODEL_20B: return "20B";
  4004. case MODEL_30B: return "30B";
  4005. case MODEL_34B: return "34B";
  4006. case MODEL_35B: return "35B";
  4007. case MODEL_40B: return "40B";
  4008. case MODEL_65B: return "65B";
  4009. case MODEL_70B: return "70B";
  4010. case MODEL_236B: return "236B";
  4011. case MODEL_314B: return "314B";
  4012. case MODEL_SMALL: return "0.1B";
  4013. case MODEL_MEDIUM: return "0.4B";
  4014. case MODEL_LARGE: return "0.8B";
  4015. case MODEL_XL: return "1.5B";
  4016. case MODEL_A2_7B: return "A2.7B";
  4017. case MODEL_8x7B: return "8x7B";
  4018. case MODEL_8x22B: return "8x22B";
  4019. case MODEL_16x12B: return "16x12B";
  4020. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  4021. case MODEL_57B_A14B: return "57B.A14B";
  4022. case MODEL_27B: return "27B";
  4023. default: return "?B";
  4024. }
  4025. }
  4026. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  4027. switch (type) {
  4028. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  4029. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  4030. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  4031. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  4032. case LLAMA_VOCAB_TYPE_UGM: return "UGM";
  4033. default: return "unknown";
  4034. }
  4035. }
  4036. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  4037. model.arch = ml.get_arch();
  4038. if (model.arch == LLM_ARCH_UNKNOWN) {
  4039. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  4040. }
  4041. }
  4042. static void llm_load_hparams(
  4043. llama_model_loader & ml,
  4044. llama_model & model) {
  4045. auto & hparams = model.hparams;
  4046. const gguf_context * ctx = ml.meta;
  4047. // get metadata as string
  4048. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  4049. enum gguf_type type = gguf_get_kv_type(ctx, i);
  4050. if (type == GGUF_TYPE_ARRAY) {
  4051. continue;
  4052. }
  4053. const char * name = gguf_get_key(ctx, i);
  4054. const std::string value = gguf_kv_to_str(ctx, i);
  4055. model.gguf_kv.emplace(name, value);
  4056. }
  4057. // get general kv
  4058. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  4059. // get hparams kv
  4060. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  4061. // everything past this point is not vocab-related
  4062. if (hparams.vocab_only) {
  4063. return;
  4064. }
  4065. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  4066. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  4067. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  4068. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  4069. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  4070. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  4071. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  4072. if (hparams.n_expert > 0) {
  4073. GGML_ASSERT(hparams.n_expert_used > 0);
  4074. } else {
  4075. GGML_ASSERT(hparams.n_expert_used == 0);
  4076. }
  4077. // zero-out the per-layer hparams
  4078. std::fill(hparams.n_head_arr.begin(), hparams.n_head_arr.end(), 0);
  4079. std::fill(hparams.n_head_kv_arr.begin(), hparams.n_head_kv_arr.end(), 0);
  4080. std::fill(hparams.n_ff_arr.begin(), hparams.n_ff_arr.end(), 0);
  4081. ml.get_key_or_arr(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff_arr, hparams.n_layer);
  4082. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head_arr, hparams.n_layer);
  4083. // n_head_kv is optional, default to n_head
  4084. hparams.n_head_kv_arr = hparams.n_head_arr;
  4085. ml.get_key_or_arr(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv_arr, hparams.n_layer, false);
  4086. bool rope_finetuned = false;
  4087. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  4088. hparams.rope_finetuned = rope_finetuned;
  4089. hparams.n_ctx_orig_yarn = hparams.n_ctx_train;
  4090. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_ctx_orig_yarn, false);
  4091. // rope_freq_base (optional)
  4092. hparams.rope_freq_base_train = 10000.0f;
  4093. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  4094. std::string rope_scaling("linear");
  4095. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  4096. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  4097. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  4098. // rope_freq_scale (inverse of the kv) is optional
  4099. float ropescale = 0.0f;
  4100. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  4101. // try the old key name
  4102. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  4103. }
  4104. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  4105. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  4106. // non-transformer models do not have attention heads
  4107. if (hparams.n_head() > 0) {
  4108. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  4109. // gpt-j n_rot = rotary_dim
  4110. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head();
  4111. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  4112. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head();
  4113. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  4114. // sanity check for n_rot (optional)
  4115. hparams.n_rot = hparams.n_embd_head_k;
  4116. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  4117. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  4118. if (hparams.n_rot != hparams.n_embd_head_k) {
  4119. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd_head_k));
  4120. }
  4121. }
  4122. } else {
  4123. hparams.n_rot = 0;
  4124. hparams.n_embd_head_k = 0;
  4125. hparams.n_embd_head_v = 0;
  4126. }
  4127. // arch-specific KVs
  4128. switch (model.arch) {
  4129. case LLM_ARCH_LLAMA:
  4130. {
  4131. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4132. if (hparams.n_expert == 8) {
  4133. switch (hparams.n_layer) {
  4134. case 32: model.type = e_model::MODEL_8x7B; break;
  4135. case 56: model.type = e_model::MODEL_8x22B; break;
  4136. default: model.type = e_model::MODEL_UNKNOWN;
  4137. }
  4138. } else {
  4139. switch (hparams.n_layer) {
  4140. case 22: model.type = e_model::MODEL_1B; break;
  4141. case 26: model.type = e_model::MODEL_3B; break;
  4142. // granite uses a vocab with len 49152
  4143. 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;
  4144. case 36: model.type = e_model::MODEL_8B; break; // granite
  4145. case 40: model.type = e_model::MODEL_13B; break;
  4146. case 48: model.type = e_model::MODEL_34B; break;
  4147. case 60: model.type = e_model::MODEL_30B; break;
  4148. case 80: model.type = hparams.n_head() == hparams.n_head_kv() ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  4149. default: model.type = e_model::MODEL_UNKNOWN;
  4150. }
  4151. }
  4152. } break;
  4153. case LLM_ARCH_MINICPM:
  4154. {
  4155. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4156. switch (hparams.n_layer) {
  4157. case 40: model.type = e_model::MODEL_2B; break;
  4158. default: model.type = e_model::MODEL_UNKNOWN;
  4159. }
  4160. } break;
  4161. case LLM_ARCH_GROK:
  4162. {
  4163. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4164. switch (hparams.n_layer) {
  4165. case 64: model.type = e_model::MODEL_314B; break;
  4166. default: model.type = e_model::MODEL_UNKNOWN;
  4167. }
  4168. } break;
  4169. case LLM_ARCH_FALCON:
  4170. {
  4171. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4172. switch (hparams.n_layer) {
  4173. case 32: model.type = e_model::MODEL_7B; break;
  4174. case 60: model.type = e_model::MODEL_40B; break;
  4175. default: model.type = e_model::MODEL_UNKNOWN;
  4176. }
  4177. } break;
  4178. case LLM_ARCH_BAICHUAN:
  4179. {
  4180. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4181. switch (hparams.n_layer) {
  4182. case 32: model.type = e_model::MODEL_7B; break;
  4183. case 40: model.type = e_model::MODEL_13B; break;
  4184. default: model.type = e_model::MODEL_UNKNOWN;
  4185. }
  4186. if (model.type == e_model::MODEL_13B) {
  4187. // TODO: become GGUF KV parameter
  4188. hparams.f_max_alibi_bias = 8.0f;
  4189. }
  4190. } break;
  4191. case LLM_ARCH_STARCODER:
  4192. {
  4193. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4194. switch (hparams.n_layer) {
  4195. case 24: model.type = e_model::MODEL_1B; break;
  4196. case 36: model.type = e_model::MODEL_3B; break;
  4197. case 42: model.type = e_model::MODEL_7B; break;
  4198. case 40: model.type = e_model::MODEL_15B; break;
  4199. default: model.type = e_model::MODEL_UNKNOWN;
  4200. }
  4201. } break;
  4202. case LLM_ARCH_REFACT:
  4203. {
  4204. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4205. switch (hparams.n_layer) {
  4206. case 32: model.type = e_model::MODEL_1B; break;
  4207. default: model.type = e_model::MODEL_UNKNOWN;
  4208. }
  4209. // TODO: become GGUF KV parameter
  4210. hparams.f_max_alibi_bias = 8.0f;
  4211. } break;
  4212. case LLM_ARCH_BERT:
  4213. {
  4214. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4215. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4216. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4217. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  4218. switch (hparams.n_layer) {
  4219. case 3:
  4220. model.type = e_model::MODEL_17M; break; // bge-micro
  4221. case 6:
  4222. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  4223. case 12:
  4224. switch (hparams.n_embd) {
  4225. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  4226. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  4227. } break;
  4228. case 24:
  4229. model.type = e_model::MODEL_335M; break; // bge-large
  4230. }
  4231. } break;
  4232. case LLM_ARCH_JINA_BERT_V2:
  4233. {
  4234. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4235. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4236. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4237. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4238. hparams.f_max_alibi_bias = 8.0f;
  4239. switch (hparams.n_layer) {
  4240. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  4241. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  4242. }
  4243. } break;
  4244. case LLM_ARCH_NOMIC_BERT:
  4245. {
  4246. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4247. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  4248. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  4249. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  4250. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  4251. model.type = e_model::MODEL_137M;
  4252. }
  4253. } break;
  4254. case LLM_ARCH_BLOOM:
  4255. {
  4256. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4257. switch (hparams.n_layer) {
  4258. case 24: model.type = e_model::MODEL_1B; break;
  4259. case 30:
  4260. switch (hparams.n_embd) {
  4261. case 2560: model.type = e_model::MODEL_3B; break;
  4262. case 4096: model.type = e_model::MODEL_7B; break;
  4263. } break;
  4264. }
  4265. // TODO: become GGUF KV parameter
  4266. hparams.f_max_alibi_bias = 8.0f;
  4267. } break;
  4268. case LLM_ARCH_MPT:
  4269. {
  4270. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4271. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4272. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4273. switch (hparams.n_layer) {
  4274. case 32: model.type = e_model::MODEL_7B; break;
  4275. case 48: model.type = e_model::MODEL_30B; break;
  4276. default: model.type = e_model::MODEL_UNKNOWN;
  4277. }
  4278. } break;
  4279. case LLM_ARCH_STABLELM:
  4280. {
  4281. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4282. switch (hparams.n_layer) {
  4283. case 24: model.type = e_model::MODEL_1B; break;
  4284. case 32: model.type = e_model::MODEL_3B; break;
  4285. case 40: model.type = e_model::MODEL_12B; break;
  4286. default: model.type = e_model::MODEL_UNKNOWN;
  4287. }
  4288. } break;
  4289. case LLM_ARCH_QWEN:
  4290. {
  4291. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4292. switch (hparams.n_layer) {
  4293. case 32: model.type = e_model::MODEL_7B; break;
  4294. case 40: model.type = e_model::MODEL_13B; break;
  4295. default: model.type = e_model::MODEL_UNKNOWN;
  4296. }
  4297. } break;
  4298. case LLM_ARCH_QWEN2:
  4299. {
  4300. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4301. switch (hparams.n_layer) {
  4302. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  4303. case 32: model.type = e_model::MODEL_7B; break;
  4304. case 40: model.type = hparams.n_head() == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  4305. case 80: model.type = e_model::MODEL_70B; break;
  4306. default: model.type = e_model::MODEL_UNKNOWN;
  4307. }
  4308. } break;
  4309. case LLM_ARCH_QWEN2MOE:
  4310. {
  4311. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);
  4312. ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp, false);
  4313. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4314. switch (hparams.n_layer) {
  4315. case 24: model.type = e_model::MODEL_A2_7B; break;
  4316. case 28: model.type = e_model::MODEL_57B_A14B; break;
  4317. default: model.type = e_model::MODEL_UNKNOWN;
  4318. }
  4319. } break;
  4320. case LLM_ARCH_PHI2:
  4321. {
  4322. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4323. switch (hparams.n_layer) {
  4324. case 24: model.type = e_model::MODEL_1B; break;
  4325. case 32: model.type = e_model::MODEL_3B; break;
  4326. default: model.type = e_model::MODEL_UNKNOWN;
  4327. }
  4328. } break;
  4329. case LLM_ARCH_PHI3:
  4330. {
  4331. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);
  4332. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4333. switch (hparams.n_layer) {
  4334. case 24: model.type = e_model::MODEL_1B; break;
  4335. case 32: model.type = e_model::MODEL_3B; break;
  4336. case 40: model.type = e_model::MODEL_14B; break;
  4337. default: model.type = e_model::MODEL_UNKNOWN;
  4338. }
  4339. } break;
  4340. case LLM_ARCH_PLAMO:
  4341. {
  4342. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4343. switch (hparams.n_layer) {
  4344. case 40: model.type = e_model::MODEL_13B; break;
  4345. default: model.type = e_model::MODEL_UNKNOWN;
  4346. }
  4347. } break;
  4348. case LLM_ARCH_GPT2:
  4349. {
  4350. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4351. switch (hparams.n_layer) {
  4352. case 12: model.type = e_model::MODEL_SMALL; break;
  4353. case 24: model.type = e_model::MODEL_MEDIUM; break;
  4354. case 36: model.type = e_model::MODEL_LARGE; break;
  4355. case 48: model.type = e_model::MODEL_XL; break;
  4356. default: model.type = e_model::MODEL_UNKNOWN;
  4357. }
  4358. } break;
  4359. case LLM_ARCH_CODESHELL:
  4360. {
  4361. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4362. switch (hparams.n_layer) {
  4363. case 42: model.type = e_model::MODEL_7B; break;
  4364. default: model.type = e_model::MODEL_UNKNOWN;
  4365. }
  4366. } break;
  4367. case LLM_ARCH_ORION:
  4368. {
  4369. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4370. switch (hparams.n_layer) {
  4371. case 40: model.type = e_model::MODEL_14B; break;
  4372. default: model.type = e_model::MODEL_UNKNOWN;
  4373. }
  4374. } break;
  4375. case LLM_ARCH_INTERNLM2:
  4376. {
  4377. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4378. switch (hparams.n_layer) {
  4379. case 32: model.type = e_model::MODEL_7B; break;
  4380. case 48: model.type = e_model::MODEL_20B; break;
  4381. default: model.type = e_model::MODEL_UNKNOWN;
  4382. }
  4383. } break;
  4384. case LLM_ARCH_GEMMA:
  4385. {
  4386. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4387. switch (hparams.n_layer) {
  4388. case 18: model.type = e_model::MODEL_2B; break;
  4389. case 28: model.type = e_model::MODEL_7B; break;
  4390. default: model.type = e_model::MODEL_UNKNOWN;
  4391. }
  4392. } break;
  4393. case LLM_ARCH_GEMMA2:
  4394. {
  4395. hparams.n_swa = 4096; // default value of gemma 2
  4396. ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false);
  4397. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4398. ml.get_key(LLM_KV_ATTN_LOGIT_SOFTCAPPING, hparams.f_attn_logit_softcapping, false);
  4399. ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);
  4400. hparams.attn_soft_cap = true;
  4401. switch (hparams.n_layer) {
  4402. case 42: model.type = e_model::MODEL_9B; break;
  4403. case 46: model.type = e_model::MODEL_27B; break;
  4404. default: model.type = e_model::MODEL_UNKNOWN;
  4405. }
  4406. } break;
  4407. case LLM_ARCH_STARCODER2:
  4408. {
  4409. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4410. switch (hparams.n_layer) {
  4411. case 30: model.type = e_model::MODEL_3B; break;
  4412. case 32: model.type = e_model::MODEL_7B; break;
  4413. case 40: model.type = e_model::MODEL_15B; break;
  4414. case 52: model.type = e_model::MODEL_20B; break; // granite
  4415. case 88: model.type = e_model::MODEL_34B; break; // granite
  4416. default: model.type = e_model::MODEL_UNKNOWN;
  4417. }
  4418. } break;
  4419. case LLM_ARCH_MAMBA:
  4420. {
  4421. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  4422. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  4423. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  4424. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  4425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4426. switch (hparams.n_layer) {
  4427. case 24:
  4428. switch (hparams.n_embd) {
  4429. case 768: model.type = e_model::MODEL_SMALL; break;
  4430. default: model.type = e_model::MODEL_UNKNOWN;
  4431. } break;
  4432. case 48:
  4433. switch (hparams.n_embd) {
  4434. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  4435. case 1536: model.type = e_model::MODEL_LARGE; break;
  4436. case 2048: model.type = e_model::MODEL_XL; break;
  4437. default: model.type = e_model::MODEL_UNKNOWN;
  4438. } break;
  4439. case 64:
  4440. switch (hparams.n_embd) {
  4441. case 2560: model.type = e_model::MODEL_3B; break;
  4442. default: model.type = e_model::MODEL_UNKNOWN;
  4443. } break;
  4444. default: model.type = e_model::MODEL_UNKNOWN;
  4445. }
  4446. } break;
  4447. case LLM_ARCH_XVERSE:
  4448. {
  4449. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4450. switch (hparams.n_layer) {
  4451. case 32: model.type = e_model::MODEL_7B; break;
  4452. case 40: model.type = e_model::MODEL_13B; break;
  4453. case 80: model.type = e_model::MODEL_65B; break;
  4454. default: model.type = e_model::MODEL_UNKNOWN;
  4455. }
  4456. } break;
  4457. case LLM_ARCH_COMMAND_R:
  4458. {
  4459. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  4460. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4461. switch (hparams.n_layer) {
  4462. case 40: model.type = e_model::MODEL_35B; break;
  4463. default: model.type = e_model::MODEL_UNKNOWN;
  4464. }
  4465. } break;
  4466. case LLM_ARCH_DBRX:
  4467. {
  4468. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4469. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  4470. switch (hparams.n_layer) {
  4471. case 40: model.type = e_model::MODEL_16x12B; break;
  4472. default: model.type = e_model::MODEL_UNKNOWN;
  4473. }
  4474. } break;
  4475. case LLM_ARCH_OLMO:
  4476. {
  4477. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4478. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  4479. switch (hparams.n_layer) {
  4480. case 22: model.type = e_model::MODEL_1B; break;
  4481. case 32: model.type = e_model::MODEL_7B; break;
  4482. case 80: model.type = e_model::MODEL_70B; break;
  4483. default: model.type = e_model::MODEL_UNKNOWN;
  4484. }
  4485. } break;
  4486. case LLM_ARCH_OPENELM:
  4487. {
  4488. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4489. switch (hparams.n_layer) {
  4490. case 16: model.type = e_model::MODEL_270M; break;
  4491. case 20: model.type = e_model::MODEL_450M; break;
  4492. case 28: model.type = e_model::MODEL_1B; break;
  4493. case 36: model.type = e_model::MODEL_3B; break;
  4494. default: model.type = e_model::MODEL_UNKNOWN;
  4495. }
  4496. } break;
  4497. case LLM_ARCH_GPTNEOX:
  4498. {
  4499. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4500. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  4501. switch (hparams.n_layer) {
  4502. case 6:
  4503. switch (hparams.n_ff()) {
  4504. case 512: model.type = e_model::MODEL_14M; break;
  4505. case 2048: model.type = e_model::MODEL_70M; break;
  4506. default: model.type = e_model::MODEL_UNKNOWN;
  4507. } break;
  4508. case 12:
  4509. switch (hparams.n_ff()) {
  4510. case 3072: model.type = e_model::MODEL_160M; break;
  4511. default: model.type = e_model::MODEL_UNKNOWN;
  4512. } break;
  4513. case 16:
  4514. switch (hparams.n_ff()) {
  4515. case 8192: model.type = e_model::MODEL_1B; break;
  4516. default: model.type = e_model::MODEL_UNKNOWN;
  4517. } break;
  4518. case 24:
  4519. switch (hparams.n_ff()) {
  4520. case 4096: model.type = e_model::MODEL_410M; break;
  4521. case 8192: model.type = e_model::MODEL_1_4B; break;
  4522. default: model.type = e_model::MODEL_UNKNOWN;
  4523. } break;
  4524. case 32:
  4525. switch (hparams.n_ff()) {
  4526. case 10240: model.type = e_model::MODEL_2_8B; break;
  4527. case 16384: model.type = e_model::MODEL_6_9B; break;
  4528. default: model.type = e_model::MODEL_UNKNOWN;
  4529. } break;
  4530. case 36:
  4531. switch (hparams.n_ff()) {
  4532. case 20480: model.type = e_model::MODEL_12B; break;
  4533. default: model.type = e_model::MODEL_UNKNOWN;
  4534. } break;
  4535. case 44:
  4536. switch (hparams.n_ff()) {
  4537. case 24576: model.type = e_model::MODEL_20B; break;
  4538. default: model.type = e_model::MODEL_UNKNOWN;
  4539. } break;
  4540. default: model.type = e_model::MODEL_UNKNOWN;
  4541. }
  4542. } break;
  4543. case LLM_ARCH_ARCTIC:
  4544. {
  4545. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4546. if (hparams.n_expert == 128) {
  4547. switch (hparams.n_layer) {
  4548. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  4549. default: model.type = e_model::MODEL_UNKNOWN;
  4550. }
  4551. } else {
  4552. model.type = e_model::MODEL_UNKNOWN;
  4553. }
  4554. } break;
  4555. case LLM_ARCH_DEEPSEEK2:
  4556. {
  4557. bool is_lite = (hparams.n_layer == 27);
  4558. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4559. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  4560. if (!is_lite) {
  4561. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  4562. }
  4563. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  4564. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  4565. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  4566. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  4567. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  4568. switch (hparams.n_layer) {
  4569. case 27: model.type = e_model::MODEL_16B; break;
  4570. case 60: model.type = e_model::MODEL_236B; break;
  4571. default: model.type = e_model::MODEL_UNKNOWN;
  4572. }
  4573. } break;
  4574. case LLM_ARCH_CHATGLM:
  4575. {
  4576. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4577. switch (hparams.n_layer) {
  4578. case 28: model.type = e_model::MODEL_6B; break;
  4579. case 40: model.type = e_model::MODEL_9B; break;
  4580. default: model.type = e_model::MODEL_UNKNOWN;
  4581. }
  4582. } break;
  4583. case LLM_ARCH_BITNET:
  4584. {
  4585. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4586. switch (hparams.n_layer) {
  4587. case 26: model.type = e_model::MODEL_3B; break;
  4588. default: model.type = e_model::MODEL_UNKNOWN;
  4589. }
  4590. } break;
  4591. case LLM_ARCH_T5:
  4592. {
  4593. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  4594. ml.get_key(LLM_KV_ATTENTION_RELATIVE_BUCKETS_COUNT, hparams.n_rel_attn_bkts);
  4595. uint32_t dec_start_token_id;
  4596. if (ml.get_key(LLM_KV_DECODER_START_TOKEN_ID, dec_start_token_id, false)) {
  4597. hparams.dec_start_token_id = dec_start_token_id;
  4598. }
  4599. switch (hparams.n_layer) {
  4600. case 6: model.type = e_model::MODEL_60M; break; // t5-small
  4601. case 8: model.type = e_model::MODEL_80M; break; // flan-t5-small
  4602. case 12:
  4603. switch (hparams.n_ff()) {
  4604. case 3072: model.type = e_model::MODEL_220M; break; // t5-base
  4605. case 2048: model.type = e_model::MODEL_250M; break; // flan-t5-base
  4606. default: model.type = e_model::MODEL_UNKNOWN;
  4607. } break;
  4608. case 24:
  4609. switch (hparams.n_ff()) {
  4610. case 4096: model.type = e_model::MODEL_770M; break; // t5-large
  4611. case 2816: model.type = e_model::MODEL_780M; break; // flan-t5-large
  4612. case 16384: model.type = e_model::MODEL_3B; break; // t5-3b
  4613. case 5120: model.type = e_model::MODEL_3B; break; // flan-t5-xl
  4614. case 65536: model.type = e_model::MODEL_11B; break; // t5-11b
  4615. case 10240: model.type = e_model::MODEL_11B; break; // flan-t5-xxl
  4616. default: model.type = e_model::MODEL_UNKNOWN;
  4617. } break;
  4618. default: model.type = e_model::MODEL_UNKNOWN;
  4619. }
  4620. } break;
  4621. case LLM_ARCH_JAIS:
  4622. {
  4623. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  4624. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  4625. switch (hparams.n_layer) {
  4626. case 24: model.type = e_model::MODEL_1_3B; break;
  4627. case 40: model.type = e_model::MODEL_13B; break;
  4628. /* TODO: add variants */
  4629. default: model.type = e_model::MODEL_UNKNOWN;
  4630. }
  4631. } break;
  4632. default: (void)0;
  4633. }
  4634. model.ftype = ml.ftype;
  4635. if (hparams.f_max_alibi_bias > 0.0f) {
  4636. hparams.use_alibi = true;
  4637. }
  4638. hparams.rope_type = llama_rope_type(&model);
  4639. }
  4640. static void llm_load_vocab(
  4641. llama_model_loader & ml,
  4642. llama_model & model) {
  4643. auto & vocab = model.vocab;
  4644. struct gguf_context * ctx = ml.meta;
  4645. const auto kv = LLM_KV(model.arch);
  4646. // determine vocab type
  4647. {
  4648. std::string tokenizer_model;
  4649. std::string tokenizer_pre;
  4650. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  4651. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  4652. if (tokenizer_model == "no_vocab") {
  4653. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  4654. // default special tokens
  4655. vocab.special_bos_id = -1;
  4656. vocab.special_eos_id = -1;
  4657. vocab.special_unk_id = -1;
  4658. vocab.special_sep_id = -1;
  4659. vocab.special_pad_id = -1;
  4660. vocab.special_cls_id = -1;
  4661. vocab.special_mask_id = -1;
  4662. vocab.linefeed_id = -1;
  4663. return;
  4664. } else if (tokenizer_model == "llama") {
  4665. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  4666. // default special tokens
  4667. vocab.special_bos_id = 1;
  4668. vocab.special_eos_id = 2;
  4669. vocab.special_unk_id = 0;
  4670. vocab.special_sep_id = -1;
  4671. vocab.special_pad_id = -1;
  4672. vocab.special_cls_id = -1;
  4673. vocab.special_mask_id = -1;
  4674. } else if (tokenizer_model == "bert") {
  4675. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  4676. // default special tokens
  4677. vocab.special_bos_id = -1;
  4678. vocab.special_eos_id = -1;
  4679. vocab.special_unk_id = 100;
  4680. vocab.special_sep_id = 102;
  4681. vocab.special_pad_id = 0;
  4682. vocab.special_cls_id = 101;
  4683. vocab.special_mask_id = 103;
  4684. } else if (tokenizer_model == "gpt2") {
  4685. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  4686. // read bpe merges and populate bpe ranks
  4687. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  4688. if (merges_keyidx == -1) {
  4689. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  4690. }
  4691. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  4692. for (int i = 0; i < n_merges; i++) {
  4693. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  4694. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4695. std::string first;
  4696. std::string second;
  4697. const size_t pos = word.find(' ', 1);
  4698. if (pos != std::string::npos) {
  4699. first = word.substr(0, pos);
  4700. second = word.substr(pos + 1);
  4701. }
  4702. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  4703. }
  4704. // default special tokens
  4705. vocab.special_bos_id = 11;
  4706. vocab.special_eos_id = 11;
  4707. vocab.special_unk_id = -1;
  4708. vocab.special_sep_id = -1;
  4709. vocab.special_pad_id = -1;
  4710. vocab.special_cls_id = -1;
  4711. vocab.special_mask_id = -1;
  4712. } else if (tokenizer_model == "t5") {
  4713. vocab.type = LLAMA_VOCAB_TYPE_UGM;
  4714. // default special tokens
  4715. vocab.special_bos_id = -1;
  4716. vocab.special_eos_id = 1;
  4717. vocab.special_unk_id = 2;
  4718. vocab.special_sep_id = -1;
  4719. vocab.special_pad_id = 0;
  4720. vocab.special_cls_id = -1;
  4721. vocab.special_mask_id = -1;
  4722. const int precompiled_charsmap_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP).c_str());
  4723. if (precompiled_charsmap_keyidx != -1) {
  4724. size_t n_precompiled_charsmap = gguf_get_arr_n(ctx, precompiled_charsmap_keyidx);
  4725. const char * precompiled_charsmap = (const char *) gguf_get_arr_data(ctx, precompiled_charsmap_keyidx);
  4726. vocab.precompiled_charsmap.assign(precompiled_charsmap, precompiled_charsmap + n_precompiled_charsmap);
  4727. #ifdef IS_BIG_ENDIAN
  4728. // correct endiannes of data in precompiled_charsmap binary blob
  4729. uint32_t * xcda_blob_size = (uint32_t *) &vocab.precompiled_charsmap[0];
  4730. *xcda_blob_size = __builtin_bswap32(*xcda_blob_size);
  4731. assert(*xcda_blob_size + sizeof(uint32_t) < n_precompiled_charsmap);
  4732. size_t xcda_array_size = *xcda_blob_size / sizeof(uint32_t);
  4733. uint32_t * xcda_array = (uint32_t *) &vocab.precompiled_charsmap[sizeof(uint32_t)];
  4734. for (size_t i = 0; i < xcda_array_size; ++i) {
  4735. xcda_array[i] = __builtin_bswap32(xcda_array[i]);
  4736. }
  4737. #endif
  4738. }
  4739. } else {
  4740. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  4741. }
  4742. // for now, only BPE models have pre-tokenizers
  4743. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  4744. vocab.tokenizer_add_space_prefix = false;
  4745. vocab.tokenizer_clean_spaces = true;
  4746. if (tokenizer_pre == "default") {
  4747. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4748. } else if (
  4749. tokenizer_pre == "llama3" ||
  4750. tokenizer_pre == "llama-v3" ||
  4751. tokenizer_pre == "llama-bpe") {
  4752. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  4753. vocab.tokenizer_ignore_merges = true;
  4754. vocab.tokenizer_add_bos = true;
  4755. } else if (
  4756. tokenizer_pre == "deepseek-llm") {
  4757. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  4758. vocab.tokenizer_clean_spaces = false;
  4759. } else if (
  4760. tokenizer_pre == "deepseek-coder") {
  4761. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  4762. vocab.tokenizer_clean_spaces = false;
  4763. } else if (
  4764. tokenizer_pre == "falcon") {
  4765. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  4766. } else if (
  4767. tokenizer_pre == "mpt") {
  4768. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  4769. } else if (
  4770. tokenizer_pre == "starcoder") {
  4771. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  4772. } else if (
  4773. tokenizer_pre == "gpt-2" ||
  4774. tokenizer_pre == "phi-2" ||
  4775. tokenizer_pre == "jina-es" ||
  4776. tokenizer_pre == "jina-de" ||
  4777. tokenizer_pre == "jina-v2-es" ||
  4778. tokenizer_pre == "jina-v2-de" ||
  4779. tokenizer_pre == "jina-v2-code") {
  4780. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  4781. } else if (
  4782. tokenizer_pre == "refact") {
  4783. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  4784. } else if (
  4785. tokenizer_pre == "command-r") {
  4786. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  4787. vocab.tokenizer_clean_spaces = false;
  4788. } else if (
  4789. tokenizer_pre == "qwen2") {
  4790. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  4791. vocab.tokenizer_clean_spaces = false;
  4792. } else if (
  4793. tokenizer_pre == "stablelm2") {
  4794. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  4795. } else if (
  4796. tokenizer_pre == "olmo") {
  4797. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  4798. } else if (
  4799. tokenizer_pre == "dbrx") {
  4800. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  4801. } else if (
  4802. tokenizer_pre == "smaug-bpe") {
  4803. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  4804. } else if (
  4805. tokenizer_pre == "poro-chat") {
  4806. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_PORO;
  4807. vocab.tokenizer_clean_spaces = false;
  4808. } else if (
  4809. tokenizer_pre == "chatglm-bpe") {
  4810. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CHATGLM4;
  4811. vocab.special_bos_id = -1;
  4812. } else if (
  4813. tokenizer_pre == "viking") {
  4814. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_VIKING;
  4815. vocab.tokenizer_clean_spaces = false;
  4816. } else if (
  4817. tokenizer_pre == "jais") {
  4818. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_JAIS;
  4819. } else if (
  4820. tokenizer_pre == "tekken") {
  4821. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_TEKKEN;
  4822. vocab.tokenizer_clean_spaces = false;
  4823. vocab.tokenizer_ignore_merges = true;
  4824. vocab.tokenizer_add_bos = true;
  4825. } else if (
  4826. tokenizer_pre == "smollm") {
  4827. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMOLLM;
  4828. vocab.tokenizer_clean_spaces = false;
  4829. } else if (
  4830. tokenizer_pre == "codeshell") {
  4831. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_CODESHELL;
  4832. } else {
  4833. LLAMA_LOG_WARN("%s: missing or unrecognized pre-tokenizer type, using: 'default'\n", __func__);
  4834. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4835. }
  4836. } else if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4837. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4838. vocab.tokenizer_add_space_prefix = true;
  4839. vocab.tokenizer_clean_spaces = false;
  4840. vocab.tokenizer_add_bos = true;
  4841. vocab.tokenizer_add_eos = false;
  4842. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4843. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4844. vocab.tokenizer_add_space_prefix = false;
  4845. vocab.tokenizer_clean_spaces = true;
  4846. vocab.tokenizer_add_bos = true;
  4847. vocab.tokenizer_add_eos = false;
  4848. } else if (vocab.type == LLAMA_VOCAB_TYPE_UGM) {
  4849. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4850. vocab.tokenizer_add_bos = false;
  4851. vocab.tokenizer_add_eos = true;
  4852. } else {
  4853. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4854. }
  4855. ml.get_key(LLM_KV_TOKENIZER_ADD_PREFIX, vocab.tokenizer_add_space_prefix, false);
  4856. ml.get_key(LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, vocab.tokenizer_remove_extra_whitespaces, false);
  4857. }
  4858. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  4859. if (token_idx == -1) {
  4860. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  4861. }
  4862. const float * scores = nullptr;
  4863. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  4864. if (score_idx != -1) {
  4865. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  4866. }
  4867. const int * toktypes = nullptr;
  4868. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  4869. if (toktype_idx != -1) {
  4870. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  4871. }
  4872. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  4873. vocab.id_to_token.resize(n_vocab);
  4874. for (uint32_t i = 0; i < n_vocab; i++) {
  4875. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  4876. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4877. vocab.token_to_id[word] = i;
  4878. vocab.max_token_len = std::max(vocab.max_token_len, (int) word.size());
  4879. auto & token_data = vocab.id_to_token[i];
  4880. token_data.text = std::move(word);
  4881. token_data.score = scores ? scores[i] : 0.0f;
  4882. token_data.attr = LLAMA_TOKEN_ATTR_NORMAL;
  4883. if (toktypes) { //TODO: remove, required until per token attributes are available from GGUF file
  4884. switch(toktypes[i]) {
  4885. case LLAMA_TOKEN_TYPE_UNKNOWN: token_data.attr = LLAMA_TOKEN_ATTR_UNKNOWN; break;
  4886. case LLAMA_TOKEN_TYPE_UNUSED: token_data.attr = LLAMA_TOKEN_ATTR_UNUSED; break;
  4887. case LLAMA_TOKEN_TYPE_NORMAL: token_data.attr = LLAMA_TOKEN_ATTR_NORMAL; break;
  4888. case LLAMA_TOKEN_TYPE_CONTROL: token_data.attr = LLAMA_TOKEN_ATTR_CONTROL; break;
  4889. case LLAMA_TOKEN_TYPE_USER_DEFINED: token_data.attr = LLAMA_TOKEN_ATTR_USER_DEFINED; break;
  4890. case LLAMA_TOKEN_TYPE_BYTE: token_data.attr = LLAMA_TOKEN_ATTR_BYTE; break;
  4891. case LLAMA_TOKEN_TYPE_UNDEFINED: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4892. default: token_data.attr = LLAMA_TOKEN_ATTR_UNDEFINED; break;
  4893. }
  4894. }
  4895. }
  4896. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  4897. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  4898. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4899. // For Fill-In-the-Middle (FIM)/infill models which where converted
  4900. // prior to support of FIM special tokens in GGUF, the following
  4901. // will allow those models to continue to work. The general names
  4902. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  4903. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  4904. // new versions of these models have been published.
  4905. std::string gen_name;
  4906. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  4907. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  4908. [](unsigned char c){ return std::tolower(c); });
  4909. if (gen_name.find("code") != std::string::npos) {
  4910. if (model.arch == LLM_ARCH_LLAMA
  4911. && 32010 < vocab.id_to_token.size()
  4912. && vocab.id_to_token[32007].text.find("<PRE>") != std::string::npos
  4913. && vocab.id_to_token[32008].text.find("<SUF>") != std::string::npos
  4914. && vocab.id_to_token[32009].text.find("<MID>") != std::string::npos
  4915. && vocab.id_to_token[32010].text.find("<EOT>") != std::string::npos) {
  4916. vocab.special_prefix_id = 32007;
  4917. vocab.special_suffix_id = 32008;
  4918. vocab.special_middle_id = 32009;
  4919. vocab.special_eot_id = 32010;
  4920. } else if (model.arch == LLM_ARCH_GEMMA
  4921. && 107 < vocab.id_to_token.size()
  4922. && vocab.id_to_token[67].text == "<|fim_prefix|>"
  4923. && vocab.id_to_token[69].text == "<|fim_suffix|>"
  4924. && vocab.id_to_token[68].text == "<|fim_middle|>"
  4925. && vocab.id_to_token[107].text == "<end_of_turn>") {
  4926. vocab.special_prefix_id = 67;
  4927. vocab.special_suffix_id = 69;
  4928. vocab.special_middle_id = 68;
  4929. // TODO: this is not EOT, it is "file separator" token, needs fix
  4930. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  4931. //vocab.special_eot_id = 70;
  4932. vocab.special_eot_id = 107;
  4933. }
  4934. }
  4935. try {
  4936. vocab.linefeed_id = llama_byte_to_token_impl(vocab, '\n');
  4937. } catch (const std::exception & e) {
  4938. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  4939. vocab.linefeed_id = vocab.special_pad_id;
  4940. }
  4941. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4942. vocab.linefeed_id = vocab.special_pad_id;
  4943. } else {
  4944. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  4945. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  4946. vocab.linefeed_id = ids[0];
  4947. }
  4948. // special tokens
  4949. {
  4950. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  4951. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  4952. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  4953. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  4954. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  4955. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  4956. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  4957. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  4958. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  4959. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  4960. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  4961. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  4962. };
  4963. for (const auto & it : special_token_types) {
  4964. const std::string & key = kv(std::get<0>(it));
  4965. int32_t & id = std::get<1>(it);
  4966. uint32_t new_id;
  4967. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  4968. continue;
  4969. }
  4970. if (new_id >= vocab.id_to_token.size()) {
  4971. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  4972. __func__, key.c_str(), new_id, id);
  4973. } else {
  4974. id = new_id;
  4975. }
  4976. }
  4977. // Handle add_bos_token and add_eos_token
  4978. {
  4979. bool temp = true;
  4980. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  4981. vocab.tokenizer_add_bos = temp;
  4982. }
  4983. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  4984. vocab.tokenizer_add_eos = temp;
  4985. }
  4986. }
  4987. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  4988. //
  4989. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  4990. // for now, we apply this workaround to find the EOT token based on its text
  4991. if (vocab.special_eot_id == -1) {
  4992. for (const auto & t : vocab.token_to_id) {
  4993. if (
  4994. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  4995. // need to fix convert script
  4996. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  4997. (t.first == "<|eot_id|>" ||
  4998. t.first == "<|im_end|>" ||
  4999. t.first == "<|end|>" ||
  5000. t.first == "<end_of_turn>" ||
  5001. t.first == "<|endoftext|>"
  5002. )
  5003. ) {
  5004. vocab.special_eot_id = t.second;
  5005. break;
  5006. }
  5007. }
  5008. }
  5009. }
  5010. // build special tokens cache
  5011. {
  5012. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  5013. if (vocab.id_to_token[id].attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) {
  5014. vocab.cache_special_tokens.push_back(id);
  5015. }
  5016. }
  5017. std::sort(vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  5018. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  5019. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  5020. }
  5021. );
  5022. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  5023. }
  5024. // build token to piece cache
  5025. {
  5026. size_t size_cache = 0;
  5027. std::vector<llama_vocab::token> cache_token_to_piece(n_vocab);
  5028. for (uint32_t id = 0; id < n_vocab; ++id) {
  5029. cache_token_to_piece[id] = llama_token_to_piece(&model, id, true);
  5030. size_cache += cache_token_to_piece[id].size();
  5031. }
  5032. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  5033. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  5034. }
  5035. // Handle per token attributes
  5036. //NOTE: Each model customizes per token attributes.
  5037. //NOTE: Per token attributes are missing from the GGUF file.
  5038. //TODO: Extract attributes from GGUF file.
  5039. {
  5040. auto _contains_any = [] (const std::string &str, const std::vector<std::string> &substrs) -> bool {
  5041. for (auto substr : substrs) {
  5042. if (str.find(substr) < std::string::npos) {
  5043. return true;
  5044. }
  5045. }
  5046. return false;
  5047. };
  5048. auto _set_tokenid_attr = [&] (const llama_vocab::id id, llama_token_attr attr, bool value) {
  5049. uint32_t current = vocab.id_to_token.at(id).attr;
  5050. current = value ? (current | attr) : (current & ~attr);
  5051. vocab.id_to_token[id].attr = (llama_token_attr) current;
  5052. };
  5053. auto _set_token_attr = [&] (const std::string & token, llama_token_attr attr, bool value) {
  5054. _set_tokenid_attr(vocab.token_to_id.at(token), attr, value);
  5055. };
  5056. std::string model_name;
  5057. std::string tokenizer_pre;
  5058. ml.get_key(LLM_KV_GENERAL_NAME, model_name, false);
  5059. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  5060. // model name to lowercase
  5061. std::transform(model_name.begin(), model_name.end(), model_name.begin(),
  5062. [] (const std::string::value_type x) {
  5063. return std::tolower(x);
  5064. }
  5065. );
  5066. // set attributes by model/tokenizer name
  5067. if (_contains_any(tokenizer_pre, {"jina-v2-de", "jina-v2-es", "jina-v2-code"})) {
  5068. _set_token_attr("<mask>", LLAMA_TOKEN_ATTR_LSTRIP, true);
  5069. } else if (_contains_any(model_name, {"phi-3", "phi3"})) {
  5070. for (auto id : vocab.cache_special_tokens) {
  5071. _set_tokenid_attr(id, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5072. }
  5073. for (auto token : {"</s>"}) {
  5074. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, true);
  5075. }
  5076. for (auto token : {"<unk>", "<s>", "<|endoftext|>"}) {
  5077. _set_token_attr(token, LLAMA_TOKEN_ATTR_RSTRIP, false);
  5078. }
  5079. }
  5080. }
  5081. }
  5082. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  5083. const auto & hparams = model.hparams;
  5084. const auto & vocab = model.vocab;
  5085. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  5086. auto print_f = [](const std::function<uint32_t(uint32_t)> & f, uint32_t n) {
  5087. bool is_var = false;
  5088. std::vector<uint32_t> v;
  5089. for (uint32_t i = 0; i < n; ++i) {
  5090. v.push_back(f(i));
  5091. if (v[i] != v[0]) {
  5092. is_var = true;
  5093. }
  5094. }
  5095. std::stringstream ss;
  5096. if (is_var) {
  5097. ss << "[";
  5098. for (uint32_t i = 0; i < n; ++i) {
  5099. ss << v[i];
  5100. if (i < n - 1) {
  5101. ss << ", ";
  5102. }
  5103. }
  5104. ss << "]";
  5105. } else {
  5106. ss << v[0];
  5107. }
  5108. return ss.str();
  5109. };
  5110. // hparams
  5111. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  5112. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  5113. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  5114. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  5115. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  5116. LLAMA_LOG_INFO("%s: vocab_only = %d\n", __func__, hparams.vocab_only);
  5117. if (!hparams.vocab_only) {
  5118. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  5119. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  5120. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  5121. LLAMA_LOG_INFO("%s: n_head = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_head(il); }, hparams.n_layer).c_str());
  5122. 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());
  5123. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  5124. LLAMA_LOG_INFO("%s: n_swa = %u\n", __func__, hparams.n_swa);
  5125. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  5126. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  5127. LLAMA_LOG_INFO("%s: n_gqa = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_gqa(il); }, hparams.n_layer).c_str());
  5128. 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());
  5129. 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());
  5130. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  5131. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  5132. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  5133. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  5134. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  5135. LLAMA_LOG_INFO("%s: n_ff = %s\n", __func__, print_f([&](uint32_t il) { return hparams.n_ff(il); }, hparams.n_layer).c_str());
  5136. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  5137. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  5138. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  5139. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  5140. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  5141. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  5142. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  5143. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  5144. LLAMA_LOG_INFO("%s: n_ctx_orig_yarn = %u\n", __func__, hparams.n_ctx_orig_yarn);
  5145. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  5146. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  5147. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  5148. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  5149. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  5150. }
  5151. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  5152. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  5153. if (ml.n_elements >= 1e12) {
  5154. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  5155. } else if (ml.n_elements >= 1e9) {
  5156. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  5157. } else if (ml.n_elements >= 1e6) {
  5158. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  5159. } else {
  5160. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  5161. }
  5162. if (ml.n_bytes < GiB) {
  5163. 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);
  5164. } else {
  5165. 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);
  5166. }
  5167. // general kv
  5168. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  5169. // special tokens
  5170. 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() ); }
  5171. 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() ); }
  5172. 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() ); }
  5173. 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() ); }
  5174. 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() ); }
  5175. 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() ); }
  5176. 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() ); }
  5177. 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() ); }
  5178. 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() ); }
  5179. 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() ); }
  5180. 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() ); }
  5181. 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() ); }
  5182. LLAMA_LOG_INFO("%s: max token length = %d\n", __func__, vocab.max_token_len);
  5183. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  5184. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  5185. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  5186. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  5187. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5188. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  5189. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  5190. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  5191. }
  5192. if (model.arch == LLM_ARCH_QWEN2MOE) {
  5193. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  5194. LLAMA_LOG_INFO("%s: n_ff_shexp = %d\n", __func__, hparams.n_ff_shexp);
  5195. }
  5196. }
  5197. // Returns false if cancelled by progress_callback
  5198. static bool llm_load_tensors(
  5199. llama_model_loader & ml,
  5200. llama_model & model,
  5201. int n_gpu_layers,
  5202. enum llama_split_mode split_mode,
  5203. int main_gpu,
  5204. const float * tensor_split,
  5205. bool use_mlock,
  5206. llama_progress_callback progress_callback,
  5207. void * progress_callback_user_data) {
  5208. model.t_start_us = ggml_time_us();
  5209. auto & hparams = model.hparams;
  5210. model.split_mode = split_mode;
  5211. model.main_gpu = main_gpu;
  5212. model.n_gpu_layers = n_gpu_layers;
  5213. const int n_layer = hparams.n_layer;
  5214. const int i_gpu_start = std::max((int) hparams.n_layer - n_gpu_layers, (int) 0);
  5215. bool use_mmap_buffer = true;
  5216. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  5217. model.buft_input = llama_default_buffer_type_cpu(true);
  5218. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  5219. model.buft_layer.resize(n_layer);
  5220. // assign cpu layers
  5221. for (int i = 0; i < i_gpu_start; ++i) {
  5222. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  5223. }
  5224. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  5225. // calculate the split points
  5226. int device_count = llama_get_device_count(model);
  5227. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  5228. std::vector<float> splits(device_count);
  5229. if (all_zero) {
  5230. // default split, by free memory
  5231. for (int i = 0; i < device_count; ++i) {
  5232. splits[i] = llama_get_device_memory(model, i);
  5233. }
  5234. } else {
  5235. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  5236. }
  5237. // sum and normalize the splits to get the split points
  5238. float split_sum = 0.0f;
  5239. for (int i = 0; i < device_count; ++i) {
  5240. split_sum += splits[i];
  5241. splits[i] = split_sum;
  5242. }
  5243. for (int i = 0; i < device_count; ++i) {
  5244. splits[i] /= split_sum;
  5245. }
  5246. // assign the repeating layers to the devices according to the splits
  5247. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  5248. for (int i = i_gpu_start; i < n_layer; ++i) {
  5249. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  5250. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  5251. }
  5252. // assign the output layer
  5253. if (n_gpu_layers > n_layer) {
  5254. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  5255. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  5256. } else {
  5257. model.buft_output = llama_default_buffer_type_cpu(true);
  5258. }
  5259. } else {
  5260. ggml_backend_buffer_type_t split_buft;
  5261. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  5262. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  5263. } else {
  5264. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  5265. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  5266. }
  5267. // assign the repeating layers
  5268. for (int i = i_gpu_start; i < n_layer; ++i) {
  5269. model.buft_layer[i] = {
  5270. split_buft,
  5271. llama_default_buffer_type_offload(model, main_gpu)
  5272. };
  5273. }
  5274. // assign the output layer
  5275. if (n_gpu_layers > n_layer) {
  5276. model.buft_output = {
  5277. split_buft,
  5278. llama_default_buffer_type_offload(model, main_gpu)
  5279. };
  5280. } else {
  5281. model.buft_output = llama_default_buffer_type_cpu(true);
  5282. }
  5283. }
  5284. // count used buffer types
  5285. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  5286. buft_layer_count[model.buft_input.buft]++;
  5287. buft_layer_count[model.buft_input.buft_matrix]++;
  5288. buft_layer_count[model.buft_output.buft]++;
  5289. buft_layer_count[model.buft_output.buft_matrix]++;
  5290. for (int i = 0; i < n_layer; ++i) {
  5291. buft_layer_count[model.buft_layer[i].buft]++;
  5292. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  5293. }
  5294. // create one context per buffer type
  5295. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  5296. // for moe merged tensors
  5297. ctx_size += ggml_tensor_overhead()*n_layer*3;
  5298. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  5299. for (auto & it : buft_layer_count) {
  5300. struct ggml_init_params params = {
  5301. /*.mem_size =*/ ctx_size,
  5302. /*.mem_buffer =*/ NULL,
  5303. /*.no_alloc =*/ true,
  5304. };
  5305. ggml_context * ctx = ggml_init(params);
  5306. if (!ctx) {
  5307. throw std::runtime_error(format("failed to create context"));
  5308. }
  5309. ctx_map[it.first] = ctx;
  5310. model.ctxs.push_back(ctx);
  5311. }
  5312. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  5313. // create tensors for the weights
  5314. {
  5315. // note: cast to int64_t since we will use these for the tensor dimensions
  5316. const int64_t n_head = hparams.n_head();
  5317. const int64_t n_head_kv = hparams.n_head_kv();
  5318. const int64_t n_embd = hparams.n_embd;
  5319. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5320. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5321. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5322. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5323. const int64_t n_ff = hparams.n_ff();
  5324. const int64_t n_embd_gqa = n_embd_v_gqa;
  5325. const int64_t n_vocab = hparams.n_vocab;
  5326. const int64_t n_vocab_type = hparams.n_vocab_type;
  5327. const int64_t n_expert = hparams.n_expert;
  5328. const int64_t n_expert_used = hparams.n_expert_used;
  5329. const int64_t n_ctx_train = hparams.n_ctx_train;
  5330. if (n_expert > 0 && hparams.n_expert_used == 0) {
  5331. throw std::runtime_error("model has expert layers but no expert layers are used");
  5332. }
  5333. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  5334. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  5335. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  5336. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  5337. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  5338. model.layers.resize(n_layer);
  5339. const auto tn = LLM_TN(model.arch);
  5340. switch (model.arch) {
  5341. case LLM_ARCH_LLAMA:
  5342. case LLM_ARCH_REFACT:
  5343. case LLM_ARCH_MINICPM:
  5344. {
  5345. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5346. // output
  5347. {
  5348. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5349. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5350. // if output is NULL, init from the input tok embed
  5351. if (model.output == NULL) {
  5352. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5353. }
  5354. }
  5355. for (int i = 0; i < n_layer; ++i) {
  5356. ggml_context * ctx_layer = ctx_for_layer(i);
  5357. ggml_context * ctx_split = ctx_for_layer_split(i);
  5358. auto & layer = model.layers[i];
  5359. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5360. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  5361. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5362. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5363. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  5364. // optional bias tensors
  5365. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5366. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5367. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5368. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5369. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5370. layer.rope_freqs = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ROPE_FREQS, "weight"), {n_embd/n_head/2}, llama_model_loader::TENSOR_NOT_REQUIRED | (i != 0 ? llama_model_loader::TENSOR_DUPLICATED : 0));
  5371. if (n_expert == 0) {
  5372. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5373. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5374. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5375. // optional MLP bias
  5376. layer.ffn_gate_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5377. layer.ffn_down_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5378. layer.ffn_up_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5379. } else {
  5380. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5381. 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);
  5382. if (layer.ffn_gate_exps) {
  5383. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5384. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5385. } else {
  5386. // merge split expert into a single tensor for compatibility with older models
  5387. // requires disabling mmap
  5388. use_mmap_buffer = false;
  5389. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5390. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5391. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5392. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5393. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5394. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5395. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5396. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5397. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5398. for (uint32_t x = 0; x < n_expert; ++x) {
  5399. // the individual experts are loaded into a view of the merged tensor
  5400. 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);
  5401. 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);
  5402. 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);
  5403. }
  5404. }
  5405. }
  5406. }
  5407. } break;
  5408. case LLM_ARCH_GROK:
  5409. {
  5410. if (n_expert == 0) {
  5411. throw std::runtime_error("Grok model cannot have zero experts");
  5412. }
  5413. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5414. // output
  5415. {
  5416. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5417. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5418. // if output is NULL, init from the input tok embed
  5419. if (model.output == NULL) {
  5420. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5421. }
  5422. }
  5423. for (int i = 0; i < n_layer; ++i) {
  5424. ggml_context * ctx_layer = ctx_for_layer(i);
  5425. ggml_context * ctx_split = ctx_for_layer_split(i);
  5426. auto & layer = model.layers[i];
  5427. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5428. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5429. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5430. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5431. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5432. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5433. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5434. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5435. 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);
  5436. if (layer.ffn_gate_exps) {
  5437. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5438. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5439. } else {
  5440. // merge split expert into a single tensor for compatibility with older models
  5441. // requires disabling mmap
  5442. use_mmap_buffer = false;
  5443. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  5444. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  5445. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  5446. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  5447. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  5448. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  5449. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  5450. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  5451. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  5452. for (uint32_t x = 0; x < n_expert; ++x) {
  5453. // the individual experts are loaded into a view of the merged tensor
  5454. 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);
  5455. 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);
  5456. 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);
  5457. }
  5458. }
  5459. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5460. }
  5461. } break;
  5462. case LLM_ARCH_DBRX:
  5463. {
  5464. if (n_expert == 0) {
  5465. throw std::runtime_error("DBRX model cannot have zero experts");
  5466. }
  5467. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5468. // output
  5469. {
  5470. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5471. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5472. }
  5473. for (int i = 0; i < n_layer; ++i) {
  5474. ggml_context * ctx_layer = ctx_for_layer(i);
  5475. ggml_context * ctx_split = ctx_for_layer_split(i);
  5476. auto & layer = model.layers[i];
  5477. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5478. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5479. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5480. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5481. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5482. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5483. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  5484. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5485. }
  5486. } break;
  5487. case LLM_ARCH_BAICHUAN:
  5488. {
  5489. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5490. {
  5491. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5492. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5493. }
  5494. for (int i = 0; i < n_layer; ++i) {
  5495. ggml_context * ctx_layer = ctx_for_layer(i);
  5496. ggml_context * ctx_split = ctx_for_layer_split(i);
  5497. auto & layer = model.layers[i];
  5498. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5499. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5500. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5501. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5502. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5503. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5504. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5505. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5506. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5507. }
  5508. } break;
  5509. case LLM_ARCH_FALCON:
  5510. {
  5511. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5512. // output
  5513. {
  5514. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5515. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5516. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5517. if (!model.output) {
  5518. 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
  5519. }
  5520. }
  5521. for (int i = 0; i < n_layer; ++i) {
  5522. ggml_context * ctx_layer = ctx_for_layer(i);
  5523. ggml_context * ctx_split = ctx_for_layer_split(i);
  5524. auto & layer = model.layers[i];
  5525. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5526. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5527. 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);
  5528. 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);
  5529. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5530. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5531. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5532. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5533. }
  5534. } break;
  5535. case LLM_ARCH_STARCODER:
  5536. {
  5537. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5538. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5539. // output
  5540. {
  5541. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5542. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5543. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5544. if (!model.output) {
  5545. // needs to be on GPU
  5546. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5547. }
  5548. }
  5549. for (int i = 0; i < n_layer; ++i) {
  5550. ggml_context * ctx_layer = ctx_for_layer(i);
  5551. ggml_context * ctx_split = ctx_for_layer_split(i);
  5552. auto & layer = model.layers[i];
  5553. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5554. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5555. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5556. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5557. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5558. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5559. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5560. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5561. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5562. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5563. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5564. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5565. }
  5566. } break;
  5567. case LLM_ARCH_BERT:
  5568. case LLM_ARCH_NOMIC_BERT:
  5569. {
  5570. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5571. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  5572. if (model.arch == LLM_ARCH_BERT) {
  5573. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5574. }
  5575. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5576. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5577. for (int i = 0; i < n_layer; ++i) {
  5578. ggml_context * ctx_layer = ctx_for_layer(i);
  5579. ggml_context * ctx_split = ctx_for_layer_split(i);
  5580. auto & layer = model.layers[i];
  5581. if (model.arch == LLM_ARCH_BERT) {
  5582. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5583. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5584. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5585. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5586. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5587. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5588. } else {
  5589. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5590. }
  5591. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5592. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  5593. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5594. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5595. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5596. if (model.arch == LLM_ARCH_BERT) {
  5597. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5598. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5599. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5600. } else {
  5601. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5602. }
  5603. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5604. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5605. }
  5606. } break;
  5607. case LLM_ARCH_JINA_BERT_V2:
  5608. {
  5609. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  5610. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); // token_type_embeddings
  5611. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  5612. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  5613. for (int i = 0; i < n_layer; ++i) {
  5614. ggml_context * ctx_layer = ctx_for_layer(i);
  5615. ggml_context * ctx_split = ctx_for_layer_split(i);
  5616. auto & layer = model.layers[i]; // JinaBertLayer
  5617. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5618. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5619. 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);
  5620. 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);
  5621. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5622. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5623. 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);
  5624. 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);
  5625. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5626. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5627. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  5628. layer.bo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  5629. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  5630. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  5631. 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);
  5632. 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);
  5633. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5634. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5635. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5636. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5637. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  5638. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  5639. }
  5640. } break;
  5641. case LLM_ARCH_BLOOM:
  5642. {
  5643. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5644. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  5645. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  5646. // output
  5647. {
  5648. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5649. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5650. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5651. }
  5652. for (int i = 0; i < n_layer; ++i) {
  5653. ggml_context * ctx_layer = ctx_for_layer(i);
  5654. ggml_context * ctx_split = ctx_for_layer_split(i);
  5655. auto & layer = model.layers[i];
  5656. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5657. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5658. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5659. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5660. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5661. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5662. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5663. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5664. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5665. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5666. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5667. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5668. }
  5669. } break;
  5670. case LLM_ARCH_MPT:
  5671. {
  5672. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5673. 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);
  5674. // output
  5675. {
  5676. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5677. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5678. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5679. if (!model.output) {
  5680. 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
  5681. }
  5682. }
  5683. for (int i = 0; i < n_layer; ++i) {
  5684. ggml_context * ctx_layer = ctx_for_layer(i);
  5685. ggml_context * ctx_split = ctx_for_layer_split(i);
  5686. auto & layer = model.layers[i];
  5687. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5688. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5689. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5690. 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);
  5691. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5692. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5693. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5694. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5695. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5696. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5697. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5698. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5699. 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);
  5700. 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);
  5701. 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);
  5702. 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);
  5703. // AWQ ScaleActivation layer
  5704. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5705. }
  5706. } break;
  5707. case LLM_ARCH_STABLELM:
  5708. {
  5709. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5710. // output
  5711. {
  5712. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5713. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5714. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5715. }
  5716. for (int i = 0; i < n_layer; ++i) {
  5717. ggml_context * ctx_layer = ctx_for_layer(i);
  5718. ggml_context * ctx_split = ctx_for_layer_split(i);
  5719. auto & layer = model.layers[i];
  5720. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5721. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5722. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5723. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5724. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5725. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5726. // optional bias tensors, present in Stable LM 2 1.6B
  5727. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5728. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5729. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5730. // optional q and k layernorms, present in StableLM 2 12B
  5731. 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);
  5732. 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);
  5733. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  5734. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5735. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5736. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5737. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5738. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5739. }
  5740. } break;
  5741. case LLM_ARCH_QWEN:
  5742. {
  5743. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5744. // output
  5745. {
  5746. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5747. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5748. }
  5749. for (int i = 0; i < n_layer; ++i) {
  5750. ggml_context * ctx_layer = ctx_for_layer(i);
  5751. ggml_context * ctx_split = ctx_for_layer_split(i);
  5752. auto & layer = model.layers[i];
  5753. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5754. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  5755. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  5756. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5757. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5758. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  5759. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  5760. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  5761. }
  5762. } break;
  5763. case LLM_ARCH_QWEN2:
  5764. {
  5765. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5766. // output
  5767. {
  5768. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5769. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5770. // if output is NULL, init from the input tok embed
  5771. if (model.output == NULL) {
  5772. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5773. }
  5774. }
  5775. for (int i = 0; i < n_layer; ++i) {
  5776. ggml_context * ctx_layer = ctx_for_layer(i);
  5777. ggml_context * ctx_split = ctx_for_layer_split(i);
  5778. auto & layer = model.layers[i];
  5779. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5780. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5781. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5782. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5783. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5784. // optional bias tensors
  5785. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5786. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5787. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5788. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5789. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5790. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5791. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5792. }
  5793. } break;
  5794. case LLM_ARCH_QWEN2MOE:
  5795. {
  5796. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5797. // output
  5798. {
  5799. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5800. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5801. }
  5802. for (int i = 0; i < n_layer; ++i) {
  5803. ggml_context * ctx_layer = ctx_for_layer(i);
  5804. ggml_context * ctx_split = ctx_for_layer_split(i);
  5805. auto & layer = model.layers[i];
  5806. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5807. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5808. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5809. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5810. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5811. // optional bias tensors
  5812. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5813. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5814. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5815. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5816. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5817. GGML_ASSERT(n_expert > 0);
  5818. GGML_ASSERT(n_expert_used > 0);
  5819. // MoE branch
  5820. const int64_t n_ff_exp = hparams.n_ff_exp ? hparams.n_ff_exp : n_ff / n_expert_used;
  5821. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5822. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  5823. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5824. // Shared expert branch
  5825. const int64_t n_ff_shexp = hparams.n_ff_shexp ? hparams.n_ff_shexp : n_ff;
  5826. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  5827. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5828. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd});
  5829. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), { n_embd, n_ff_shexp});
  5830. }
  5831. } break;
  5832. case LLM_ARCH_PHI2:
  5833. {
  5834. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5835. // output
  5836. {
  5837. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5838. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5839. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5840. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  5841. }
  5842. for (int i = 0; i < n_layer; ++i) {
  5843. ggml_context * ctx_layer = ctx_for_layer(i);
  5844. ggml_context * ctx_split = ctx_for_layer_split(i);
  5845. auto & layer = model.layers[i];
  5846. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5847. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5848. 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);
  5849. 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);
  5850. if (layer.wqkv == nullptr) {
  5851. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5852. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5853. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5854. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5855. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5856. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5857. }
  5858. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5859. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5860. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5861. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5862. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5863. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5864. }
  5865. } break;
  5866. case LLM_ARCH_PHI3:
  5867. {
  5868. const int64_t n_embd_head = n_embd / n_head;
  5869. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  5870. // output
  5871. {
  5872. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  5873. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  5874. }
  5875. for (int i = 0; i < n_layer; ++i) {
  5876. ggml_context * ctx_layer = ctx_for_layer(i);
  5877. ggml_context * ctx_split = ctx_for_layer_split(i);
  5878. auto & layer = model.layers[i];
  5879. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  5880. 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);
  5881. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  5882. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  5883. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  5884. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  5885. 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));
  5886. 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));
  5887. }
  5888. } break;
  5889. case LLM_ARCH_PLAMO:
  5890. {
  5891. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5892. // output
  5893. {
  5894. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5895. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5896. }
  5897. for (int i = 0; i < n_layer; ++i) {
  5898. ggml_context * ctx_layer = ctx_for_layer(i);
  5899. ggml_context * ctx_split = ctx_for_layer_split(i);
  5900. auto & layer = model.layers[i];
  5901. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5902. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5903. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5904. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5905. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5906. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5907. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5908. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5909. }
  5910. } break;
  5911. case LLM_ARCH_GPT2:
  5912. {
  5913. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5914. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, n_ctx_train});
  5915. // output
  5916. {
  5917. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5918. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5919. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5920. }
  5921. for (int i = 0; i < n_layer; ++i) {
  5922. ggml_context * ctx_layer = ctx_for_layer(i);
  5923. ggml_context * ctx_split = ctx_for_layer_split(i);
  5924. auto & layer = model.layers[i];
  5925. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5926. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5927. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5928. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5929. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5930. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5931. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5932. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5933. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5934. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5935. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5936. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5937. }
  5938. } break;
  5939. case LLM_ARCH_CODESHELL:
  5940. {
  5941. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5942. // output
  5943. {
  5944. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5945. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5946. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5947. }
  5948. for (int i = 0; i < n_layer; ++i) {
  5949. ggml_context * ctx_layer = ctx_for_layer(i);
  5950. ggml_context * ctx_split = ctx_for_layer_split(i);
  5951. auto & layer = model.layers[i];
  5952. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5953. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5954. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5955. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5956. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5957. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5958. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5959. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5960. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5961. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5962. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5963. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5964. }
  5965. } break;
  5966. case LLM_ARCH_ORION:
  5967. {
  5968. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5969. {
  5970. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5971. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5972. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5973. }
  5974. for (int i = 0; i < n_layer; ++i) {
  5975. ggml_context * ctx_layer = ctx_for_layer(i);
  5976. ggml_context * ctx_split = ctx_for_layer_split(i);
  5977. auto & layer = model.layers[i];
  5978. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5979. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5980. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5981. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5982. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5983. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5984. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5985. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5986. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5987. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5988. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5989. }
  5990. } break;
  5991. case LLM_ARCH_INTERNLM2:
  5992. {
  5993. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5994. // output
  5995. {
  5996. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5997. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5998. }
  5999. for (int i = 0; i < n_layer; ++i) {
  6000. ggml_context * ctx_layer = ctx_for_layer(i);
  6001. ggml_context * ctx_split = ctx_for_layer_split(i);
  6002. auto & layer = model.layers[i];
  6003. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6004. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6005. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6006. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6007. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6008. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6009. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6010. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6011. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6012. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6013. }
  6014. } break;
  6015. case LLM_ARCH_GEMMA:
  6016. {
  6017. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6018. // output
  6019. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6020. 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
  6021. for (int i = 0; i < n_layer; ++i) {
  6022. ggml_context * ctx_layer = ctx_for_layer(i);
  6023. ggml_context * ctx_split = ctx_for_layer_split(i);
  6024. auto & layer = model.layers[i];
  6025. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6026. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6027. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6028. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6029. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6030. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6031. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6032. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6033. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6034. }
  6035. } break;
  6036. case LLM_ARCH_GEMMA2:
  6037. {
  6038. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6039. // output
  6040. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6041. 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
  6042. for (int i = 0; i < n_layer; ++i) {
  6043. ggml_context * ctx_layer = ctx_for_layer(i);
  6044. ggml_context * ctx_split = ctx_for_layer_split(i);
  6045. auto & layer = model.layers[i];
  6046. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6047. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * n_head});
  6048. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6049. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6050. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd});
  6051. layer.attn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd});
  6052. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6053. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6054. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6055. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6056. layer.ffn_post_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd});
  6057. }
  6058. } break;
  6059. case LLM_ARCH_STARCODER2:
  6060. {
  6061. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6062. // output
  6063. {
  6064. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6065. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6066. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6067. // if output is NULL, init from the input tok embed
  6068. if (model.output == NULL) {
  6069. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6070. }
  6071. }
  6072. for (int i = 0; i < n_layer; ++i) {
  6073. ggml_context * ctx_layer = ctx_for_layer(i);
  6074. ggml_context * ctx_split = ctx_for_layer_split(i);
  6075. auto & layer = model.layers[i];
  6076. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6077. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6078. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6079. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6080. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6081. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6082. // optional bias tensors
  6083. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  6084. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  6085. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  6086. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6087. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6088. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6089. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6090. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6091. // optional bias tensors
  6092. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6093. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  6094. }
  6095. } break;
  6096. case LLM_ARCH_MAMBA:
  6097. {
  6098. const int64_t d_conv = hparams.ssm_d_conv;
  6099. const int64_t d_inner = hparams.ssm_d_inner;
  6100. const int64_t d_state = hparams.ssm_d_state;
  6101. const int64_t dt_rank = hparams.ssm_dt_rank;
  6102. // only an expansion factor of 2 is supported for now
  6103. GGML_ASSERT(2 * n_embd == d_inner);
  6104. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6105. // output
  6106. {
  6107. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6108. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6109. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  6110. if (model.output == NULL) {
  6111. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6112. }
  6113. }
  6114. for (int i = 0; i < n_layer; ++i) {
  6115. ggml_context * ctx_layer = ctx_for_layer(i);
  6116. ggml_context * ctx_split = ctx_for_layer_split(i);
  6117. auto & layer = model.layers[i];
  6118. // norm
  6119. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6120. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  6121. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  6122. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  6123. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  6124. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  6125. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  6126. // no "weight" suffix for these
  6127. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  6128. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  6129. // out_proj
  6130. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  6131. }
  6132. } break;
  6133. case LLM_ARCH_XVERSE:
  6134. {
  6135. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6136. {
  6137. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6138. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6139. }
  6140. for (int i = 0; i < n_layer; ++i) {
  6141. ggml_context * ctx_layer = ctx_for_layer(i);
  6142. ggml_context * ctx_split = ctx_for_layer_split(i);
  6143. auto & layer = model.layers[i];
  6144. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6145. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6146. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6147. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6148. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6149. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6150. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "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. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6153. }
  6154. } break;
  6155. case LLM_ARCH_COMMAND_R:
  6156. {
  6157. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6158. // output
  6159. {
  6160. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6161. // init output from the input tok embed
  6162. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6163. }
  6164. for (int i = 0; i < n_layer; ++i) {
  6165. ggml_context * ctx_layer = ctx_for_layer(i);
  6166. ggml_context * ctx_split = ctx_for_layer_split(i);
  6167. auto & layer = model.layers[i];
  6168. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6169. if (n_layer >= 64){
  6170. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k, n_head});
  6171. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k, n_head_kv});
  6172. }
  6173. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6174. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6175. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6176. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6177. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6178. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6179. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6180. }
  6181. } break;
  6182. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  6183. {
  6184. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6185. // output
  6186. {
  6187. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6188. // if output is NULL, init from the input tok embed
  6189. if (model.output == NULL) {
  6190. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6191. }
  6192. }
  6193. for (int i = 0; i < n_layer; ++i) {
  6194. ggml_context * ctx_split = ctx_for_layer_split(i);
  6195. auto & layer = model.layers[i];
  6196. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6197. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6198. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6199. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6200. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6201. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6202. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6203. }
  6204. } break;
  6205. case LLM_ARCH_OPENELM:
  6206. {
  6207. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6208. // output
  6209. {
  6210. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6211. // init output from the input tok embed
  6212. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6213. }
  6214. for (int i = 0; i < n_layer; ++i) {
  6215. const int64_t n_head = hparams.n_head(i);
  6216. const int64_t n_head_qkv = 2*hparams.n_head_kv(i) + n_head;
  6217. const int64_t n_ff = hparams.n_ff(i);
  6218. ggml_context * ctx_layer = ctx_for_layer(i);
  6219. ggml_context * ctx_split = ctx_for_layer_split(i);
  6220. auto & layer = model.layers[i];
  6221. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6222. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_head_qkv*n_embd_head_k});
  6223. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k});
  6224. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k});
  6225. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*n_embd_head_k, n_embd});
  6226. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6227. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6228. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6229. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6230. }
  6231. } break;
  6232. case LLM_ARCH_GPTNEOX:
  6233. {
  6234. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6235. // output
  6236. {
  6237. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6238. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  6239. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6240. }
  6241. for (int i = 0; i < n_layer; ++i) {
  6242. ggml_context * ctx_layer = ctx_for_layer(i);
  6243. ggml_context * ctx_split = ctx_for_layer_split(i);
  6244. auto & layer = model.layers[i];
  6245. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6246. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6247. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6248. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6249. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6250. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6251. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6252. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6253. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6254. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6255. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6256. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6257. }
  6258. } break;
  6259. case LLM_ARCH_ARCTIC:
  6260. {
  6261. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6262. // output
  6263. {
  6264. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6265. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6266. // if output is NULL, init from the input tok embed
  6267. if (model.output == NULL) {
  6268. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6269. }
  6270. }
  6271. for (int i = 0; i < n_layer; ++i) {
  6272. ggml_context * ctx_layer = ctx_for_layer(i);
  6273. ggml_context * ctx_split = ctx_for_layer_split(i);
  6274. auto & layer = model.layers[i];
  6275. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6276. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6277. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6278. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6279. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6280. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6281. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  6282. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  6283. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  6284. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6285. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  6286. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  6287. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  6288. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  6289. }
  6290. } break;
  6291. case LLM_ARCH_DEEPSEEK2:
  6292. {
  6293. const bool is_lite = (hparams.n_layer == 27);
  6294. const int64_t n_embd_head_qk_rope = hparams.n_rot;
  6295. const int64_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  6296. const int64_t q_lora_rank = hparams.n_lora_q;
  6297. const int64_t kv_lora_rank = hparams.n_lora_kv;
  6298. const int64_t n_ff_exp = hparams.n_ff_exp;
  6299. const int64_t n_expert_shared = hparams.n_expert_shared;
  6300. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6301. // output
  6302. {
  6303. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6304. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6305. }
  6306. for (int i = 0; i < n_layer; ++i) {
  6307. ggml_context * ctx_layer = ctx_for_layer(i);
  6308. ggml_context * ctx_split = ctx_for_layer_split(i);
  6309. auto & layer = model.layers[i];
  6310. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6311. if (!is_lite) {
  6312. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  6313. }
  6314. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  6315. if (!is_lite) {
  6316. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  6317. 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});
  6318. } else {
  6319. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6320. }
  6321. 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)});
  6322. 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)});
  6323. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_head * ( n_embd_head_v), n_embd});
  6324. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6325. if (i < (int) hparams.n_layer_dense_lead) {
  6326. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6327. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6328. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6329. } else {
  6330. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  6331. GGML_ASSERT(n_expert > 0);
  6332. GGML_ASSERT(n_expert_used > 0);
  6333. // MoE branch
  6334. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6335. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  6336. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  6337. // Shared expert branch
  6338. 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});
  6339. 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});
  6340. 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});
  6341. }
  6342. }
  6343. } break;
  6344. case LLM_ARCH_BITNET:
  6345. {
  6346. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6347. // output
  6348. {
  6349. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6350. }
  6351. for (int i = 0; i < n_layer; ++i) {
  6352. ggml_context * ctx_layer = ctx_for_layer(i);
  6353. ggml_context * ctx_split = ctx_for_layer_split(i);
  6354. auto & layer = model.layers[i];
  6355. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6356. layer.attn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd});
  6357. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  6358. layer.wq_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "scale", i), {1});
  6359. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  6360. layer.wk_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "scale", i), {1});
  6361. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  6362. layer.wv_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "scale", i), {1});
  6363. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6364. layer.wo_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1});
  6365. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6366. layer.ffn_sub_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff});
  6367. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6368. layer.ffn_gate_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "scale", i), {1});
  6369. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6370. layer.ffn_down_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1});
  6371. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6372. layer.ffn_up_scale = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "scale", i), {1});
  6373. }
  6374. } break;
  6375. case LLM_ARCH_T5:
  6376. {
  6377. const auto n_rel_attn_bkts = hparams.n_rel_attn_bkts;
  6378. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6379. // output
  6380. {
  6381. model.output_norm_enc = ml.create_tensor(ctx_output, tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), {n_embd});
  6382. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_DEC_OUTPUT_NORM, "weight"), {n_embd});
  6383. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  6384. // if output is NULL, init from the input tok embed
  6385. if (model.output == NULL) {
  6386. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  6387. }
  6388. }
  6389. for (int i = 0; i < n_layer; ++i) {
  6390. ggml_context * ctx_layer = ctx_for_layer(i);
  6391. ggml_context * ctx_split = ctx_for_layer_split(i);
  6392. auto & layer = model.layers[i];
  6393. layer.attn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_ATTN_NORM, "weight", i), {n_embd});
  6394. 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);
  6395. layer.wq_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6396. layer.wk_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6397. layer.wv_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6398. layer.wo_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6399. layer.ffn_norm_enc = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ENC_FFN_NORM, "weight", i), {n_embd});
  6400. 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);
  6401. layer.ffn_down_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6402. layer.ffn_up_enc = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ENC_FFN_UP, "weight", i), {n_embd, n_ff});
  6403. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_ATTN_NORM, "weight", i), {n_embd});
  6404. 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);
  6405. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6406. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6407. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6408. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6409. layer.attn_norm_cross = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_CROSS_ATTN_NORM, "weight", i), {n_embd});
  6410. // this tensor seems to be unused in HF transformers implementation
  6411. 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);
  6412. layer.wq_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  6413. layer.wk_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  6414. layer.wv_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  6415. layer.wo_cross = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_CROSS_ATTN_OUT, "weight", i), {n_embd_v_gqa, n_embd});
  6416. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_DEC_FFN_NORM, "weight", i), {n_embd});
  6417. 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);
  6418. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_DOWN, "weight", i), { n_ff, n_embd});
  6419. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_DEC_FFN_UP, "weight", i), {n_embd, n_ff});
  6420. }
  6421. } break;
  6422. case LLM_ARCH_JAIS:
  6423. {
  6424. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6425. // Output
  6426. {
  6427. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6428. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {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.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  6437. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  6438. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  6439. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6440. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  6441. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6442. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  6443. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6444. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  6445. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  6446. layer.ffn_gate_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff});
  6447. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  6448. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  6449. }
  6450. } break;
  6451. case LLM_ARCH_CHATGLM:
  6452. {
  6453. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  6454. // output
  6455. {
  6456. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  6457. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  6458. }
  6459. for (int i = 0; i < n_layer; ++i) {
  6460. ggml_context * ctx_layer = ctx_for_layer(i);
  6461. ggml_context * ctx_split = ctx_for_layer_split(i);
  6462. auto & layer = model.layers[i];
  6463. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  6464. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + (hparams.n_embd_head_k << 2)});
  6465. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + (hparams.n_embd_head_k << 2)});
  6466. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  6467. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  6468. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff * 2});
  6469. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  6470. }
  6471. } break;
  6472. default:
  6473. throw std::runtime_error("unknown architecture");
  6474. }
  6475. }
  6476. ml.done_getting_tensors();
  6477. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  6478. model.mappings.reserve(ml.mappings.size());
  6479. // create the backend buffers
  6480. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  6481. ctx_bufs.reserve(ctx_map.size());
  6482. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  6483. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  6484. model.bufs.reserve(n_max_backend_buffer);
  6485. for (auto & it : ctx_map) {
  6486. ggml_backend_buffer_type_t buft = it.first;
  6487. ggml_context * ctx = it.second;
  6488. llama_buf_map bufs;
  6489. bufs.reserve(n_max_backend_buffer);
  6490. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  6491. // 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
  6492. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  6493. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  6494. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6495. void * addr = nullptr;
  6496. size_t first, last;
  6497. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6498. if (first >= last) {
  6499. continue;
  6500. }
  6501. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  6502. if (buf == nullptr) {
  6503. throw std::runtime_error("unable to allocate backend CPU buffer");
  6504. }
  6505. model.bufs.push_back(buf);
  6506. bufs.emplace(idx, buf);
  6507. #ifdef GGML_USE_CUDA
  6508. if (n_layer >= n_gpu_layers) {
  6509. ggml_backend_cuda_register_host_buffer(
  6510. ggml_backend_buffer_get_base(buf),
  6511. ggml_backend_buffer_get_size(buf));
  6512. }
  6513. #endif
  6514. }
  6515. }
  6516. #ifdef GGML_USE_METAL
  6517. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  6518. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6519. const size_t max_size = ggml_get_max_tensor_size(ctx);
  6520. void * addr = nullptr;
  6521. size_t first, last;
  6522. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  6523. if (first >= last) {
  6524. continue;
  6525. }
  6526. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  6527. if (buf == nullptr) {
  6528. throw std::runtime_error("unable to allocate backend metal buffer");
  6529. }
  6530. model.bufs.push_back(buf);
  6531. bufs.emplace(idx, buf);
  6532. }
  6533. }
  6534. #endif
  6535. else {
  6536. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  6537. if (buf == nullptr) {
  6538. throw std::runtime_error("unable to allocate backend buffer");
  6539. }
  6540. model.bufs.push_back(buf);
  6541. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  6542. model.mlock_bufs.emplace_back(new llama_mlock);
  6543. auto & mlock_buf = model.mlock_bufs.back();
  6544. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  6545. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  6546. }
  6547. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  6548. bufs.emplace(idx, buf);
  6549. }
  6550. }
  6551. if (bufs.empty()) {
  6552. throw std::runtime_error("failed to allocate buffer");
  6553. }
  6554. for (auto & buf : bufs) {
  6555. // indicate that this buffer contains weights
  6556. // 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
  6557. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  6558. }
  6559. ctx_bufs.emplace_back(ctx, bufs);
  6560. }
  6561. if (llama_supports_gpu_offload()) {
  6562. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  6563. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  6564. if (n_gpu_layers > (int) hparams.n_layer) {
  6565. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  6566. }
  6567. const int max_backend_supported_layers = hparams.n_layer + 1;
  6568. const int max_offloadable_layers = hparams.n_layer + 1;
  6569. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  6570. }
  6571. // print memory requirements
  6572. for (ggml_backend_buffer_t buf : model.bufs) {
  6573. 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);
  6574. }
  6575. // populate tensors_by_name
  6576. for (ggml_context * ctx : model.ctxs) {
  6577. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  6578. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  6579. }
  6580. }
  6581. // load tensor data
  6582. for (auto & it : ctx_bufs) {
  6583. ggml_context * ctx = it.first;
  6584. auto & bufs = it.second;
  6585. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  6586. return false;
  6587. }
  6588. }
  6589. if (use_mmap_buffer) {
  6590. for (auto & mapping : ml.mappings) {
  6591. model.mappings.emplace_back(std::move(mapping));
  6592. }
  6593. }
  6594. // loading time will be recalculate after the first eval, so
  6595. // we take page faults deferred by mmap() into consideration
  6596. model.t_load_us = ggml_time_us() - model.t_start_us;
  6597. return true;
  6598. }
  6599. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  6600. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  6601. try {
  6602. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  6603. model.hparams.vocab_only = params.vocab_only;
  6604. try {
  6605. llm_load_arch(ml, model);
  6606. } catch(const std::exception & e) {
  6607. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  6608. }
  6609. try {
  6610. llm_load_hparams(ml, model);
  6611. } catch(const std::exception & e) {
  6612. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  6613. }
  6614. try {
  6615. llm_load_vocab(ml, model);
  6616. } catch(const std::exception & e) {
  6617. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  6618. }
  6619. llm_load_print_meta(ml, model);
  6620. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  6621. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  6622. throw std::runtime_error("vocab size mismatch");
  6623. }
  6624. if (params.vocab_only) {
  6625. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  6626. return 0;
  6627. }
  6628. #ifdef GGML_USE_KOMPUTE
  6629. if (params.n_gpu_layers > 0 && (
  6630. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  6631. || !(
  6632. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  6633. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  6634. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  6635. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  6636. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  6637. )
  6638. )) {
  6639. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  6640. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  6641. params.n_gpu_layers = 0;
  6642. }
  6643. #endif
  6644. if (!llm_load_tensors(
  6645. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  6646. params.progress_callback, params.progress_callback_user_data
  6647. )) {
  6648. return -2;
  6649. }
  6650. } catch (const std::exception & err) {
  6651. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  6652. return -1;
  6653. }
  6654. return 0;
  6655. }
  6656. //
  6657. // llm_build
  6658. //
  6659. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  6660. enum llm_ffn_op_type {
  6661. LLM_FFN_SILU,
  6662. LLM_FFN_GELU,
  6663. LLM_FFN_RELU,
  6664. LLM_FFN_RELU_SQR,
  6665. LLM_FFN_SWIGLU,
  6666. };
  6667. enum llm_ffn_gate_type {
  6668. LLM_FFN_SEQ,
  6669. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  6670. };
  6671. enum llm_norm_type {
  6672. LLM_NORM,
  6673. LLM_NORM_RMS,
  6674. };
  6675. static struct ggml_tensor * llm_build_inp_embd(
  6676. struct ggml_context * ctx,
  6677. struct llama_context & lctx,
  6678. const llama_hparams & hparams,
  6679. const llama_batch & batch,
  6680. struct ggml_tensor * tok_embd,
  6681. const llm_build_cb & cb) {
  6682. const int64_t n_embd = hparams.n_embd;
  6683. struct ggml_tensor * inpL;
  6684. if (batch.token) {
  6685. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  6686. cb(lctx.inp_tokens, "inp_tokens", -1);
  6687. ggml_set_input(lctx.inp_tokens);
  6688. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  6689. } else {
  6690. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  6691. inpL = lctx.inp_embd;
  6692. ggml_set_input(lctx.inp_embd);
  6693. }
  6694. cb(inpL, "inp_embd", -1);
  6695. return inpL;
  6696. }
  6697. static void llm_build_kv_store(
  6698. struct ggml_context * ctx,
  6699. const llama_hparams & hparams,
  6700. const llama_cparams & cparams,
  6701. const llama_kv_cache & kv,
  6702. struct ggml_cgraph * graph,
  6703. struct ggml_tensor * k_cur,
  6704. struct ggml_tensor * v_cur,
  6705. int32_t n_tokens,
  6706. int32_t kv_head,
  6707. const llm_build_cb & cb,
  6708. int64_t il) {
  6709. const int64_t n_ctx = cparams.n_ctx;
  6710. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  6711. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  6712. GGML_ASSERT(kv.size == n_ctx);
  6713. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  6714. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  6715. cb(k_cache_view, "k_cache_view", il);
  6716. // note: storing RoPE-ed version of K in the KV cache
  6717. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  6718. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  6719. struct ggml_tensor * v_cache_view = nullptr;
  6720. if (cparams.flash_attn) {
  6721. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  6722. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  6723. } else {
  6724. // note: the V cache is transposed when not using flash attention
  6725. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  6726. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  6727. (kv_head)*ggml_element_size(kv.v_l[il]));
  6728. v_cur = ggml_transpose(ctx, v_cur);
  6729. }
  6730. cb(v_cache_view, "v_cache_view", il);
  6731. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  6732. }
  6733. // do mat_mul, while optionally apply lora
  6734. static struct ggml_tensor * llm_build_lora_mm(
  6735. struct llama_context & lctx,
  6736. struct ggml_context * ctx0,
  6737. struct ggml_tensor * w,
  6738. struct ggml_tensor * cur) {
  6739. struct ggml_tensor * res = ggml_mul_mat(ctx0, w, cur);
  6740. for (auto & it : lctx.lora_adapters) {
  6741. struct llama_lora_weight * lora = it.first->get_weight(w);
  6742. if (lora == nullptr) {
  6743. continue;
  6744. }
  6745. const float alpha = it.first->alpha;
  6746. const float rank = (float) lora->b->ne[0];
  6747. const float scale = alpha ? it.second * alpha / rank : it.second;
  6748. struct ggml_tensor * ab_cur = ggml_mul_mat(
  6749. ctx0, lora->b,
  6750. ggml_mul_mat(ctx0, lora->a, cur)
  6751. );
  6752. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6753. res = ggml_add(ctx0, res, ab_cur);
  6754. }
  6755. return res;
  6756. }
  6757. // do mat_mul_id, while optionally apply lora
  6758. static struct ggml_tensor * llm_build_lora_mm_id(
  6759. struct llama_context & lctx,
  6760. struct ggml_context * ctx0,
  6761. struct ggml_tensor * w, // struct ggml_tensor * as
  6762. struct ggml_tensor * cur, // struct ggml_tensor * b
  6763. struct ggml_tensor * ids) {
  6764. struct ggml_tensor * res = ggml_mul_mat_id(ctx0, w, cur, ids);
  6765. for (auto & it : lctx.lora_adapters) {
  6766. struct llama_lora_weight * lora = it.first->get_weight(w);
  6767. if (lora == nullptr) {
  6768. continue;
  6769. }
  6770. const float alpha = it.first->alpha;
  6771. const float rank = (float) lora->b->ne[0];
  6772. const float scale = alpha ? it.second * alpha / rank : it.second;
  6773. struct ggml_tensor * ab_cur = ggml_mul_mat_id(
  6774. ctx0, lora->b,
  6775. ggml_mul_mat_id(ctx0, lora->a, cur, ids),
  6776. ids
  6777. );
  6778. ab_cur = ggml_scale(ctx0, ab_cur, scale);
  6779. res = ggml_add(ctx0, res, ab_cur);
  6780. }
  6781. return res;
  6782. }
  6783. static struct ggml_tensor * llm_build_norm(
  6784. struct ggml_context * ctx,
  6785. struct ggml_tensor * cur,
  6786. const llama_hparams & hparams,
  6787. struct ggml_tensor * mw,
  6788. struct ggml_tensor * mb,
  6789. llm_norm_type type,
  6790. const llm_build_cb & cb,
  6791. int il) {
  6792. switch (type) {
  6793. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  6794. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  6795. }
  6796. if (mw || mb) {
  6797. cb(cur, "norm", il);
  6798. }
  6799. if (mw) {
  6800. cur = ggml_mul(ctx, cur, mw);
  6801. if (mb) {
  6802. cb(cur, "norm_w", il);
  6803. }
  6804. }
  6805. if (mb) {
  6806. cur = ggml_add(ctx, cur, mb);
  6807. }
  6808. return cur;
  6809. }
  6810. static struct ggml_tensor * llm_build_ffn(
  6811. struct ggml_context * ctx,
  6812. struct llama_context & lctx,
  6813. struct ggml_tensor * cur,
  6814. struct ggml_tensor * up,
  6815. struct ggml_tensor * up_b,
  6816. struct ggml_tensor * up_s,
  6817. struct ggml_tensor * gate,
  6818. struct ggml_tensor * gate_b,
  6819. struct ggml_tensor * gate_s,
  6820. struct ggml_tensor * down,
  6821. struct ggml_tensor * down_b,
  6822. struct ggml_tensor * down_s,
  6823. struct ggml_tensor * act_scales,
  6824. llm_ffn_op_type type_op,
  6825. llm_ffn_gate_type type_gate,
  6826. const llm_build_cb & cb,
  6827. int il) {
  6828. struct ggml_tensor * tmp = up ? llm_build_lora_mm(lctx, ctx, up, cur) : cur;
  6829. cb(tmp, "ffn_up", il);
  6830. if (up_b) {
  6831. tmp = ggml_add(ctx, tmp, up_b);
  6832. cb(tmp, "ffn_up_b", il);
  6833. }
  6834. if (up_s) {
  6835. tmp = ggml_mul(ctx, tmp, up_s);
  6836. cb(tmp, "ffn_up_s", il);
  6837. }
  6838. if (gate) {
  6839. switch (type_gate) {
  6840. case LLM_FFN_SEQ:
  6841. {
  6842. cur = llm_build_lora_mm(lctx, ctx, gate, tmp);
  6843. cb(cur, "ffn_gate", il);
  6844. } break;
  6845. case LLM_FFN_PAR:
  6846. {
  6847. cur = llm_build_lora_mm(lctx, ctx, gate, cur);
  6848. cb(cur, "ffn_gate", il);
  6849. } break;
  6850. }
  6851. if (gate_b) {
  6852. cur = ggml_add(ctx, cur, gate_b);
  6853. cb(cur, "ffn_gate_b", il);
  6854. }
  6855. if (gate_s) {
  6856. cur = ggml_mul(ctx, cur, gate_s);
  6857. cb(cur, "ffn_gate_s", il);
  6858. }
  6859. } else {
  6860. cur = tmp;
  6861. }
  6862. switch (type_op) {
  6863. case LLM_FFN_SILU:
  6864. {
  6865. cur = ggml_silu(ctx, cur);
  6866. cb(cur, "ffn_silu", il);
  6867. } break;
  6868. case LLM_FFN_GELU:
  6869. {
  6870. cur = ggml_gelu(ctx, cur);
  6871. cb(cur, "ffn_gelu", il);
  6872. if (act_scales != NULL) {
  6873. cur = ggml_div(ctx, cur, act_scales);
  6874. cb(cur, "ffn_act", il);
  6875. }
  6876. } break;
  6877. case LLM_FFN_RELU:
  6878. {
  6879. cur = ggml_relu(ctx, cur);
  6880. cb(cur, "ffn_relu", il);
  6881. } break;
  6882. case LLM_FFN_RELU_SQR:
  6883. {
  6884. cur = ggml_relu(ctx, cur);
  6885. cb(cur, "ffn_relu", il);
  6886. cur = ggml_sqr(ctx, cur);
  6887. cb(cur, "ffn_sqr(relu)", il);
  6888. } break;
  6889. case LLM_FFN_SWIGLU:
  6890. {
  6891. // Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  6892. int64_t split_point = cur->ne[0] / 2;
  6893. struct ggml_tensor * x0 = ggml_cont(ctx, ggml_view_2d(ctx, cur, split_point, cur->ne[1], cur->nb[1], 0));
  6894. 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)));
  6895. x0 = ggml_silu(ctx, x0);
  6896. cb(cur, "ffn_silu", il);
  6897. cur = ggml_mul(ctx, x0, x1);
  6898. cb(cur, "ffn_mul", il);
  6899. } break;
  6900. }
  6901. if (type_gate == LLM_FFN_PAR) {
  6902. cur = ggml_mul(ctx, cur, tmp);
  6903. cb(cur, "ffn_gate_par", il);
  6904. }
  6905. if (down) {
  6906. cur = llm_build_lora_mm(lctx, ctx, down, cur);
  6907. }
  6908. if (down_b) {
  6909. cb(cur, "ffn_down", il);
  6910. }
  6911. if (down_b) {
  6912. cur = ggml_add(ctx, cur, down_b);
  6913. }
  6914. if (down_s) {
  6915. cur = ggml_mul(ctx, cur, down_s);
  6916. cb(cur, "ffn_down_s", il);
  6917. }
  6918. return cur;
  6919. }
  6920. static struct ggml_tensor * llm_build_moe_ffn(
  6921. struct ggml_context * ctx,
  6922. struct llama_context & lctx,
  6923. struct ggml_tensor * cur,
  6924. struct ggml_tensor * gate_inp,
  6925. struct ggml_tensor * up_exps,
  6926. struct ggml_tensor * gate_exps,
  6927. struct ggml_tensor * down_exps,
  6928. int64_t n_expert,
  6929. int64_t n_expert_used,
  6930. llm_ffn_op_type type_op,
  6931. bool norm_w,
  6932. bool scale_w,
  6933. float w_scale,
  6934. const llm_build_cb & cb,
  6935. int il) {
  6936. int64_t n_embd = cur->ne[0];
  6937. int64_t n_tokens = cur->ne[1];
  6938. ggml_tensor * logits = llm_build_lora_mm(lctx, ctx, gate_inp, cur); // [n_expert, n_tokens]
  6939. cb(logits, "ffn_moe_logits", il);
  6940. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  6941. cb(probs, "ffn_moe_probs", il);
  6942. // select experts
  6943. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  6944. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  6945. cb(selected_experts, "ffn_moe_topk", il);
  6946. ggml_tensor * weights = ggml_get_rows(ctx,
  6947. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  6948. cb(weights, "ffn_moe_weights", il);
  6949. if (norm_w) {
  6950. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  6951. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  6952. cb(weights_sum, "ffn_moe_weights_sum", il);
  6953. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  6954. cb(weights, "ffn_moe_weights_norm", il);
  6955. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  6956. }
  6957. if (scale_w) {
  6958. weights = ggml_scale(ctx, weights, w_scale);
  6959. cb(weights, "ffn_moe_weights_scaled", il);
  6960. }
  6961. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  6962. ggml_tensor * up = llm_build_lora_mm_id(lctx, ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6963. cb(up, "ffn_moe_up", il);
  6964. ggml_tensor * gate = llm_build_lora_mm_id(lctx, ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  6965. cb(gate, "ffn_moe_gate", il);
  6966. switch (type_op) {
  6967. case LLM_FFN_SILU:
  6968. {
  6969. gate = ggml_silu(ctx, gate);
  6970. cb(gate, "ffn_moe_silu", il);
  6971. } break;
  6972. case LLM_FFN_GELU:
  6973. {
  6974. gate = ggml_gelu(ctx, gate);
  6975. cb(gate, "ffn_moe_gelu", il);
  6976. } break;
  6977. default:
  6978. GGML_ABORT("fatal error");
  6979. }
  6980. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  6981. cb(par, "ffn_moe_gate_par", il);
  6982. ggml_tensor * experts = llm_build_lora_mm_id(lctx, ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  6983. cb(experts, "ffn_moe_down", il);
  6984. experts = ggml_mul(ctx, experts, weights);
  6985. // aggregate experts
  6986. ggml_tensor * moe_out = nullptr;
  6987. for (int i = 0; i < n_expert_used; ++i) {
  6988. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  6989. experts->nb[2], i*experts->nb[1]);
  6990. if (i == 0) {
  6991. moe_out = cur_expert;
  6992. } else {
  6993. moe_out = ggml_add(ctx, moe_out, cur_expert);
  6994. }
  6995. }
  6996. if (n_expert_used == 1) {
  6997. // avoid returning a non-contiguous tensor
  6998. moe_out = ggml_cont(ctx, moe_out);
  6999. }
  7000. return moe_out;
  7001. }
  7002. static struct ggml_tensor * llm_build_kqv(
  7003. struct ggml_context * ctx,
  7004. struct llama_context & lctx,
  7005. const llama_kv_cache & kv,
  7006. struct ggml_cgraph * graph,
  7007. struct ggml_tensor * wo,
  7008. struct ggml_tensor * wo_b,
  7009. struct ggml_tensor * q_cur,
  7010. struct ggml_tensor * kq_mask,
  7011. int32_t n_tokens,
  7012. int32_t n_kv,
  7013. float kq_scale,
  7014. const llm_build_cb & cb,
  7015. int il) {
  7016. const llama_model & model = lctx.model;
  7017. const llama_hparams & hparams = lctx.model.hparams;
  7018. const llama_cparams & cparams = lctx.cparams;
  7019. const int64_t n_ctx = cparams.n_ctx;
  7020. const int64_t n_head = hparams.n_head(il);
  7021. const int64_t n_head_kv = hparams.n_head_kv(il);
  7022. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7023. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7024. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  7025. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7026. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  7027. cb(q, "q", il);
  7028. struct ggml_tensor * k =
  7029. ggml_view_3d(ctx, kv.k_l[il],
  7030. n_embd_head_k, n_kv, n_head_kv,
  7031. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  7032. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  7033. 0);
  7034. cb(k, "k", il);
  7035. struct ggml_tensor * cur;
  7036. if (cparams.flash_attn) {
  7037. GGML_UNUSED(model);
  7038. GGML_UNUSED(n_ctx);
  7039. // split cached v into n_head heads (not transposed)
  7040. struct ggml_tensor * v =
  7041. ggml_view_3d(ctx, kv.v_l[il],
  7042. n_embd_head_v, n_kv, n_head_kv,
  7043. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  7044. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  7045. 0);
  7046. cb(v, "v", il);
  7047. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7048. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX) {
  7049. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  7050. }
  7051. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  7052. } else {
  7053. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  7054. cb(kq, "kq", il);
  7055. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX || model.arch == LLM_ARCH_QWEN2) {
  7056. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  7057. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  7058. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7059. }
  7060. if (model.arch == LLM_ARCH_GROK) {
  7061. // need to do the following:
  7062. // multiply by attn_output_multiplyer of 0.08838834764831845
  7063. // and then :
  7064. // kq = 30 * tanh(kq / 30)
  7065. // before the softmax below
  7066. //try from phi2
  7067. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  7068. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  7069. kq = ggml_scale(ctx, kq, 30);
  7070. }
  7071. if (hparams.attn_soft_cap) {
  7072. kq = ggml_scale(ctx, kq, 1.0f / hparams.f_attn_logit_softcapping);
  7073. kq = ggml_tanh(ctx, kq);
  7074. kq = ggml_scale(ctx, kq, hparams.f_attn_logit_softcapping);
  7075. }
  7076. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  7077. cb(kq, "kq_soft_max_ext", il);
  7078. GGML_ASSERT(kv.size == n_ctx);
  7079. // split cached v into n_head heads
  7080. struct ggml_tensor * v =
  7081. ggml_view_3d(ctx, kv.v_l[il],
  7082. n_kv, n_embd_head_v, n_head_kv,
  7083. ggml_element_size(kv.v_l[il])*n_ctx,
  7084. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  7085. 0);
  7086. cb(v, "v", il);
  7087. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  7088. cb(kqv, "kqv", il);
  7089. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  7090. cb(kqv_merged, "kqv_merged", il);
  7091. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  7092. cb(cur, "kqv_merged_cont", il);
  7093. }
  7094. ggml_build_forward_expand(graph, cur);
  7095. if (wo) {
  7096. cur = llm_build_lora_mm(lctx, ctx, wo, cur);
  7097. }
  7098. if (wo_b) {
  7099. cb(cur, "kqv_wo", il);
  7100. }
  7101. if (wo_b) {
  7102. cur = ggml_add(ctx, cur, wo_b);
  7103. }
  7104. return cur;
  7105. }
  7106. static struct ggml_tensor * llm_build_kv(
  7107. struct ggml_context * ctx,
  7108. struct llama_context & lctx,
  7109. const llama_kv_cache & kv,
  7110. struct ggml_cgraph * graph,
  7111. struct ggml_tensor * wo,
  7112. struct ggml_tensor * wo_b,
  7113. struct ggml_tensor * k_cur,
  7114. struct ggml_tensor * v_cur,
  7115. struct ggml_tensor * q_cur,
  7116. struct ggml_tensor * kq_mask,
  7117. int32_t n_tokens,
  7118. int32_t kv_head,
  7119. int32_t n_kv,
  7120. float kq_scale,
  7121. const llm_build_cb & cb,
  7122. int il) {
  7123. const llama_hparams & hparams = lctx.model.hparams;
  7124. const llama_cparams & cparams = lctx.cparams;
  7125. // these nodes are added to the graph together so that they are not reordered
  7126. // by doing so, the number of splits in the graph is reduced
  7127. ggml_build_forward_expand(graph, q_cur);
  7128. ggml_build_forward_expand(graph, k_cur);
  7129. ggml_build_forward_expand(graph, v_cur);
  7130. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  7131. struct ggml_tensor * cur;
  7132. cur = llm_build_kqv(ctx, lctx, kv, graph, wo, wo_b,
  7133. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  7134. cb(cur, "kqv_out", il);
  7135. return cur;
  7136. }
  7137. struct llm_build_context {
  7138. const llama_model & model;
  7139. llama_context & lctx;
  7140. const llama_hparams & hparams;
  7141. const llama_cparams & cparams;
  7142. const llama_batch & batch;
  7143. const llama_kv_cache & kv_self;
  7144. const int64_t n_embd;
  7145. const int64_t n_layer;
  7146. const int64_t n_rot;
  7147. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  7148. const int64_t n_head;
  7149. const int64_t n_head_kv;
  7150. const int64_t n_embd_head_k;
  7151. const int64_t n_embd_k_gqa;
  7152. const int64_t n_embd_head_v;
  7153. const int64_t n_embd_v_gqa;
  7154. const int64_t n_expert;
  7155. const int64_t n_expert_used;
  7156. const float freq_base;
  7157. const float freq_scale;
  7158. const float ext_factor;
  7159. const float attn_factor;
  7160. const float beta_fast;
  7161. const float beta_slow;
  7162. const float norm_eps;
  7163. const float norm_rms_eps;
  7164. const int32_t n_tokens;
  7165. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  7166. const int32_t n_outputs;
  7167. const int32_t n_outputs_enc;
  7168. const int32_t kv_head; // index of where we store new KV data in the cache
  7169. const int32_t n_ctx_orig;
  7170. const bool flash_attn;
  7171. const enum llama_pooling_type pooling_type;
  7172. const enum llama_rope_type rope_type;
  7173. const llm_build_cb & cb;
  7174. std::vector<uint8_t> & buf_compute_meta;
  7175. struct ggml_context * ctx0 = nullptr;
  7176. // TODO: consider making the entire interface noexcept
  7177. llm_build_context(
  7178. llama_context & lctx,
  7179. const llama_batch & batch,
  7180. const llm_build_cb & cb,
  7181. bool worst_case) :
  7182. model (lctx.model),
  7183. lctx (lctx),
  7184. hparams (model.hparams),
  7185. cparams (lctx.cparams),
  7186. batch (batch),
  7187. kv_self (lctx.kv_self),
  7188. n_embd (hparams.n_embd),
  7189. n_layer (hparams.n_layer),
  7190. n_rot (hparams.n_rot),
  7191. n_ctx (cparams.n_ctx),
  7192. n_head (hparams.n_head()),
  7193. n_head_kv (hparams.n_head_kv()),
  7194. n_embd_head_k (hparams.n_embd_head_k),
  7195. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  7196. n_embd_head_v (hparams.n_embd_head_v),
  7197. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  7198. n_expert (hparams.n_expert),
  7199. n_expert_used (hparams.n_expert_used),
  7200. freq_base (cparams.rope_freq_base),
  7201. freq_scale (cparams.rope_freq_scale),
  7202. ext_factor (cparams.yarn_ext_factor),
  7203. attn_factor (cparams.yarn_attn_factor),
  7204. beta_fast (cparams.yarn_beta_fast),
  7205. beta_slow (cparams.yarn_beta_slow),
  7206. norm_eps (hparams.f_norm_eps),
  7207. norm_rms_eps (hparams.f_norm_rms_eps),
  7208. n_tokens (batch.n_tokens),
  7209. n_kv (worst_case ? kv_self.size : kv_self.n),
  7210. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  7211. n_outputs_enc (worst_case ? n_tokens : lctx.embd_enc.size() / hparams.n_embd),
  7212. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  7213. n_ctx_orig (cparams.n_ctx_orig_yarn),
  7214. flash_attn (cparams.flash_attn),
  7215. pooling_type (cparams.pooling_type),
  7216. rope_type (hparams.rope_type),
  7217. cb (cb),
  7218. buf_compute_meta (lctx.buf_compute_meta) {
  7219. // all initializations should be done in init()
  7220. }
  7221. void init() {
  7222. struct ggml_init_params params = {
  7223. /*.mem_size =*/ buf_compute_meta.size(),
  7224. /*.mem_buffer =*/ buf_compute_meta.data(),
  7225. /*.no_alloc =*/ true,
  7226. };
  7227. ctx0 = ggml_init(params);
  7228. lctx.inp_tokens = nullptr;
  7229. lctx.inp_embd = nullptr;
  7230. lctx.inp_pos = nullptr;
  7231. lctx.inp_out_ids = nullptr;
  7232. lctx.inp_KQ_mask = nullptr;
  7233. lctx.inp_KQ_mask_swa = nullptr;
  7234. lctx.inp_K_shift = nullptr;
  7235. lctx.inp_mean = nullptr;
  7236. lctx.inp_cls = nullptr;
  7237. lctx.inp_s_copy = nullptr;
  7238. lctx.inp_s_mask = nullptr;
  7239. lctx.inp_s_seq = nullptr;
  7240. lctx.inp_pos_bucket = nullptr;
  7241. lctx.inp_embd_enc = nullptr;
  7242. lctx.inp_KQ_mask_cross = nullptr;
  7243. }
  7244. void free() {
  7245. if (ctx0) {
  7246. ggml_free(ctx0);
  7247. ctx0 = nullptr;
  7248. }
  7249. }
  7250. struct ggml_cgraph * build_k_shift() {
  7251. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7252. GGML_ASSERT(kv_self.size == n_ctx);
  7253. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  7254. cb(lctx.inp_K_shift, "K_shift", -1);
  7255. ggml_set_input(lctx.inp_K_shift);
  7256. for (int il = 0; il < n_layer; ++il) {
  7257. const int64_t n_head_kv = hparams.n_head_kv(il);
  7258. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7259. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7260. struct ggml_tensor * tmp =
  7261. // we rotate only the first n_rot dimensions
  7262. ggml_rope_ext_inplace(ctx0,
  7263. ggml_view_3d(ctx0, kv_self.k_l[il],
  7264. n_embd_head_k, n_head_kv, n_ctx,
  7265. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  7266. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7267. 0),
  7268. lctx.inp_K_shift, rope_factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7269. ext_factor, attn_factor, beta_fast, beta_slow);
  7270. cb(tmp, "K_shifted", il);
  7271. ggml_build_forward_expand(gf, tmp);
  7272. }
  7273. return gf;
  7274. }
  7275. struct ggml_cgraph * build_s_copy() {
  7276. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7277. GGML_ASSERT(kv_self.recurrent);
  7278. struct ggml_tensor * state_copy = build_inp_s_copy();
  7279. for (int il = 0; il < n_layer; ++il) {
  7280. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7281. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7282. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  7283. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  7284. // TODO: name the intermediate tensors with cb()
  7285. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  7286. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  7287. }
  7288. return gf;
  7289. }
  7290. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  7291. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7292. for (uint32_t i = 0; i < ids.size(); ++i) {
  7293. const uint32_t id = ids[i];
  7294. if (i == id || id == ids.size()) {
  7295. continue;
  7296. }
  7297. uint32_t nm = 1;
  7298. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  7299. nm++;
  7300. }
  7301. for (int il = 0; il < n_layer; ++il) {
  7302. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
  7303. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
  7304. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  7305. n_embd_k_gqa, nm,
  7306. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7307. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  7308. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  7309. n_embd_k_gqa, nm,
  7310. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  7311. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  7312. ggml_tensor * view_v_src;
  7313. ggml_tensor * view_v_dst;
  7314. if (flash_attn) {
  7315. // NOTE: the V cache is not transposed when using flash attention
  7316. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7317. n_embd_v_gqa, nm,
  7318. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7319. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  7320. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7321. n_embd_v_gqa, nm,
  7322. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  7323. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  7324. } else {
  7325. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  7326. nm, n_embd_v_gqa,
  7327. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7328. ggml_row_size(kv_self.v_l[il]->type, i));
  7329. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  7330. nm, n_embd_v_gqa,
  7331. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  7332. ggml_row_size(kv_self.v_l[il]->type, id));
  7333. }
  7334. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  7335. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  7336. }
  7337. i += nm - 1;
  7338. }
  7339. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  7340. return gf;
  7341. }
  7342. struct ggml_tensor * build_inp_pos() {
  7343. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7344. cb(lctx.inp_pos, "inp_pos", -1);
  7345. ggml_set_input(lctx.inp_pos);
  7346. return lctx.inp_pos;
  7347. }
  7348. struct ggml_tensor * build_rope_factors(int il) {
  7349. // choose long/short freq factors based on the context size
  7350. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  7351. if (model.layers[il].rope_freqs != nullptr) {
  7352. return model.layers[il].rope_freqs;
  7353. }
  7354. if (n_ctx_pre_seq > hparams.n_ctx_orig_yarn) {
  7355. return model.layers[il].rope_long;
  7356. }
  7357. return model.layers[il].rope_short;
  7358. }
  7359. struct ggml_tensor * build_inp_out_ids() {
  7360. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  7361. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  7362. ggml_set_input(lctx.inp_out_ids);
  7363. return lctx.inp_out_ids;
  7364. }
  7365. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  7366. lctx.inp_KQ_mask = causal
  7367. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7368. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7369. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  7370. ggml_set_input(lctx.inp_KQ_mask);
  7371. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  7372. }
  7373. struct ggml_tensor * build_inp_KQ_mask_swa(bool causal = true) {
  7374. GGML_ASSERT(hparams.n_swa > 0);
  7375. lctx.inp_KQ_mask_swa = causal
  7376. ? ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD))
  7377. : ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7378. cb(lctx.inp_KQ_mask_swa, "KQ_mask_swa", -1);
  7379. ggml_set_input(lctx.inp_KQ_mask_swa);
  7380. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask_swa, GGML_TYPE_F16) : lctx.inp_KQ_mask_swa;
  7381. }
  7382. struct ggml_tensor * build_inp_mean() {
  7383. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  7384. cb(lctx.inp_mean, "inp_mean", -1);
  7385. ggml_set_input(lctx.inp_mean);
  7386. return lctx.inp_mean;
  7387. }
  7388. struct ggml_tensor * build_inp_cls() {
  7389. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  7390. cb(lctx.inp_cls, "inp_cls", -1);
  7391. ggml_set_input(lctx.inp_cls);
  7392. return lctx.inp_cls;
  7393. }
  7394. struct ggml_tensor * build_inp_s_copy() {
  7395. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  7396. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  7397. ggml_set_input(lctx.inp_s_copy);
  7398. return lctx.inp_s_copy;
  7399. }
  7400. struct ggml_tensor * build_inp_s_mask() {
  7401. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  7402. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  7403. ggml_set_input(lctx.inp_s_mask);
  7404. return lctx.inp_s_mask;
  7405. }
  7406. struct ggml_tensor * build_inp_s_seq() {
  7407. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7408. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  7409. ggml_set_input(lctx.inp_s_seq);
  7410. return lctx.inp_s_seq;
  7411. }
  7412. struct ggml_cgraph * append_pooling(struct ggml_cgraph * gf) {
  7413. // find result_norm tensor for input
  7414. struct ggml_tensor * inp = nullptr;
  7415. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  7416. inp = gf->nodes[i];
  7417. if (strcmp(inp->name, "result_norm") == 0 || strcmp(inp->name, "result_embd") == 0) {
  7418. break;
  7419. } else {
  7420. inp = nullptr;
  7421. }
  7422. }
  7423. GGML_ASSERT(inp != nullptr && "missing result_norm/result_embd tensor");
  7424. struct ggml_tensor * cur;
  7425. switch (pooling_type) {
  7426. case LLAMA_POOLING_TYPE_MEAN:
  7427. {
  7428. struct ggml_tensor * inp_mean = build_inp_mean();
  7429. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, inp)), inp_mean);
  7430. } break;
  7431. case LLAMA_POOLING_TYPE_CLS:
  7432. case LLAMA_POOLING_TYPE_LAST:
  7433. {
  7434. struct ggml_tensor * inp_cls = build_inp_cls();
  7435. cur = ggml_get_rows(ctx0, inp, inp_cls);
  7436. } break;
  7437. case LLAMA_POOLING_TYPE_NONE:
  7438. {
  7439. cur = inp;
  7440. } break;
  7441. default:
  7442. {
  7443. GGML_ABORT("unknown pooling type");
  7444. }
  7445. }
  7446. cb(cur, "result_embd_pooled", -1);
  7447. ggml_build_forward_expand(gf, cur);
  7448. return gf;
  7449. }
  7450. struct ggml_tensor * llm_build_pos_bucket(bool causal) {
  7451. if (causal) {
  7452. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  7453. } else {
  7454. lctx.inp_pos_bucket = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_tokens);
  7455. }
  7456. ggml_set_input(lctx.inp_pos_bucket);
  7457. cb(lctx.inp_pos_bucket, "pos_bucket", -1);
  7458. return lctx.inp_pos_bucket;
  7459. }
  7460. struct ggml_tensor * llm_build_pos_bias(struct ggml_tensor * pos_bucket, struct ggml_tensor * attn_rel_b) {
  7461. struct ggml_tensor * pos_bucket_1d = ggml_view_1d(ctx0, pos_bucket, pos_bucket->ne[0] * pos_bucket->ne[1], 0);
  7462. cb(pos_bucket_1d, "pos_bucket_1d", -1);
  7463. struct ggml_tensor * pos_bias = ggml_get_rows(ctx0, attn_rel_b, pos_bucket_1d);
  7464. cb(pos_bias, "pos_bias", -1);
  7465. 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);
  7466. cb(pos_bias, "pos_bias", -1);
  7467. pos_bias = ggml_permute(ctx0, pos_bias, 2, 0, 1, 3);
  7468. cb(pos_bias, "pos_bias", -1);
  7469. pos_bias = ggml_cont(ctx0, pos_bias);
  7470. cb(pos_bias, "pos_bias", -1);
  7471. return pos_bias;
  7472. }
  7473. struct ggml_tensor * llm_build_inp_embd_enc() {
  7474. const int64_t n_embd = hparams.n_embd;
  7475. lctx.inp_embd_enc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, n_outputs_enc);
  7476. ggml_set_input(lctx.inp_embd_enc);
  7477. cb(lctx.inp_embd_enc, "embd_enc", -1);
  7478. return lctx.inp_embd_enc;
  7479. }
  7480. struct ggml_tensor * llm_build_inp_KQ_mask_cross() {
  7481. lctx.inp_KQ_mask_cross = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_outputs_enc, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  7482. ggml_set_input(lctx.inp_KQ_mask_cross);
  7483. cb(lctx.inp_KQ_mask_cross, "KQ_mask_cross", -1);
  7484. return lctx.inp_KQ_mask_cross;
  7485. }
  7486. struct ggml_cgraph * build_llama() {
  7487. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7488. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7489. int32_t n_tokens = this->n_tokens;
  7490. const int64_t n_embd_head = hparams.n_embd_head_v;
  7491. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7492. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7493. struct ggml_tensor * cur;
  7494. struct ggml_tensor * inpL;
  7495. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7496. // inp_pos - contains the positions
  7497. struct ggml_tensor * inp_pos = build_inp_pos();
  7498. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7499. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7500. for (int il = 0; il < n_layer; ++il) {
  7501. struct ggml_tensor * inpSA = inpL;
  7502. // norm
  7503. cur = llm_build_norm(ctx0, inpL, hparams,
  7504. model.layers[il].attn_norm, NULL,
  7505. LLM_NORM_RMS, cb, il);
  7506. cb(cur, "attn_norm", il);
  7507. // self-attention
  7508. {
  7509. // rope freq factors for llama3; may return nullptr for llama2 and other models
  7510. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7511. // compute Q and K and RoPE them
  7512. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7513. cb(Qcur, "Qcur", il);
  7514. if (model.layers[il].bq) {
  7515. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7516. cb(Qcur, "Qcur", il);
  7517. }
  7518. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7519. cb(Kcur, "Kcur", il);
  7520. if (model.layers[il].bk) {
  7521. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7522. cb(Kcur, "Kcur", il);
  7523. }
  7524. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7525. cb(Vcur, "Vcur", il);
  7526. if (model.layers[il].bv) {
  7527. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7528. cb(Vcur, "Vcur", il);
  7529. }
  7530. Qcur = ggml_rope_ext(
  7531. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, rope_factors,
  7532. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7533. ext_factor, attn_factor, beta_fast, beta_slow
  7534. );
  7535. cb(Qcur, "Qcur", il);
  7536. Kcur = ggml_rope_ext(
  7537. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, rope_factors,
  7538. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7539. ext_factor, attn_factor, beta_fast, beta_slow
  7540. );
  7541. cb(Kcur, "Kcur", il);
  7542. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7543. model.layers[il].wo, model.layers[il].bo,
  7544. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7545. }
  7546. if (il == n_layer - 1) {
  7547. // skip computing output for unused tokens
  7548. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7549. n_tokens = n_outputs;
  7550. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7551. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7552. }
  7553. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7554. cb(ffn_inp, "ffn_inp", il);
  7555. // feed-forward network
  7556. if (model.layers[il].ffn_gate_inp == nullptr) {
  7557. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7558. model.layers[il].ffn_norm, NULL,
  7559. LLM_NORM_RMS, cb, il);
  7560. cb(cur, "ffn_norm", il);
  7561. cur = llm_build_ffn(ctx0, lctx, cur,
  7562. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  7563. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  7564. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  7565. NULL,
  7566. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7567. cb(cur, "ffn_out", il);
  7568. } else {
  7569. // MoE branch
  7570. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7571. model.layers[il].ffn_norm, NULL,
  7572. LLM_NORM_RMS, cb, il);
  7573. cb(cur, "ffn_norm", il);
  7574. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7575. model.layers[il].ffn_gate_inp,
  7576. model.layers[il].ffn_up_exps,
  7577. model.layers[il].ffn_gate_exps,
  7578. model.layers[il].ffn_down_exps,
  7579. n_expert, n_expert_used,
  7580. LLM_FFN_SILU, true,
  7581. false, 0.0,
  7582. cb, il);
  7583. cb(cur, "ffn_moe_out", il);
  7584. }
  7585. cur = ggml_add(ctx0, cur, ffn_inp);
  7586. cb(cur, "ffn_out", il);
  7587. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7588. cb(cur, "l_out", il);
  7589. // input for next layer
  7590. inpL = cur;
  7591. }
  7592. cur = inpL;
  7593. cur = llm_build_norm(ctx0, cur, hparams,
  7594. model.output_norm, NULL,
  7595. LLM_NORM_RMS, cb, -1);
  7596. cb(cur, "result_norm", -1);
  7597. // lm_head
  7598. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7599. cb(cur, "result_output", -1);
  7600. ggml_build_forward_expand(gf, cur);
  7601. return gf;
  7602. }
  7603. struct ggml_cgraph * build_baichuan() {
  7604. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7605. const int64_t n_embd_head = hparams.n_embd_head_v;
  7606. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7607. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7608. struct ggml_tensor * cur;
  7609. struct ggml_tensor * inpL;
  7610. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7611. // inp_pos - contains the positions
  7612. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  7613. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7614. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7615. for (int il = 0; il < n_layer; ++il) {
  7616. struct ggml_tensor * inpSA = inpL;
  7617. cur = llm_build_norm(ctx0, inpL, hparams,
  7618. model.layers[il].attn_norm, NULL,
  7619. LLM_NORM_RMS, cb, il);
  7620. cb(cur, "attn_norm", il);
  7621. // self-attention
  7622. {
  7623. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7624. cb(Qcur, "Qcur", il);
  7625. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7626. cb(Kcur, "Kcur", il);
  7627. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7628. cb(Vcur, "Vcur", il);
  7629. switch (model.type) {
  7630. case MODEL_7B:
  7631. Qcur = ggml_rope_ext(
  7632. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7633. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7634. ext_factor, attn_factor, beta_fast, beta_slow
  7635. );
  7636. Kcur = ggml_rope_ext(
  7637. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7638. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7639. ext_factor, attn_factor, beta_fast, beta_slow
  7640. );
  7641. break;
  7642. case MODEL_13B:
  7643. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  7644. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  7645. break;
  7646. default:
  7647. GGML_ABORT("fatal error");
  7648. }
  7649. cb(Qcur, "Qcur", il);
  7650. cb(Kcur, "Kcur", il);
  7651. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7652. model.layers[il].wo, NULL,
  7653. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7654. }
  7655. if (il == n_layer - 1) {
  7656. // skip computing output for unused tokens
  7657. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7658. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7659. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7660. }
  7661. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7662. cb(ffn_inp, "ffn_inp", il);
  7663. // feed-forward network
  7664. {
  7665. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7666. model.layers[il].ffn_norm, NULL,
  7667. LLM_NORM_RMS, cb, il);
  7668. cb(cur, "ffn_norm", il);
  7669. cur = llm_build_ffn(ctx0, lctx, cur,
  7670. model.layers[il].ffn_up, NULL, NULL,
  7671. model.layers[il].ffn_gate, NULL, NULL,
  7672. model.layers[il].ffn_down, NULL, NULL,
  7673. NULL,
  7674. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7675. cb(cur, "ffn_out", il);
  7676. }
  7677. cur = ggml_add(ctx0, cur, ffn_inp);
  7678. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7679. cb(cur, "l_out", il);
  7680. // input for next layer
  7681. inpL = cur;
  7682. }
  7683. cur = inpL;
  7684. cur = llm_build_norm(ctx0, cur, hparams,
  7685. model.output_norm, NULL,
  7686. LLM_NORM_RMS, cb, -1);
  7687. cb(cur, "result_norm", -1);
  7688. // lm_head
  7689. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7690. cb(cur, "result_output", -1);
  7691. ggml_build_forward_expand(gf, cur);
  7692. return gf;
  7693. }
  7694. struct ggml_cgraph * build_xverse() {
  7695. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7696. const int64_t n_embd_head = hparams.n_embd_head_v;
  7697. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7698. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7699. struct ggml_tensor * cur;
  7700. struct ggml_tensor * inpL;
  7701. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7702. // inp_pos - contains the positions
  7703. struct ggml_tensor * inp_pos = build_inp_pos();
  7704. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7705. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7706. for (int il = 0; il < n_layer; ++il) {
  7707. struct ggml_tensor * inpSA = inpL;
  7708. cur = llm_build_norm(ctx0, inpL, hparams,
  7709. model.layers[il].attn_norm, NULL,
  7710. LLM_NORM_RMS, cb, il);
  7711. cb(cur, "attn_norm", il);
  7712. // self-attention
  7713. {
  7714. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7715. cb(Qcur, "Qcur", il);
  7716. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7717. cb(Kcur, "Kcur", il);
  7718. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7719. cb(Vcur, "Vcur", il);
  7720. Qcur = ggml_rope_ext(
  7721. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7722. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7723. ext_factor, attn_factor, beta_fast, beta_slow
  7724. );
  7725. cb(Qcur, "Qcur", il);
  7726. Kcur = ggml_rope_ext(
  7727. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7728. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7729. ext_factor, attn_factor, beta_fast, beta_slow
  7730. );
  7731. cb(Kcur, "Kcur", il);
  7732. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7733. model.layers[il].wo, NULL,
  7734. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7735. }
  7736. if (il == n_layer - 1) {
  7737. // skip computing output for unused tokens
  7738. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7739. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7740. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7741. }
  7742. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7743. cb(ffn_inp, "ffn_inp", il);
  7744. // feed-forward network
  7745. {
  7746. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7747. model.layers[il].ffn_norm, NULL,
  7748. LLM_NORM_RMS, cb, il);
  7749. cb(cur, "ffn_norm", il);
  7750. cur = llm_build_ffn(ctx0, lctx, cur,
  7751. model.layers[il].ffn_up, NULL, NULL,
  7752. model.layers[il].ffn_gate, NULL, NULL,
  7753. model.layers[il].ffn_down, NULL, NULL,
  7754. NULL,
  7755. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7756. cb(cur, "ffn_out", il);
  7757. }
  7758. cur = ggml_add(ctx0, cur, ffn_inp);
  7759. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7760. cb(cur, "l_out", il);
  7761. // input for next layer
  7762. inpL = cur;
  7763. }
  7764. cur = inpL;
  7765. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  7766. cb(cur, "result_norm", -1);
  7767. // lm_head
  7768. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7769. cb(cur, "result_output", -1);
  7770. ggml_build_forward_expand(gf, cur);
  7771. return gf;
  7772. }
  7773. struct ggml_cgraph * build_falcon() {
  7774. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7775. const int64_t n_embd_head = hparams.n_embd_head_v;
  7776. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7777. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7778. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7779. struct ggml_tensor * cur;
  7780. struct ggml_tensor * inpL;
  7781. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7782. // inp_pos - contains the positions
  7783. struct ggml_tensor * inp_pos = build_inp_pos();
  7784. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7785. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7786. for (int il = 0; il < n_layer; ++il) {
  7787. struct ggml_tensor * attn_norm;
  7788. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  7789. model.layers[il].attn_norm,
  7790. model.layers[il].attn_norm_b,
  7791. LLM_NORM, cb, il);
  7792. cb(attn_norm, "attn_norm", il);
  7793. // self-attention
  7794. {
  7795. if (model.layers[il].attn_norm_2) {
  7796. // Falcon-40B
  7797. cur = llm_build_norm(ctx0, inpL, hparams,
  7798. model.layers[il].attn_norm_2,
  7799. model.layers[il].attn_norm_2_b,
  7800. LLM_NORM, cb, il);
  7801. cb(cur, "attn_norm_2", il);
  7802. } else {
  7803. cur = attn_norm;
  7804. }
  7805. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  7806. cb(cur, "wqkv", il);
  7807. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7808. 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)));
  7809. 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)));
  7810. cb(Qcur, "Qcur", il);
  7811. cb(Kcur, "Kcur", il);
  7812. cb(Vcur, "Vcur", il);
  7813. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7814. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7815. // using mode = 2 for neox mode
  7816. Qcur = ggml_rope_ext(
  7817. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7818. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7819. );
  7820. cb(Qcur, "Qcur", il);
  7821. Kcur = ggml_rope_ext(
  7822. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  7823. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7824. );
  7825. cb(Kcur, "Kcur", il);
  7826. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7827. model.layers[il].wo, NULL,
  7828. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7829. }
  7830. if (il == n_layer - 1) {
  7831. // skip computing output for unused tokens
  7832. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7833. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7834. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7835. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  7836. }
  7837. struct ggml_tensor * ffn_inp = cur;
  7838. // feed forward
  7839. {
  7840. cur = llm_build_ffn(ctx0, lctx, attn_norm, // !! use the attn norm, not the result
  7841. model.layers[il].ffn_up, NULL, NULL,
  7842. NULL, NULL, NULL,
  7843. model.layers[il].ffn_down, NULL, NULL,
  7844. NULL,
  7845. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7846. cb(cur, "ffn_out", il);
  7847. }
  7848. cur = ggml_add(ctx0, cur, ffn_inp);
  7849. cur = ggml_add(ctx0, cur, inpL);
  7850. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7851. cb(cur, "l_out", il);
  7852. // input for next layer
  7853. inpL = cur;
  7854. }
  7855. cur = inpL;
  7856. // norm
  7857. cur = llm_build_norm(ctx0, cur, hparams,
  7858. model.output_norm,
  7859. model.output_norm_b,
  7860. LLM_NORM, cb, -1);
  7861. cb(cur, "result_norm", -1);
  7862. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7863. cb(cur, "result_output", -1);
  7864. ggml_build_forward_expand(gf, cur);
  7865. return gf;
  7866. }
  7867. struct ggml_cgraph * build_grok() {
  7868. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7869. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7870. int32_t n_tokens = this->n_tokens;
  7871. const int64_t n_embd_head = hparams.n_embd_head_v;
  7872. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7873. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7874. struct ggml_tensor * cur;
  7875. struct ggml_tensor * inpL;
  7876. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7877. // multiply by embedding_multiplier_scale of 78.38367176906169
  7878. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  7879. // inp_pos - contains the positions
  7880. struct ggml_tensor * inp_pos = build_inp_pos();
  7881. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7882. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7883. for (int il = 0; il < n_layer; ++il) {
  7884. struct ggml_tensor * inpSA = inpL;
  7885. // norm
  7886. cur = llm_build_norm(ctx0, inpL, hparams,
  7887. model.layers[il].attn_norm, NULL,
  7888. LLM_NORM_RMS, cb, il);
  7889. cb(cur, "attn_norm", il);
  7890. // self-attention
  7891. {
  7892. // compute Q and K and RoPE them
  7893. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  7894. cb(Qcur, "Qcur", il);
  7895. if (model.layers[il].bq) {
  7896. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7897. cb(Qcur, "Qcur", il);
  7898. }
  7899. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  7900. cb(Kcur, "Kcur", il);
  7901. if (model.layers[il].bk) {
  7902. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7903. cb(Kcur, "Kcur", il);
  7904. }
  7905. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  7906. cb(Vcur, "Vcur", il);
  7907. if (model.layers[il].bv) {
  7908. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7909. cb(Vcur, "Vcur", il);
  7910. }
  7911. Qcur = ggml_rope_ext(
  7912. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7913. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7914. ext_factor, attn_factor, beta_fast, beta_slow
  7915. );
  7916. cb(Qcur, "Qcur", il);
  7917. Kcur = ggml_rope_ext(
  7918. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7919. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  7920. ext_factor, attn_factor, beta_fast, beta_slow
  7921. );
  7922. cb(Kcur, "Kcur", il);
  7923. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  7924. model.layers[il].wo, model.layers[il].bo,
  7925. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7926. }
  7927. if (il == n_layer - 1) {
  7928. // skip computing output for unused tokens
  7929. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7930. n_tokens = n_outputs;
  7931. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7932. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7933. }
  7934. // Grok
  7935. // if attn_out_norm is present then apply it before adding the input
  7936. if (model.layers[il].attn_out_norm) {
  7937. cur = llm_build_norm(ctx0, cur, hparams,
  7938. model.layers[il].attn_out_norm, NULL,
  7939. LLM_NORM_RMS, cb, il);
  7940. cb(cur, "attn_out_norm", il);
  7941. }
  7942. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7943. cb(ffn_inp, "ffn_inp", il);
  7944. // feed-forward network
  7945. // MoE branch
  7946. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7947. model.layers[il].ffn_norm, NULL,
  7948. LLM_NORM_RMS, cb, il);
  7949. cb(cur, "ffn_norm", il);
  7950. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  7951. model.layers[il].ffn_gate_inp,
  7952. model.layers[il].ffn_up_exps,
  7953. model.layers[il].ffn_gate_exps,
  7954. model.layers[il].ffn_down_exps,
  7955. n_expert, n_expert_used,
  7956. LLM_FFN_GELU, true,
  7957. false, 0.0,
  7958. cb, il);
  7959. cb(cur, "ffn_moe_out", il);
  7960. // Grok
  7961. // if layer_out_norm is present then apply it before adding the input
  7962. // Idea: maybe ffn_out_norm is a better name
  7963. if (model.layers[il].layer_out_norm) {
  7964. cur = llm_build_norm(ctx0, cur, hparams,
  7965. model.layers[il].layer_out_norm, NULL,
  7966. LLM_NORM_RMS, cb, il);
  7967. cb(cur, "layer_out_norm", il);
  7968. }
  7969. cur = ggml_add(ctx0, cur, ffn_inp);
  7970. cb(cur, "ffn_out", il);
  7971. cur = lctx.cvec.apply_to(ctx0, cur, il);
  7972. cb(cur, "l_out", il);
  7973. // input for next layer
  7974. inpL = cur;
  7975. }
  7976. cur = inpL;
  7977. cur = llm_build_norm(ctx0, cur, hparams,
  7978. model.output_norm, NULL,
  7979. LLM_NORM_RMS, cb, -1);
  7980. cb(cur, "result_norm", -1);
  7981. // lm_head
  7982. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  7983. // Grok
  7984. // multiply logits by output_multiplier_scale of 0.5773502691896257
  7985. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  7986. cb(cur, "result_output", -1);
  7987. ggml_build_forward_expand(gf, cur);
  7988. return gf;
  7989. }
  7990. struct ggml_cgraph * build_dbrx() {
  7991. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  7992. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7993. int32_t n_tokens = this->n_tokens;
  7994. const int64_t n_embd_head = hparams.n_embd_head_v;
  7995. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7996. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7997. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7998. struct ggml_tensor * cur;
  7999. struct ggml_tensor * inpL;
  8000. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8001. // inp_pos - contains the positions
  8002. struct ggml_tensor * inp_pos = build_inp_pos();
  8003. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8004. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8005. for (int il = 0; il < n_layer; ++il) {
  8006. struct ggml_tensor * inpSA = inpL;
  8007. // norm
  8008. cur = llm_build_norm(ctx0, inpL, hparams,
  8009. model.layers[il].attn_norm, NULL,
  8010. LLM_NORM, cb, il);
  8011. cb(cur, "attn_norm", il);
  8012. // self-attention
  8013. {
  8014. struct ggml_tensor * Qcur = nullptr;
  8015. struct ggml_tensor * Kcur = nullptr;
  8016. struct ggml_tensor * Vcur = nullptr;
  8017. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8018. cb(cur, "wqkv", il);
  8019. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8020. cb(cur, "wqkv_clamped", il);
  8021. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8022. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8023. 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)));
  8024. cb(Qcur, "Qcur", il);
  8025. cb(Kcur, "Kcur", il);
  8026. cb(Vcur, "Vcur", il);
  8027. Qcur = ggml_rope_ext(
  8028. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8029. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8030. ext_factor, attn_factor, beta_fast, beta_slow
  8031. );
  8032. cb(Qcur, "Qcur", il);
  8033. Kcur = ggml_rope_ext(
  8034. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8035. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8036. ext_factor, attn_factor, beta_fast, beta_slow
  8037. );
  8038. cb(Kcur, "Kcur", il);
  8039. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8040. model.layers[il].wo, NULL,
  8041. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8042. }
  8043. if (il == n_layer - 1) {
  8044. // skip computing output for unused tokens
  8045. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8046. n_tokens = n_outputs;
  8047. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8048. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8049. }
  8050. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8051. cb(ffn_inp, "ffn_inp", il);
  8052. // feed-forward network
  8053. // MoE branch
  8054. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8055. model.layers[il].attn_out_norm, NULL,
  8056. LLM_NORM, cb, il);
  8057. cb(cur, "attn_out_norm", il);
  8058. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  8059. model.layers[il].ffn_gate_inp,
  8060. model.layers[il].ffn_up_exps,
  8061. model.layers[il].ffn_gate_exps,
  8062. model.layers[il].ffn_down_exps,
  8063. n_expert, n_expert_used,
  8064. LLM_FFN_SILU, true,
  8065. false, 0.0,
  8066. cb, il);
  8067. cb(cur, "ffn_moe_out", il);
  8068. cur = ggml_add(ctx0, cur, ffn_inp);
  8069. cb(cur, "ffn_out", il);
  8070. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8071. cb(cur, "l_out", il);
  8072. // input for next layer
  8073. inpL = cur;
  8074. }
  8075. cur = inpL;
  8076. cur = llm_build_norm(ctx0, cur, hparams,
  8077. model.output_norm, NULL,
  8078. LLM_NORM, cb, -1);
  8079. cb(cur, "result_norm", -1);
  8080. // lm_head
  8081. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8082. cb(cur, "result_output", -1);
  8083. ggml_build_forward_expand(gf, cur);
  8084. return gf;
  8085. }
  8086. struct ggml_cgraph * build_starcoder() {
  8087. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8088. const int64_t n_embd_head = hparams.n_embd_head_v;
  8089. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8090. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8091. struct ggml_tensor * cur;
  8092. struct ggml_tensor * inpL;
  8093. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8094. // inp_pos - contains the positions
  8095. struct ggml_tensor * inp_pos = build_inp_pos();
  8096. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8097. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8098. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8099. cb(pos, "pos_embd", -1);
  8100. inpL = ggml_add(ctx0, inpL, pos);
  8101. cb(inpL, "inpL", -1);
  8102. for (int il = 0; il < n_layer; ++il) {
  8103. cur = llm_build_norm(ctx0, inpL, hparams,
  8104. model.layers[il].attn_norm,
  8105. model.layers[il].attn_norm_b,
  8106. LLM_NORM, cb, il);
  8107. cb(cur, "attn_norm", il);
  8108. // self-attention
  8109. {
  8110. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8111. cb(cur, "wqkv", il);
  8112. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8113. cb(cur, "bqkv", il);
  8114. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8115. 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)));
  8116. 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)));
  8117. cb(Qcur, "Qcur", il);
  8118. cb(Kcur, "Kcur", il);
  8119. cb(Vcur, "Vcur", il);
  8120. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8121. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8122. model.layers[il].wo, model.layers[il].bo,
  8123. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8124. }
  8125. if (il == n_layer - 1) {
  8126. // skip computing output for unused tokens
  8127. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8128. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8129. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8130. }
  8131. // add the input
  8132. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8133. cb(ffn_inp, "ffn_inp", il);
  8134. // FF
  8135. {
  8136. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8137. model.layers[il].ffn_norm,
  8138. model.layers[il].ffn_norm_b,
  8139. LLM_NORM, cb, il);
  8140. cb(cur, "ffn_norm", il);
  8141. cur = llm_build_ffn(ctx0, lctx, cur,
  8142. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8143. NULL, NULL, NULL,
  8144. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8145. NULL,
  8146. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8147. cb(cur, "ffn_out", il);
  8148. }
  8149. cur = ggml_add(ctx0, cur, ffn_inp);
  8150. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8151. cb(cur, "l_out", il);
  8152. // input for next layer
  8153. inpL = cur;
  8154. }
  8155. cur = llm_build_norm(ctx0, inpL, hparams,
  8156. model.output_norm,
  8157. model.output_norm_b,
  8158. LLM_NORM, cb, -1);
  8159. cb(cur, "result_norm", -1);
  8160. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8161. cb(cur, "result_output", -1);
  8162. ggml_build_forward_expand(gf, cur);
  8163. return gf;
  8164. }
  8165. struct ggml_cgraph * build_refact() {
  8166. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8167. const int64_t n_embd_head = hparams.n_embd_head_v;
  8168. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8169. struct ggml_tensor * cur;
  8170. struct ggml_tensor * inpL;
  8171. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8172. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8173. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8174. for (int il = 0; il < n_layer; ++il) {
  8175. struct ggml_tensor * inpSA = inpL;
  8176. cur = llm_build_norm(ctx0, inpL, hparams,
  8177. model.layers[il].attn_norm, NULL,
  8178. LLM_NORM_RMS, cb, il);
  8179. cb(cur, "attn_norm", il);
  8180. // self-attention
  8181. {
  8182. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8183. cb(Qcur, "Qcur", il);
  8184. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8185. cb(Kcur, "Kcur", il);
  8186. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8187. cb(Vcur, "Vcur", il);
  8188. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8189. cb(Kcur, "Kcur", il);
  8190. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8191. cb(Qcur, "Qcur", il);
  8192. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8193. model.layers[il].wo, NULL,
  8194. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8195. }
  8196. if (il == n_layer - 1) {
  8197. // skip computing output for unused tokens
  8198. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8199. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8200. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8201. }
  8202. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8203. cb(ffn_inp, "ffn_inp", il);
  8204. // feed-forward network
  8205. {
  8206. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8207. model.layers[il].ffn_norm, NULL,
  8208. LLM_NORM_RMS, cb, il);
  8209. cb(cur, "ffn_norm", il);
  8210. cur = llm_build_ffn(ctx0, lctx, cur,
  8211. model.layers[il].ffn_up, NULL, NULL,
  8212. model.layers[il].ffn_gate, NULL, NULL,
  8213. model.layers[il].ffn_down, NULL, NULL,
  8214. NULL,
  8215. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8216. cb(cur, "ffn_out", il);
  8217. }
  8218. cur = ggml_add(ctx0, cur, ffn_inp);
  8219. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8220. cb(cur, "l_out", il);
  8221. // input for next layer
  8222. inpL = cur;
  8223. }
  8224. cur = inpL;
  8225. cur = llm_build_norm(ctx0, cur, hparams,
  8226. model.output_norm, NULL,
  8227. LLM_NORM_RMS, cb, -1);
  8228. cb(cur, "result_norm", -1);
  8229. // lm_head
  8230. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8231. cb(cur, "result_output", -1);
  8232. ggml_build_forward_expand(gf, cur);
  8233. return gf;
  8234. }
  8235. struct ggml_cgraph * build_bert() {
  8236. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8237. const int64_t n_embd_head = hparams.n_embd_head_v;
  8238. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8239. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8240. struct ggml_tensor * cur;
  8241. struct ggml_tensor * inpL;
  8242. struct ggml_tensor * inp_pos = nullptr;
  8243. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  8244. inp_pos = build_inp_pos();
  8245. }
  8246. // construct input embeddings (token, type, position)
  8247. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8248. // token types are hardcoded to zero ("Sentence A")
  8249. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  8250. inpL = ggml_add(ctx0, inpL, type_row0);
  8251. if (model.arch == LLM_ARCH_BERT) {
  8252. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  8253. }
  8254. cb(inpL, "inp_embd", -1);
  8255. // embed layer norm
  8256. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  8257. cb(inpL, "inp_norm", -1);
  8258. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8259. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  8260. // iterate layers
  8261. for (int il = 0; il < n_layer; ++il) {
  8262. struct ggml_tensor * cur = inpL;
  8263. struct ggml_tensor * Qcur;
  8264. struct ggml_tensor * Kcur;
  8265. struct ggml_tensor * Vcur;
  8266. // self-attention
  8267. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  8268. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  8269. cb(Qcur, "Qcur", il);
  8270. if (model.layers[il].attn_q_norm) {
  8271. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8272. model.layers[il].attn_q_norm,
  8273. model.layers[il].attn_q_norm_b,
  8274. LLM_NORM, cb, il);
  8275. }
  8276. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  8277. cb(Kcur, "Kcur", il);
  8278. if (model.layers[il].attn_k_norm) {
  8279. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8280. model.layers[il].attn_k_norm,
  8281. model.layers[il].attn_k_norm_b,
  8282. LLM_NORM, cb, il);
  8283. }
  8284. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  8285. cb(Vcur, "Vcur", il);
  8286. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8287. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8288. } else {
  8289. // compute Q and K and RoPE them
  8290. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8291. cb(cur, "wqkv", il);
  8292. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8293. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8294. 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)));
  8295. cb(Qcur, "Qcur", il);
  8296. cb(Kcur, "Kcur", il);
  8297. cb(Vcur, "Vcur", il);
  8298. Qcur = ggml_rope_ext(
  8299. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8300. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8301. ext_factor, attn_factor, beta_fast, beta_slow
  8302. );
  8303. cb(Qcur, "Qcur", il);
  8304. Kcur = ggml_rope_ext(
  8305. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8306. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8307. ext_factor, attn_factor, beta_fast, beta_slow
  8308. );
  8309. cb(Kcur, "Kcur", il);
  8310. }
  8311. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  8312. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  8313. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  8314. cb(kq, "kq", il);
  8315. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  8316. cb(kq, "kq_soft_max_ext", il);
  8317. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  8318. cb(v, "v", il);
  8319. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  8320. cb(kqv, "kqv", il);
  8321. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  8322. cb(kqv_merged, "kqv_merged", il);
  8323. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  8324. cb(cur, "kqv_merged_cont", il);
  8325. ggml_build_forward_expand(gf, cur);
  8326. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  8327. if (model.layers[il].bo) {
  8328. cb(cur, "kqv_wo", il);
  8329. }
  8330. if (model.layers[il].bo) {
  8331. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  8332. }
  8333. cb(cur, "kqv_out", il);
  8334. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8335. // skip computing output for unused tokens
  8336. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8337. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8338. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8339. }
  8340. // re-add the layer input
  8341. cur = ggml_add(ctx0, cur, inpL);
  8342. // attention layer norm
  8343. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  8344. if (model.layers[il].attn_norm_2 != nullptr) {
  8345. cur = ggml_add(ctx0, cur, inpL); // re-add the layer input
  8346. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_norm_2, model.layers[il].attn_norm_2_b, LLM_NORM, cb, il);
  8347. }
  8348. struct ggml_tensor * ffn_inp = cur;
  8349. cb(ffn_inp, "ffn_inp", il);
  8350. // feed-forward network
  8351. if (model.arch == LLM_ARCH_BERT) {
  8352. cur = llm_build_ffn(ctx0, lctx, cur,
  8353. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8354. NULL, NULL, NULL,
  8355. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8356. NULL,
  8357. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8358. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  8359. cur = llm_build_ffn(ctx0, lctx, cur,
  8360. model.layers[il].ffn_up, NULL, NULL,
  8361. model.layers[il].ffn_gate, NULL, NULL,
  8362. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8363. NULL,
  8364. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  8365. } else {
  8366. cur = llm_build_ffn(ctx0, lctx, cur,
  8367. model.layers[il].ffn_up, NULL, NULL,
  8368. model.layers[il].ffn_gate, NULL, NULL,
  8369. model.layers[il].ffn_down, NULL, NULL,
  8370. NULL,
  8371. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8372. }
  8373. cb(cur, "ffn_out", il);
  8374. // attentions bypass the intermediate layer
  8375. cur = ggml_add(ctx0, cur, ffn_inp);
  8376. // output layer norm
  8377. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  8378. // input for next layer
  8379. inpL = cur;
  8380. }
  8381. // final output
  8382. cur = inpL;
  8383. cb(cur, "result_embd", -1);
  8384. ggml_build_forward_expand(gf, cur);
  8385. return gf;
  8386. }
  8387. struct ggml_cgraph * build_bloom() {
  8388. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8389. const int64_t n_embd_head = hparams.n_embd_head_v;
  8390. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8391. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8392. struct ggml_tensor * cur;
  8393. struct ggml_tensor * inpL;
  8394. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8395. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8396. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8397. inpL = llm_build_norm(ctx0, inpL, hparams,
  8398. model.tok_norm,
  8399. model.tok_norm_b,
  8400. LLM_NORM, cb, -1);
  8401. cb(inpL, "inp_norm", -1);
  8402. for (int il = 0; il < n_layer; ++il) {
  8403. cur = llm_build_norm(ctx0, inpL, hparams,
  8404. model.layers[il].attn_norm,
  8405. model.layers[il].attn_norm_b,
  8406. LLM_NORM, cb, il);
  8407. cb(cur, "attn_norm", il);
  8408. // self-attention
  8409. {
  8410. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8411. cb(cur, "wqkv", il);
  8412. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8413. cb(cur, "bqkv", il);
  8414. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8415. 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)));
  8416. 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)));
  8417. cb(Qcur, "Qcur", il);
  8418. cb(Kcur, "Kcur", il);
  8419. cb(Vcur, "Vcur", il);
  8420. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8421. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8422. model.layers[il].wo, model.layers[il].bo,
  8423. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8424. }
  8425. if (il == n_layer - 1) {
  8426. // skip computing output for unused tokens
  8427. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8428. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8429. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8430. }
  8431. // Add the input
  8432. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8433. cb(ffn_inp, "ffn_inp", il);
  8434. // FF
  8435. {
  8436. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8437. model.layers[il].ffn_norm,
  8438. model.layers[il].ffn_norm_b,
  8439. LLM_NORM, cb, il);
  8440. cb(cur, "ffn_norm", il);
  8441. cur = llm_build_ffn(ctx0, lctx, cur,
  8442. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8443. NULL, NULL, NULL,
  8444. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8445. NULL,
  8446. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8447. cb(cur, "ffn_out", il);
  8448. }
  8449. cur = ggml_add(ctx0, cur, ffn_inp);
  8450. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8451. cb(cur, "l_out", il);
  8452. // input for next layer
  8453. inpL = cur;
  8454. }
  8455. cur = llm_build_norm(ctx0, inpL, hparams,
  8456. model.output_norm,
  8457. model.output_norm_b,
  8458. LLM_NORM, cb, -1);
  8459. cb(cur, "result_norm", -1);
  8460. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8461. cb(cur, "result_output", -1);
  8462. ggml_build_forward_expand(gf, cur);
  8463. return gf;
  8464. }
  8465. struct ggml_cgraph * build_mpt() {
  8466. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8467. const int64_t n_embd_head = hparams.n_embd_head_v;
  8468. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8469. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8470. struct ggml_tensor * cur;
  8471. struct ggml_tensor * pos;
  8472. struct ggml_tensor * inpL;
  8473. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8474. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8475. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8476. if (model.pos_embd) {
  8477. // inp_pos - contains the positions
  8478. struct ggml_tensor * inp_pos = build_inp_pos();
  8479. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8480. cb(pos, "pos_embd", -1);
  8481. inpL = ggml_add(ctx0, inpL, pos);
  8482. cb(inpL, "inpL", -1);
  8483. }
  8484. for (int il = 0; il < n_layer; ++il) {
  8485. struct ggml_tensor * attn_norm;
  8486. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  8487. model.layers[il].attn_norm,
  8488. model.layers[il].attn_norm_b,
  8489. LLM_NORM, cb, il);
  8490. cb(attn_norm, "attn_norm", il);
  8491. // self-attention
  8492. {
  8493. cur = attn_norm;
  8494. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8495. cb(cur, "wqkv", il);
  8496. if (model.layers[il].bqkv){
  8497. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8498. cb(cur, "bqkv", il);
  8499. }
  8500. if (hparams.f_clamp_kqv > 0.0f) {
  8501. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8502. cb(cur, "wqkv_clamped", il);
  8503. }
  8504. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8505. 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)));
  8506. 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)));
  8507. cb(Qcur, "Qcur", il);
  8508. cb(Kcur, "Kcur", il);
  8509. cb(Vcur, "Vcur", il);
  8510. // Q/K Layernorm
  8511. if (model.layers[il].attn_q_norm) {
  8512. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8513. model.layers[il].attn_q_norm,
  8514. model.layers[il].attn_q_norm_b,
  8515. LLM_NORM, cb, il);
  8516. cb(Qcur, "Qcur", il);
  8517. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8518. model.layers[il].attn_k_norm,
  8519. model.layers[il].attn_k_norm_b,
  8520. LLM_NORM, cb, il);
  8521. cb(Kcur, "Kcur", il);
  8522. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8523. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8524. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8525. model.layers[il].wo, model.layers[il].bo,
  8526. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8527. } else {
  8528. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8529. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8530. model.layers[il].wo, model.layers[il].bo,
  8531. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8532. }
  8533. }
  8534. if (il == n_layer - 1) {
  8535. // skip computing output for unused tokens
  8536. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8537. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8538. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8539. }
  8540. // Add the input
  8541. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8542. cb(ffn_inp, "ffn_inp", il);
  8543. // feed forward
  8544. {
  8545. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8546. model.layers[il].ffn_norm,
  8547. model.layers[il].ffn_norm_b,
  8548. LLM_NORM, cb, il);
  8549. cb(cur, "ffn_norm", il);
  8550. cur = llm_build_ffn(ctx0, lctx, cur,
  8551. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  8552. NULL, NULL, NULL,
  8553. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  8554. model.layers[il].ffn_act,
  8555. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8556. cb(cur, "ffn_out", il);
  8557. }
  8558. cur = ggml_add(ctx0, cur, ffn_inp);
  8559. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8560. cb(cur, "l_out", il);
  8561. // input for next layer
  8562. inpL = cur;
  8563. }
  8564. cur = inpL;
  8565. cur = llm_build_norm(ctx0, cur, hparams,
  8566. model.output_norm,
  8567. model.output_norm_b,
  8568. LLM_NORM, cb, -1);
  8569. cb(cur, "result_norm", -1);
  8570. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8571. cb(cur, "result_output", -1);
  8572. ggml_build_forward_expand(gf, cur);
  8573. return gf;
  8574. }
  8575. struct ggml_cgraph * build_stablelm() {
  8576. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  8577. const int64_t n_embd_head = hparams.n_embd_head_v;
  8578. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8579. struct ggml_tensor * cur;
  8580. struct ggml_tensor * inpL;
  8581. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8582. // inp_pos - contains the positions
  8583. struct ggml_tensor * inp_pos = build_inp_pos();
  8584. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8585. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8586. for (int il = 0; il < n_layer; ++il) {
  8587. // norm
  8588. cur = llm_build_norm(ctx0, inpL, hparams,
  8589. model.layers[il].attn_norm,
  8590. model.layers[il].attn_norm_b,
  8591. LLM_NORM, cb, il);
  8592. cb(cur, "attn_norm", il);
  8593. struct ggml_tensor * inpSA = cur;
  8594. // self-attention
  8595. {
  8596. // compute Q and K and RoPE them
  8597. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8598. cb(Qcur, "Qcur", il);
  8599. if (model.layers[il].bq) {
  8600. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8601. cb(Qcur, "Qcur", il);
  8602. }
  8603. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8604. cb(Kcur, "Kcur", il);
  8605. if (model.layers[il].bk) {
  8606. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8607. cb(Kcur, "Kcur", il);
  8608. }
  8609. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8610. cb(Vcur, "Vcur", il);
  8611. if (model.layers[il].bv) {
  8612. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8613. cb(Vcur, "Vcur", il);
  8614. }
  8615. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8616. cb(Qcur, "Qcur", il);
  8617. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8618. cb(Kcur, "Kcur", il);
  8619. if (model.layers[il].attn_q_norm) {
  8620. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8621. model.layers[il].attn_q_norm,
  8622. NULL,
  8623. LLM_NORM, cb, il);
  8624. cb(Qcur, "Qcur", il);
  8625. }
  8626. if (model.layers[il].attn_k_norm) {
  8627. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8628. model.layers[il].attn_k_norm,
  8629. NULL,
  8630. LLM_NORM, cb, il);
  8631. cb(Kcur, "Kcur", il);
  8632. }
  8633. Qcur = ggml_rope_ext(
  8634. ctx0, Qcur, inp_pos, nullptr,
  8635. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8636. ext_factor, attn_factor, beta_fast, beta_slow
  8637. );
  8638. cb(Qcur, "Qcur", il);
  8639. Kcur = ggml_rope_ext(
  8640. ctx0, Kcur, inp_pos, nullptr,
  8641. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8642. ext_factor, attn_factor, beta_fast, beta_slow
  8643. );
  8644. cb(Kcur, "Kcur", il);
  8645. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8646. model.layers[il].wo, NULL,
  8647. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8648. }
  8649. if (il == n_layer - 1) {
  8650. // skip computing output for unused tokens
  8651. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8652. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8653. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8654. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8655. }
  8656. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8657. cb(ffn_inp, "ffn_inp", il);
  8658. // feed-forward network
  8659. {
  8660. if (model.layers[il].ffn_norm) {
  8661. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8662. model.layers[il].ffn_norm,
  8663. model.layers[il].ffn_norm_b,
  8664. LLM_NORM, cb, il);
  8665. cb(cur, "ffn_norm", il);
  8666. } else {
  8667. // parallel residual
  8668. cur = inpSA;
  8669. }
  8670. cur = llm_build_ffn(ctx0, lctx, cur,
  8671. model.layers[il].ffn_up, NULL, NULL,
  8672. model.layers[il].ffn_gate, NULL, NULL,
  8673. model.layers[il].ffn_down, NULL, NULL,
  8674. NULL,
  8675. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8676. cb(cur, "ffn_out", il);
  8677. }
  8678. cur = ggml_add(ctx0, cur, ffn_inp);
  8679. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8680. cb(cur, "l_out", il);
  8681. // input for next layer
  8682. inpL = cur;
  8683. }
  8684. cur = inpL;
  8685. cur = llm_build_norm(ctx0, cur, hparams,
  8686. model.output_norm,
  8687. model.output_norm_b,
  8688. LLM_NORM, cb, -1);
  8689. cb(cur, "result_norm", -1);
  8690. // lm_head
  8691. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8692. cb(cur, "result_output", -1);
  8693. ggml_build_forward_expand(gf, cur);
  8694. return gf;
  8695. }
  8696. struct ggml_cgraph * build_qwen() {
  8697. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8698. const int64_t n_embd_head = hparams.n_embd_head_v;
  8699. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8700. struct ggml_tensor * cur;
  8701. struct ggml_tensor * inpL;
  8702. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8703. // inp_pos - contains the positions
  8704. struct ggml_tensor * inp_pos = build_inp_pos();
  8705. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8706. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8707. for (int il = 0; il < n_layer; ++il) {
  8708. struct ggml_tensor * inpSA = inpL;
  8709. cur = llm_build_norm(ctx0, inpL, hparams,
  8710. model.layers[il].attn_norm, NULL,
  8711. LLM_NORM_RMS, cb, il);
  8712. cb(cur, "attn_norm", il);
  8713. // self-attention
  8714. {
  8715. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  8716. cb(cur, "wqkv", il);
  8717. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8718. cb(cur, "bqkv", il);
  8719. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8720. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  8721. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  8722. cb(Qcur, "Qcur", il);
  8723. cb(Kcur, "Kcur", il);
  8724. cb(Vcur, "Vcur", il);
  8725. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8726. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  8727. // using mode = 2 for neox mode
  8728. Qcur = ggml_rope_ext(
  8729. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8730. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8731. );
  8732. cb(Qcur, "Qcur", il);
  8733. Kcur = ggml_rope_ext(
  8734. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  8735. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  8736. );
  8737. cb(Kcur, "Kcur", il);
  8738. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8739. model.layers[il].wo, NULL,
  8740. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8741. }
  8742. if (il == n_layer - 1) {
  8743. // skip computing output for unused tokens
  8744. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8745. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8746. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8747. }
  8748. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8749. cb(ffn_inp, "ffn_inp", il);
  8750. // feed-forward forward
  8751. {
  8752. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8753. model.layers[il].ffn_norm, NULL,
  8754. LLM_NORM_RMS, cb, il);
  8755. cb(cur, "ffn_norm", il);
  8756. cur = llm_build_ffn(ctx0, lctx, cur,
  8757. model.layers[il].ffn_up, NULL, NULL,
  8758. model.layers[il].ffn_gate, NULL, NULL,
  8759. model.layers[il].ffn_down, NULL, NULL,
  8760. NULL,
  8761. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8762. cb(cur, "ffn_out", il);
  8763. }
  8764. cur = ggml_add(ctx0, cur, ffn_inp);
  8765. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8766. cb(cur, "l_out", il);
  8767. // input for next layer
  8768. inpL = cur;
  8769. }
  8770. cur = inpL;
  8771. cur = llm_build_norm(ctx0, cur, hparams,
  8772. model.output_norm, NULL,
  8773. LLM_NORM_RMS, cb, -1);
  8774. cb(cur, "result_norm", -1);
  8775. // lm_head
  8776. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8777. cb(cur, "result_output", -1);
  8778. ggml_build_forward_expand(gf, cur);
  8779. return gf;
  8780. }
  8781. struct ggml_cgraph * build_qwen2() {
  8782. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8783. const int64_t n_embd_head = hparams.n_embd_head_v;
  8784. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8785. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8786. struct ggml_tensor * cur;
  8787. struct ggml_tensor * inpL;
  8788. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8789. // inp_pos - contains the positions
  8790. struct ggml_tensor * inp_pos = build_inp_pos();
  8791. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8792. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8793. for (int il = 0; il < n_layer; ++il) {
  8794. struct ggml_tensor * inpSA = inpL;
  8795. // norm
  8796. cur = llm_build_norm(ctx0, inpL, hparams,
  8797. model.layers[il].attn_norm, NULL,
  8798. LLM_NORM_RMS, cb, il);
  8799. cb(cur, "attn_norm", il);
  8800. // self-attention
  8801. {
  8802. // compute Q and K and RoPE them
  8803. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8804. cb(Qcur, "Qcur", il);
  8805. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8806. cb(Qcur, "Qcur", il);
  8807. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8808. cb(Kcur, "Kcur", il);
  8809. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8810. cb(Kcur, "Kcur", il);
  8811. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8812. cb(Vcur, "Vcur", il);
  8813. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8814. cb(Vcur, "Vcur", il);
  8815. Qcur = ggml_rope_ext(
  8816. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8817. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8818. ext_factor, attn_factor, beta_fast, beta_slow
  8819. );
  8820. cb(Qcur, "Qcur", il);
  8821. Kcur = ggml_rope_ext(
  8822. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8823. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8824. ext_factor, attn_factor, beta_fast, beta_slow
  8825. );
  8826. cb(Kcur, "Kcur", il);
  8827. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8828. model.layers[il].wo, model.layers[il].bo,
  8829. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8830. }
  8831. if (il == n_layer - 1) {
  8832. // skip computing output for unused tokens
  8833. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8834. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8835. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8836. }
  8837. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8838. cb(ffn_inp, "ffn_inp", il);
  8839. // feed-forward network
  8840. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8841. model.layers[il].ffn_norm, NULL,
  8842. LLM_NORM_RMS, cb, il);
  8843. cb(cur, "ffn_norm", il);
  8844. cur = llm_build_ffn(ctx0, lctx, cur,
  8845. model.layers[il].ffn_up, NULL, NULL,
  8846. model.layers[il].ffn_gate, NULL, NULL,
  8847. model.layers[il].ffn_down, NULL, NULL,
  8848. NULL,
  8849. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8850. cb(cur, "ffn_out", il);
  8851. cur = ggml_add(ctx0, cur, ffn_inp);
  8852. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8853. cb(cur, "l_out", il);
  8854. // input for next layer
  8855. inpL = cur;
  8856. }
  8857. cur = inpL;
  8858. cur = llm_build_norm(ctx0, cur, hparams,
  8859. model.output_norm, NULL,
  8860. LLM_NORM_RMS, cb, -1);
  8861. cb(cur, "result_norm", -1);
  8862. // lm_head
  8863. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8864. cb(cur, "result_output", -1);
  8865. ggml_build_forward_expand(gf, cur);
  8866. return gf;
  8867. }
  8868. struct ggml_cgraph * build_qwen2moe() {
  8869. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8870. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8871. int32_t n_tokens = this->n_tokens;
  8872. const int64_t n_embd_head = hparams.n_embd_head_v;
  8873. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8874. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8875. struct ggml_tensor * cur;
  8876. struct ggml_tensor * inpL;
  8877. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8878. // inp_pos - contains the positions
  8879. struct ggml_tensor * inp_pos = build_inp_pos();
  8880. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8881. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8882. for (int il = 0; il < n_layer; ++il) {
  8883. struct ggml_tensor * inpSA = inpL;
  8884. // norm
  8885. cur = llm_build_norm(ctx0, inpL, hparams,
  8886. model.layers[il].attn_norm, NULL,
  8887. LLM_NORM_RMS, cb, il);
  8888. cb(cur, "attn_norm", il);
  8889. // self_attention
  8890. {
  8891. // compute Q and K and RoPE them
  8892. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  8893. cb(Qcur, "Qcur", il);
  8894. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8895. cb(Qcur, "Qcur", il);
  8896. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  8897. cb(Kcur, "Kcur", il);
  8898. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8899. cb(Kcur, "Kcur", il);
  8900. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  8901. cb(Vcur, "Vcur", il);
  8902. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8903. cb(Vcur, "Vcur", il);
  8904. Qcur = ggml_rope_ext(
  8905. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8906. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8907. ext_factor, attn_factor, beta_fast, beta_slow
  8908. );
  8909. cb(Qcur, "Qcur", il);
  8910. Kcur = ggml_rope_ext(
  8911. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8912. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  8913. ext_factor, attn_factor, beta_fast, beta_slow
  8914. );
  8915. cb(Kcur, "Kcur", il);
  8916. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  8917. model.layers[il].wo, model.layers[il].bo,
  8918. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8919. }
  8920. if (il == n_layer - 1) {
  8921. // skip computing output for unused tokens
  8922. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8923. n_tokens = n_outputs;
  8924. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8925. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8926. }
  8927. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8928. cb(ffn_inp, "ffn_inp", il);
  8929. // MoE branch
  8930. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8931. model.layers[il].ffn_norm, NULL,
  8932. LLM_NORM_RMS, cb, il);
  8933. cb(cur, "ffn_norm", il);
  8934. ggml_tensor * moe_out =
  8935. llm_build_moe_ffn(ctx0, lctx, cur,
  8936. model.layers[il].ffn_gate_inp,
  8937. model.layers[il].ffn_up_exps,
  8938. model.layers[il].ffn_gate_exps,
  8939. model.layers[il].ffn_down_exps,
  8940. n_expert, n_expert_used,
  8941. LLM_FFN_SILU, false,
  8942. false, 0.0,
  8943. cb, il);
  8944. cb(cur, "ffn_moe_out", il);
  8945. // FFN shared expert
  8946. {
  8947. ggml_tensor * cur_gate_inp = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  8948. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  8949. // sigmoid
  8950. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  8951. cb(cur_gate, "ffn_shexp_gate", il);
  8952. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, lctx, cur,
  8953. model.layers[il].ffn_up_shexp, NULL, NULL,
  8954. model.layers[il].ffn_gate_shexp, NULL, NULL,
  8955. model.layers[il].ffn_down_shexp, NULL, NULL,
  8956. NULL,
  8957. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8958. cb(cur_ffn, "ffn_shexp", il);
  8959. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  8960. cb(ffn_shexp_out, "ffn_shexp_out", il);
  8961. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  8962. cb(moe_out, "ffn_out", il);
  8963. cur = moe_out;
  8964. }
  8965. cur = ggml_add(ctx0, cur, ffn_inp);
  8966. cur = lctx.cvec.apply_to(ctx0, cur, il);
  8967. cb(cur, "l_out", il);
  8968. // input for next layer
  8969. inpL = cur;
  8970. }
  8971. cur = inpL;
  8972. cur = llm_build_norm(ctx0, cur, hparams,
  8973. model.output_norm, NULL,
  8974. LLM_NORM_RMS, cb, -1);
  8975. cb(cur, "result_norm", -1);
  8976. // lm_head
  8977. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  8978. cb(cur, "result_output", -1);
  8979. ggml_build_forward_expand(gf, cur);
  8980. return gf;
  8981. }
  8982. struct ggml_cgraph * build_phi2() {
  8983. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  8984. const int64_t n_embd_head = hparams.n_embd_head_v;
  8985. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8986. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8987. struct ggml_tensor * cur;
  8988. struct ggml_tensor * attn_norm_output;
  8989. struct ggml_tensor * ffn_output;
  8990. struct ggml_tensor * inpL;
  8991. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8992. // inp_pos - contains the positions
  8993. struct ggml_tensor * inp_pos = build_inp_pos();
  8994. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8995. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8996. for (int il = 0; il < n_layer; ++il) {
  8997. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  8998. model.layers[il].attn_norm,
  8999. model.layers[il].attn_norm_b,
  9000. LLM_NORM, cb, il);
  9001. cb(attn_norm_output, "attn_norm", il);
  9002. // self-attention
  9003. {
  9004. struct ggml_tensor * Qcur = nullptr;
  9005. struct ggml_tensor * Kcur = nullptr;
  9006. struct ggml_tensor * Vcur = nullptr;
  9007. if (model.layers[il].wqkv) {
  9008. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9009. cb(cur, "wqkv", il);
  9010. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9011. cb(cur, "bqkv", il);
  9012. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9013. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  9014. 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)));
  9015. } else {
  9016. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9017. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9018. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9019. }
  9020. cb(Qcur, "Qcur", il);
  9021. cb(Kcur, "Kcur", il);
  9022. cb(Vcur, "Vcur", il);
  9023. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9024. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9025. Qcur = ggml_rope_ext(
  9026. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9027. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9028. );
  9029. cb(Qcur, "Qcur", il);
  9030. // with phi2, we scale the Q to avoid precision issues
  9031. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  9032. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  9033. cb(Qcur, "Qcur", il);
  9034. Kcur = ggml_rope_ext(
  9035. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, n_ctx_orig,
  9036. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9037. );
  9038. cb(Kcur, "Kcur", il);
  9039. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9040. model.layers[il].wo, model.layers[il].bo,
  9041. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9042. }
  9043. if (il == n_layer - 1) {
  9044. // skip computing output for unused tokens
  9045. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9046. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9047. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9048. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  9049. }
  9050. // FF
  9051. {
  9052. ffn_output = llm_build_ffn(ctx0, lctx, attn_norm_output,
  9053. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9054. NULL, NULL, NULL,
  9055. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9056. NULL,
  9057. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9058. cb(ffn_output, "ffn_out", il);
  9059. }
  9060. cur = ggml_add(ctx0, cur, ffn_output);
  9061. cur = ggml_add(ctx0, cur, inpL);
  9062. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9063. cb(cur, "l_out", il);
  9064. // input for next layer
  9065. inpL = cur;
  9066. }
  9067. cur = llm_build_norm(ctx0, inpL, hparams,
  9068. model.output_norm,
  9069. model.output_norm_b,
  9070. LLM_NORM, cb, -1);
  9071. cb(cur, "result_norm", -1);
  9072. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9073. cb(cur, "result_output_no_bias", -1);
  9074. cur = ggml_add(ctx0, cur, model.output_b);
  9075. cb(cur, "result_output", -1);
  9076. ggml_build_forward_expand(gf, cur);
  9077. return gf;
  9078. }
  9079. struct ggml_cgraph * build_phi3() {
  9080. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9081. const int64_t n_embd_head = hparams.n_embd_head_v;
  9082. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9083. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9084. struct ggml_tensor * cur;
  9085. struct ggml_tensor * inpL;
  9086. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9087. // inp_pos - contains the positions
  9088. struct ggml_tensor * inp_pos = build_inp_pos();
  9089. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9090. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa();
  9091. for (int il = 0; il < n_layer; ++il) {
  9092. auto residual = inpL;
  9093. // self-attention
  9094. {
  9095. // rope freq factors for 128k context
  9096. struct ggml_tensor * rope_factors = build_rope_factors(il);
  9097. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  9098. model.layers[il].attn_norm,
  9099. NULL,
  9100. LLM_NORM_RMS, cb, il);
  9101. cb(attn_norm_output, "attn_norm", il);
  9102. struct ggml_tensor * Qcur = nullptr;
  9103. struct ggml_tensor * Kcur = nullptr;
  9104. struct ggml_tensor * Vcur = nullptr;
  9105. if (model.layers[il].wqkv) {
  9106. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, attn_norm_output);
  9107. cb(cur, "wqkv", il);
  9108. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  9109. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  9110. 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)));
  9111. }
  9112. else {
  9113. Qcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  9114. Kcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  9115. Vcur = ggml_add(ctx0, llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  9116. }
  9117. cb(Qcur, "Qcur", il);
  9118. cb(Kcur, "Kcur", il);
  9119. cb(Vcur, "Vcur", il);
  9120. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9121. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  9122. Qcur = ggml_rope_ext(
  9123. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9124. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9125. );
  9126. cb(Qcur, "Qcur", il);
  9127. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  9128. cb(Qcur, "Qcur", il);
  9129. Kcur = ggml_rope_ext(
  9130. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, n_ctx_orig,
  9131. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  9132. );
  9133. cb(Kcur, "Kcur", il);
  9134. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9135. model.layers[il].wo, model.layers[il].bo,
  9136. Kcur, Vcur, Qcur, KQ_mask_swa, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9137. }
  9138. if (il == n_layer - 1) {
  9139. // skip computing output for unused tokens
  9140. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  9141. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9142. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  9143. }
  9144. cur = ggml_add(ctx0, cur, residual);
  9145. residual = cur;
  9146. cur = llm_build_norm(ctx0, cur, hparams,
  9147. model.layers[il].ffn_norm, NULL,
  9148. LLM_NORM_RMS, cb, il);
  9149. cb(cur, "ffn_norm", il);
  9150. // FF
  9151. // special-case: the up and gate tensors are merged into a single tensor
  9152. // TOOD: support into llm_build_ffn
  9153. {
  9154. cur = llm_build_ffn(ctx0, lctx, cur,
  9155. model.layers[il].ffn_up, NULL, NULL,
  9156. NULL, NULL, NULL,
  9157. model.layers[il].ffn_down, NULL, NULL,
  9158. NULL,
  9159. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  9160. cb(cur, "ffn_out", il);
  9161. }
  9162. cur = ggml_add(ctx0, residual, cur);
  9163. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9164. cb(cur, "l_out", il);
  9165. // input for next layer
  9166. inpL = cur;
  9167. }
  9168. cur = llm_build_norm(ctx0, inpL, hparams,
  9169. model.output_norm,
  9170. NULL,
  9171. LLM_NORM_RMS, cb, -1);
  9172. cb(cur, "result_norm", -1);
  9173. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9174. cb(cur, "result_output", -1);
  9175. ggml_build_forward_expand(gf, cur);
  9176. return gf;
  9177. }
  9178. struct ggml_cgraph * build_plamo() {
  9179. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  9180. const int64_t n_embd_head = hparams.n_embd_head_v;
  9181. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9182. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9183. struct ggml_tensor * cur;
  9184. struct ggml_tensor * inpL;
  9185. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9186. // inp_pos - contains the positions
  9187. struct ggml_tensor * inp_pos = build_inp_pos();
  9188. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9189. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9190. for (int il = 0; il < n_layer; ++il) {
  9191. // norm
  9192. cur = llm_build_norm(ctx0, inpL, hparams,
  9193. model.layers[il].attn_norm, NULL,
  9194. LLM_NORM_RMS, cb, il);
  9195. cb(cur, "attn_norm", il);
  9196. struct ggml_tensor * attention_norm = cur;
  9197. // self-attention
  9198. {
  9199. // compute Q and K and RoPE them
  9200. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9201. cb(Qcur, "Qcur", il);
  9202. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9203. cb(Kcur, "Kcur", il);
  9204. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9205. cb(Vcur, "Vcur", il);
  9206. Qcur = ggml_rope_ext(
  9207. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  9208. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9209. ext_factor, attn_factor, beta_fast, beta_slow);
  9210. cb(Qcur, "Qcur", il);
  9211. Kcur = ggml_rope_ext(
  9212. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  9213. n_embd_head, rope_type, n_ctx_orig, freq_base, freq_scale,
  9214. ext_factor, attn_factor, beta_fast, beta_slow);
  9215. cb(Kcur, "Kcur", il);
  9216. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9217. model.layers[il].wo, NULL,
  9218. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9219. }
  9220. struct ggml_tensor * sa_out = cur;
  9221. cur = attention_norm;
  9222. if (il == n_layer - 1) {
  9223. // skip computing output for unused tokens
  9224. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9225. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9226. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  9227. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9228. }
  9229. // feed-forward network
  9230. {
  9231. cur = llm_build_ffn(ctx0, lctx, cur,
  9232. model.layers[il].ffn_up, NULL, NULL,
  9233. model.layers[il].ffn_gate, NULL, NULL,
  9234. model.layers[il].ffn_down, NULL, NULL,
  9235. NULL,
  9236. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9237. cb(cur, "ffn_out", il);
  9238. }
  9239. cur = ggml_add(ctx0, cur, sa_out);
  9240. cur = ggml_add(ctx0, cur, inpL);
  9241. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9242. cb(cur, "l_out", il);
  9243. // input for next layer
  9244. inpL = cur;
  9245. }
  9246. cur = inpL;
  9247. cur = llm_build_norm(ctx0, cur, hparams,
  9248. model.output_norm, NULL,
  9249. LLM_NORM_RMS, cb, -1);
  9250. cb(cur, "result_norm", -1);
  9251. // lm_head
  9252. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9253. cb(cur, "result_output", -1);
  9254. ggml_build_forward_expand(gf, cur);
  9255. return gf;
  9256. }
  9257. struct ggml_cgraph * build_gpt2() {
  9258. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9259. const int64_t n_embd_head = hparams.n_embd_head_v;
  9260. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9261. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9262. struct ggml_tensor * cur;
  9263. struct ggml_tensor * pos;
  9264. struct ggml_tensor * inpL;
  9265. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9266. // inp_pos - contains the positions
  9267. struct ggml_tensor * inp_pos = build_inp_pos();
  9268. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9269. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9270. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  9271. cb(pos, "pos_embd", -1);
  9272. inpL = ggml_add(ctx0, inpL, pos);
  9273. cb(inpL, "inpL", -1);
  9274. for (int il = 0; il < n_layer; ++il) {
  9275. cur = llm_build_norm(ctx0, inpL, hparams,
  9276. model.layers[il].attn_norm,
  9277. model.layers[il].attn_norm_b,
  9278. LLM_NORM, cb, il);
  9279. cb(cur, "attn_norm", il);
  9280. // self-attention
  9281. {
  9282. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9283. cb(cur, "wqkv", il);
  9284. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9285. cb(cur, "bqkv", il);
  9286. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9287. 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)));
  9288. 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)));
  9289. cb(Qcur, "Qcur", il);
  9290. cb(Kcur, "Kcur", il);
  9291. cb(Vcur, "Vcur", il);
  9292. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  9293. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9294. model.layers[il].wo, model.layers[il].bo,
  9295. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9296. }
  9297. if (il == n_layer - 1) {
  9298. // skip computing output for unused tokens
  9299. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9300. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9301. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9302. }
  9303. // add the input
  9304. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9305. cb(ffn_inp, "ffn_inp", il);
  9306. // FF
  9307. {
  9308. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9309. model.layers[il].ffn_norm,
  9310. model.layers[il].ffn_norm_b,
  9311. LLM_NORM, cb, il);
  9312. cb(cur, "ffn_norm", il);
  9313. cur = llm_build_ffn(ctx0, lctx, cur,
  9314. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9315. NULL, NULL, NULL,
  9316. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9317. NULL,
  9318. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9319. cb(cur, "ffn_out", il);
  9320. }
  9321. cur = ggml_add(ctx0, cur, ffn_inp);
  9322. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9323. cb(cur, "l_out", il);
  9324. // input for next layer
  9325. inpL = cur;
  9326. }
  9327. cur = llm_build_norm(ctx0, inpL, hparams,
  9328. model.output_norm,
  9329. model.output_norm_b,
  9330. LLM_NORM, cb, -1);
  9331. cb(cur, "result_norm", -1);
  9332. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9333. cb(cur, "result_output", -1);
  9334. ggml_build_forward_expand(gf, cur);
  9335. return gf;
  9336. }
  9337. struct ggml_cgraph * build_codeshell() {
  9338. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9339. const int64_t n_embd_head = hparams.n_embd_head_v;
  9340. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9341. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9342. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9343. struct ggml_tensor * cur;
  9344. struct ggml_tensor * inpL;
  9345. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9346. // inp_pos - contains the positions
  9347. struct ggml_tensor * inp_pos = build_inp_pos();
  9348. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9349. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9350. for (int il = 0; il < n_layer; ++il) {
  9351. cur = llm_build_norm(ctx0, inpL, hparams,
  9352. model.layers[il].attn_norm,
  9353. model.layers[il].attn_norm_b,
  9354. LLM_NORM, cb, il);
  9355. cb(cur, "attn_norm", il);
  9356. // self-attention
  9357. {
  9358. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  9359. cb(cur, "wqkv", il);
  9360. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9361. cb(cur, "bqkv", il);
  9362. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9363. 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)));
  9364. 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)));
  9365. cb(tmpq, "tmpq", il);
  9366. cb(tmpk, "tmpk", il);
  9367. cb(Vcur, "Vcur", il);
  9368. struct ggml_tensor * Qcur = ggml_rope_ext(
  9369. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9370. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9371. ext_factor, attn_factor, beta_fast, beta_slow
  9372. );
  9373. cb(Qcur, "Qcur", il);
  9374. struct ggml_tensor * Kcur = ggml_rope_ext(
  9375. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9376. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9377. ext_factor, attn_factor, beta_fast, beta_slow
  9378. );
  9379. cb(Kcur, "Kcur", il);
  9380. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9381. model.layers[il].wo, model.layers[il].bo,
  9382. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9383. }
  9384. if (il == n_layer - 1) {
  9385. // skip computing output for unused tokens
  9386. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9387. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9388. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9389. }
  9390. // add the input
  9391. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9392. cb(ffn_inp, "ffn_inp", il);
  9393. // FF
  9394. {
  9395. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9396. model.layers[il].ffn_norm,
  9397. model.layers[il].ffn_norm_b,
  9398. LLM_NORM, cb, il);
  9399. cb(cur, "ffn_norm", il);
  9400. cur = llm_build_ffn(ctx0, lctx, cur,
  9401. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9402. NULL, NULL, NULL,
  9403. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9404. NULL,
  9405. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9406. cb(cur, "ffn_out", il);
  9407. }
  9408. cur = ggml_add(ctx0, cur, ffn_inp);
  9409. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9410. cb(cur, "l_out", il);
  9411. // input for next layer
  9412. inpL = cur;
  9413. }
  9414. cur = llm_build_norm(ctx0, inpL, hparams,
  9415. model.output_norm,
  9416. model.output_norm_b,
  9417. LLM_NORM, cb, -1);
  9418. cb(cur, "result_norm", -1);
  9419. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9420. cb(cur, "result_output", -1);
  9421. ggml_build_forward_expand(gf, cur);
  9422. return gf;
  9423. }
  9424. struct ggml_cgraph * build_orion() {
  9425. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9426. const int64_t n_embd_head = hparams.n_embd_head_v;
  9427. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9428. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9429. struct ggml_tensor * cur;
  9430. struct ggml_tensor * inpL;
  9431. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9432. // inp_pos - contains the positions
  9433. struct ggml_tensor * inp_pos = build_inp_pos();
  9434. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9435. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9436. for (int il = 0; il < n_layer; ++il) {
  9437. struct ggml_tensor * inpSA = inpL;
  9438. // norm
  9439. cur = llm_build_norm(ctx0, inpL, hparams,
  9440. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9441. LLM_NORM, cb, il);
  9442. cb(cur, "attn_norm", il);
  9443. // self-attention
  9444. {
  9445. // compute Q and K and RoPE them
  9446. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9447. cb(Qcur, "Qcur", il);
  9448. // if (model.layers[il].bq) {
  9449. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9450. // cb(Qcur, "Qcur", il);
  9451. // }
  9452. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9453. cb(Kcur, "Kcur", il);
  9454. // if (model.layers[il].bk) {
  9455. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9456. // cb(Kcur, "Kcur", il);
  9457. // }
  9458. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9459. cb(Vcur, "Vcur", il);
  9460. // if (model.layers[il].bv) {
  9461. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9462. // cb(Vcur, "Vcur", il);
  9463. // }
  9464. Qcur = ggml_rope_ext(
  9465. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9466. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9467. ext_factor, attn_factor, beta_fast, beta_slow
  9468. );
  9469. cb(Qcur, "Qcur", il);
  9470. Kcur = ggml_rope_ext(
  9471. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9472. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9473. ext_factor, attn_factor, beta_fast, beta_slow
  9474. );
  9475. cb(Kcur, "Kcur", il);
  9476. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9477. model.layers[il].wo, NULL,
  9478. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9479. }
  9480. if (il == n_layer - 1) {
  9481. // skip computing output for unused tokens
  9482. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9483. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9484. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9485. }
  9486. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9487. cb(ffn_inp, "ffn_inp", il);
  9488. // feed-forward network
  9489. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9490. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9491. LLM_NORM, cb, il);
  9492. cb(cur, "ffn_norm", il);
  9493. cur = llm_build_ffn(ctx0, lctx, cur,
  9494. model.layers[il].ffn_up, NULL, NULL,
  9495. model.layers[il].ffn_gate, NULL, NULL,
  9496. model.layers[il].ffn_down, NULL, NULL,
  9497. NULL,
  9498. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9499. cb(cur, "ffn_out", il);
  9500. cur = ggml_add(ctx0, cur, ffn_inp);
  9501. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9502. cb(cur, "l_out", il);
  9503. // input for next layer
  9504. inpL = cur;
  9505. }
  9506. cur = inpL;
  9507. cur = llm_build_norm(ctx0, cur, hparams,
  9508. model.output_norm, model.output_norm_b,
  9509. LLM_NORM, cb, -1);
  9510. cb(cur, "result_norm", -1);
  9511. // lm_head
  9512. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9513. cb(cur, "result_output", -1);
  9514. ggml_build_forward_expand(gf, cur);
  9515. return gf;
  9516. }
  9517. struct ggml_cgraph * build_internlm2() {
  9518. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9519. const int64_t n_embd_head = hparams.n_embd_head_v;
  9520. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9521. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9522. struct ggml_tensor * cur;
  9523. struct ggml_tensor * inpL;
  9524. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9525. // inp_pos - contains the positions
  9526. struct ggml_tensor * inp_pos = build_inp_pos();
  9527. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9528. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9529. for (int il = 0; il < n_layer; ++il) {
  9530. struct ggml_tensor * inpSA = inpL;
  9531. // norm
  9532. cur = llm_build_norm(ctx0, inpL, hparams,
  9533. model.layers[il].attn_norm, NULL,
  9534. LLM_NORM_RMS, cb, il);
  9535. cb(cur, "attn_norm", il);
  9536. // self-attention
  9537. {
  9538. // compute Q and K and RoPE them
  9539. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9540. cb(Qcur, "Qcur", il);
  9541. if (model.layers[il].bq) {
  9542. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9543. cb(Qcur, "Qcur", il);
  9544. }
  9545. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9546. cb(Kcur, "Kcur", il);
  9547. if (model.layers[il].bk) {
  9548. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9549. cb(Kcur, "Kcur", il);
  9550. }
  9551. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9552. cb(Vcur, "Vcur", il);
  9553. if (model.layers[il].bv) {
  9554. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9555. cb(Vcur, "Vcur", il);
  9556. }
  9557. Qcur = ggml_rope_ext(
  9558. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9559. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9560. ext_factor, attn_factor, beta_fast, beta_slow
  9561. );
  9562. cb(Qcur, "Qcur", il);
  9563. Kcur = ggml_rope_ext(
  9564. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9565. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9566. ext_factor, attn_factor, beta_fast, beta_slow
  9567. );
  9568. cb(Kcur, "Kcur", il);
  9569. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9570. model.layers[il].wo, model.layers[il].bo,
  9571. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9572. }
  9573. if (il == n_layer - 1) {
  9574. // skip computing output for unused tokens
  9575. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9576. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9577. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9578. }
  9579. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9580. cb(ffn_inp, "ffn_inp", il);
  9581. // feed-forward network
  9582. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9583. model.layers[il].ffn_norm, NULL,
  9584. LLM_NORM_RMS, cb, il);
  9585. cb(cur, "ffn_norm", il);
  9586. cur = llm_build_ffn(ctx0, lctx, cur,
  9587. model.layers[il].ffn_up, NULL, NULL,
  9588. model.layers[il].ffn_gate, NULL, NULL,
  9589. model.layers[il].ffn_down, NULL, NULL,
  9590. NULL,
  9591. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9592. cb(cur, "ffn_out", il);
  9593. cur = ggml_add(ctx0, cur, ffn_inp);
  9594. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9595. cb(cur, "l_out", il);
  9596. // input for next layer
  9597. inpL = cur;
  9598. }
  9599. cur = inpL;
  9600. cur = llm_build_norm(ctx0, cur, hparams,
  9601. model.output_norm, NULL,
  9602. LLM_NORM_RMS, cb, -1);
  9603. cb(cur, "result_norm", -1);
  9604. // lm_head
  9605. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9606. cb(cur, "result_output", -1);
  9607. ggml_build_forward_expand(gf, cur);
  9608. return gf;
  9609. }
  9610. // ref: https://arxiv.org/abs/2203.03466
  9611. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  9612. // based on the original build_llama() function
  9613. struct ggml_cgraph * build_minicpm() {
  9614. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9615. const int64_t n_embd_head = hparams.n_embd_head_v;
  9616. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9617. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9618. const int64_t n_embd = hparams.n_embd;
  9619. //TODO: if the model varies, these parameters need to be read from the model
  9620. const int64_t n_embd_base = 256;
  9621. const float scale_embd = 12.0f;
  9622. const float scale_depth = 1.4f;
  9623. struct ggml_tensor * cur;
  9624. struct ggml_tensor * inpL;
  9625. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9626. // scale the input embeddings
  9627. inpL = ggml_scale(ctx0, inpL, scale_embd);
  9628. cb(inpL, "inp_scaled", -1);
  9629. // inp_pos - contains the positions
  9630. struct ggml_tensor * inp_pos = build_inp_pos();
  9631. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9632. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9633. for (int il = 0; il < n_layer; ++il) {
  9634. struct ggml_tensor * inpSA = inpL;
  9635. // norm
  9636. cur = llm_build_norm(ctx0, inpL, hparams,
  9637. model.layers[il].attn_norm, NULL,
  9638. LLM_NORM_RMS, cb, il);
  9639. cb(cur, "attn_norm", il);
  9640. // self-attention
  9641. {
  9642. // compute Q and K and RoPE them
  9643. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9644. cb(Qcur, "Qcur", il);
  9645. if (model.layers[il].bq) {
  9646. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9647. cb(Qcur, "Qcur", il);
  9648. }
  9649. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9650. cb(Kcur, "Kcur", il);
  9651. if (model.layers[il].bk) {
  9652. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9653. cb(Kcur, "Kcur", il);
  9654. }
  9655. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9656. cb(Vcur, "Vcur", il);
  9657. if (model.layers[il].bv) {
  9658. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9659. cb(Vcur, "Vcur", il);
  9660. }
  9661. Qcur = ggml_rope_ext(
  9662. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9663. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9664. ext_factor, attn_factor, beta_fast, beta_slow
  9665. );
  9666. cb(Qcur, "Qcur", il);
  9667. Kcur = ggml_rope_ext(
  9668. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9669. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9670. ext_factor, attn_factor, beta_fast, beta_slow
  9671. );
  9672. cb(Kcur, "Kcur", il);
  9673. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9674. model.layers[il].wo, model.layers[il].bo,
  9675. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9676. }
  9677. if (il == n_layer - 1) {
  9678. // skip computing output for unused tokens
  9679. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9680. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9681. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9682. }
  9683. // scale_res - scale the hidden states for residual connection
  9684. const float scale_res = scale_depth/sqrtf(float(n_layer));
  9685. cur = ggml_scale(ctx0, cur, scale_res);
  9686. cb(cur, "hidden_scaled", -1);
  9687. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9688. cb(ffn_inp, "ffn_inp", il);
  9689. // feed-forward network
  9690. {
  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. cur = llm_build_ffn(ctx0, lctx, cur,
  9696. model.layers[il].ffn_up, NULL, NULL,
  9697. model.layers[il].ffn_gate, NULL, NULL,
  9698. model.layers[il].ffn_down, NULL, NULL,
  9699. NULL,
  9700. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9701. cb(cur, "ffn_out", il);
  9702. }
  9703. // scale the hidden states for residual connection
  9704. cur = ggml_scale(ctx0, cur, scale_res);
  9705. cb(cur, "hidden_scaled_ffn", -1);
  9706. cur = ggml_add(ctx0, cur, ffn_inp);
  9707. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9708. cb(cur, "l_out", il);
  9709. // input for next layer
  9710. inpL = cur;
  9711. }
  9712. cur = inpL;
  9713. cur = llm_build_norm(ctx0, cur, hparams,
  9714. model.output_norm, NULL,
  9715. LLM_NORM_RMS, cb, -1);
  9716. cb(cur, "result_norm", -1);
  9717. // lm_head scaling
  9718. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  9719. cur = ggml_scale(ctx0, cur, scale_lmhead);
  9720. cb(cur, "lmhead_scaling", -1);
  9721. // lm_head
  9722. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9723. cb(cur, "result_output", -1);
  9724. ggml_build_forward_expand(gf, cur);
  9725. return gf;
  9726. }
  9727. struct ggml_cgraph * build_gemma() {
  9728. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9729. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9730. struct ggml_tensor * cur;
  9731. struct ggml_tensor * inpL;
  9732. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9733. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9734. cb(inpL, "inp_scaled", -1);
  9735. // inp_pos - contains the positions
  9736. struct ggml_tensor * inp_pos = build_inp_pos();
  9737. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9738. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9739. for (int il = 0; il < n_layer; ++il) {
  9740. // norm
  9741. cur = llm_build_norm(ctx0, inpL, hparams,
  9742. model.layers[il].attn_norm, NULL,
  9743. LLM_NORM_RMS, cb, il);
  9744. cb(cur, "attn_norm", il);
  9745. // self-attention
  9746. {
  9747. // compute Q and K and RoPE them
  9748. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9749. cb(Qcur, "Qcur", il);
  9750. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9751. cb(Kcur, "Kcur", il);
  9752. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9753. cb(Vcur, "Vcur", il);
  9754. Qcur = ggml_rope_ext(
  9755. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9756. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9757. ext_factor, attn_factor, beta_fast, beta_slow);
  9758. cb(Qcur, "Qcur", il);
  9759. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  9760. cb(Qcur, "Qcur_scaled", il);
  9761. Kcur = ggml_rope_ext(
  9762. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9763. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9764. ext_factor, attn_factor, beta_fast, beta_slow);
  9765. cb(Kcur, "Kcur", il);
  9766. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9767. model.layers[il].wo, NULL,
  9768. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9769. }
  9770. if (il == n_layer - 1) {
  9771. // skip computing output for unused tokens
  9772. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9773. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9774. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9775. }
  9776. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9777. cb(sa_out, "sa_out", il);
  9778. cur = llm_build_norm(ctx0, sa_out, hparams,
  9779. model.layers[il].ffn_norm, NULL,
  9780. LLM_NORM_RMS, cb, il);
  9781. cb(cur, "ffn_norm", il);
  9782. // feed-forward network
  9783. {
  9784. cur = llm_build_ffn(ctx0, lctx, cur,
  9785. model.layers[il].ffn_up, NULL, NULL,
  9786. model.layers[il].ffn_gate, NULL, NULL,
  9787. model.layers[il].ffn_down, NULL, NULL,
  9788. NULL,
  9789. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9790. cb(cur, "ffn_out", il);
  9791. }
  9792. cur = ggml_add(ctx0, cur, sa_out);
  9793. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9794. cb(cur, "l_out", il);
  9795. // input for next layer
  9796. inpL = cur;
  9797. }
  9798. cur = inpL;
  9799. cur = llm_build_norm(ctx0, cur, hparams,
  9800. model.output_norm, NULL,
  9801. LLM_NORM_RMS, cb, -1);
  9802. cb(cur, "result_norm", -1);
  9803. // lm_head
  9804. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9805. cb(cur, "result_output", -1);
  9806. ggml_build_forward_expand(gf, cur);
  9807. return gf;
  9808. }
  9809. struct ggml_cgraph * build_gemma2() {
  9810. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9811. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  9812. struct ggml_tensor * cur;
  9813. struct ggml_tensor * inpL;
  9814. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9815. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  9816. cb(inpL, "inp_scaled", -1);
  9817. // inp_pos - contains the positions
  9818. struct ggml_tensor * inp_pos = build_inp_pos();
  9819. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9820. // gemma 2 requires different mask for layers using sliding window (SWA)
  9821. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(true);
  9822. struct ggml_tensor * KQ_mask_swa = build_inp_KQ_mask_swa(true);
  9823. for (int il = 0; il < n_layer; ++il) {
  9824. // (il % 2) layers use SWA
  9825. struct ggml_tensor * KQ_mask_l = (il % 2 == 0) ? KQ_mask_swa : KQ_mask;
  9826. // norm
  9827. cur = llm_build_norm(ctx0, inpL, hparams,
  9828. model.layers[il].attn_norm, NULL,
  9829. LLM_NORM_RMS, cb, il);
  9830. cb(cur, "attn_norm", il);
  9831. // self-attention
  9832. {
  9833. // compute Q and K and RoPE them
  9834. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9835. cb(Qcur, "Qcur", il);
  9836. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9837. cb(Kcur, "Kcur", il);
  9838. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9839. cb(Vcur, "Vcur", il);
  9840. Qcur = ggml_rope_ext(
  9841. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  9842. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9843. ext_factor, attn_factor, beta_fast, beta_slow);
  9844. cb(Qcur, "Qcur", il);
  9845. // ref: https://github.com/google/gemma_pytorch/commit/03e657582d17cb5a8617ebf333c1c16f3694670e
  9846. switch (model.type) {
  9847. case e_model::MODEL_9B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k))); break;
  9848. case e_model::MODEL_27B: Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd / n_head))); break;
  9849. default: GGML_ABORT("fatal error");
  9850. };
  9851. cb(Qcur, "Qcur_scaled", il);
  9852. Kcur = ggml_rope_ext(
  9853. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  9854. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9855. ext_factor, attn_factor, beta_fast, beta_slow);
  9856. cb(Kcur, "Kcur", il);
  9857. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9858. model.layers[il].wo, NULL,
  9859. Kcur, Vcur, Qcur, KQ_mask_l, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  9860. }
  9861. cur = llm_build_norm(ctx0, cur, hparams,
  9862. model.layers[il].attn_post_norm, NULL,
  9863. LLM_NORM_RMS, cb, il);
  9864. cb(cur, "attn_post_norm", il);
  9865. if (il == n_layer - 1) {
  9866. // skip computing output for unused tokens
  9867. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9868. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9869. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9870. }
  9871. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  9872. cb(sa_out, "sa_out", il);
  9873. cur = llm_build_norm(ctx0, sa_out, hparams,
  9874. model.layers[il].ffn_norm, NULL,
  9875. LLM_NORM_RMS, cb, il);
  9876. cb(cur, "ffn_norm", il);
  9877. // feed-forward network
  9878. {
  9879. cur = llm_build_ffn(ctx0, lctx, cur,
  9880. model.layers[il].ffn_up, NULL, NULL,
  9881. model.layers[il].ffn_gate, NULL, NULL,
  9882. model.layers[il].ffn_down, NULL, NULL,
  9883. NULL,
  9884. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  9885. cb(cur, "ffn_out", il);
  9886. }
  9887. cur = llm_build_norm(ctx0, cur, hparams,
  9888. model.layers[il].ffn_post_norm, NULL,
  9889. LLM_NORM_RMS, cb, -1);
  9890. cb(cur, "ffn_post_norm", -1);
  9891. cur = ggml_add(ctx0, cur, sa_out);
  9892. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9893. cb(cur, "l_out", il);
  9894. // input for next layer
  9895. inpL = cur;
  9896. }
  9897. cur = inpL;
  9898. cur = llm_build_norm(ctx0, cur, hparams,
  9899. model.output_norm, NULL,
  9900. LLM_NORM_RMS, cb, -1);
  9901. cb(cur, "result_norm", -1);
  9902. // lm_head
  9903. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  9904. // final logit soft-capping
  9905. cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
  9906. cur = ggml_tanh(ctx0, cur);
  9907. cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
  9908. cb(cur, "result_output", -1);
  9909. ggml_build_forward_expand(gf, cur);
  9910. return gf;
  9911. }
  9912. struct ggml_cgraph * build_starcoder2() {
  9913. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  9914. const int64_t n_embd_head = hparams.n_embd_head_v;
  9915. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9916. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9917. struct ggml_tensor * cur;
  9918. struct ggml_tensor * inpL;
  9919. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9920. // inp_pos - contains the positions
  9921. struct ggml_tensor * inp_pos = build_inp_pos();
  9922. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9923. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9924. for (int il = 0; il < n_layer; ++il) {
  9925. struct ggml_tensor * inpSA = inpL;
  9926. // norm
  9927. cur = llm_build_norm(ctx0, inpL, hparams,
  9928. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  9929. LLM_NORM, cb, il);
  9930. cb(cur, "attn_norm", il);
  9931. // self-attention
  9932. {
  9933. // compute Q and K and RoPE them
  9934. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  9935. cb(Qcur, "Qcur", il);
  9936. if (model.layers[il].bq) {
  9937. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  9938. cb(Qcur, "Qcur", il);
  9939. }
  9940. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  9941. cb(Kcur, "Kcur", il);
  9942. if (model.layers[il].bk) {
  9943. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  9944. cb(Kcur, "Kcur", il);
  9945. }
  9946. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  9947. cb(Vcur, "Vcur", il);
  9948. if (model.layers[il].bv) {
  9949. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  9950. cb(Vcur, "Vcur", il);
  9951. }
  9952. Qcur = ggml_rope_ext(
  9953. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9954. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9955. ext_factor, attn_factor, beta_fast, beta_slow
  9956. );
  9957. cb(Qcur, "Qcur", il);
  9958. Kcur = ggml_rope_ext(
  9959. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9960. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  9961. ext_factor, attn_factor, beta_fast, beta_slow
  9962. );
  9963. cb(Kcur, "Kcur", il);
  9964. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  9965. model.layers[il].wo, model.layers[il].bo,
  9966. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9967. }
  9968. if (il == n_layer - 1) {
  9969. // skip computing output for unused tokens
  9970. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9971. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9972. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9973. }
  9974. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9975. cb(ffn_inp, "ffn_inp", il);
  9976. // feed-forward network
  9977. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9978. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  9979. LLM_NORM, cb, il);
  9980. cb(cur, "ffn_norm", il);
  9981. cur = llm_build_ffn(ctx0, lctx, cur,
  9982. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  9983. NULL, NULL, NULL,
  9984. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  9985. NULL,
  9986. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9987. cb(cur, "ffn_out", il);
  9988. cur = ggml_add(ctx0, cur, ffn_inp);
  9989. cur = lctx.cvec.apply_to(ctx0, cur, il);
  9990. cb(cur, "l_out", il);
  9991. // input for next layer
  9992. inpL = cur;
  9993. }
  9994. cur = inpL;
  9995. cur = llm_build_norm(ctx0, cur, hparams,
  9996. model.output_norm, model.output_norm_b,
  9997. LLM_NORM, cb, -1);
  9998. cb(cur, "result_norm", -1);
  9999. // lm_head
  10000. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10001. cb(cur, "result_output", -1);
  10002. ggml_build_forward_expand(gf, cur);
  10003. return gf;
  10004. }
  10005. struct ggml_cgraph * build_mamba() {
  10006. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10007. const int64_t d_model = n_embd;
  10008. const int64_t d_conv = hparams.ssm_d_conv;
  10009. const int64_t d_inner = hparams.ssm_d_inner;
  10010. GGML_ASSERT(2 * d_model == d_inner);
  10011. const int64_t d_state = hparams.ssm_d_state;
  10012. const int64_t dt_rank = hparams.ssm_dt_rank;
  10013. struct ggml_tensor * cur;
  10014. struct ggml_tensor * inpL;
  10015. // {n_embd, n_tokens}
  10016. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10017. struct ggml_tensor * state_mask = build_inp_s_mask();
  10018. struct ggml_tensor * state_seq = build_inp_s_seq();
  10019. for (int il = 0; il < n_layer; ++il) {
  10020. // (ab)using the KV cache to store the states
  10021. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  10022. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  10023. // clear states of sequences which are starting at the beginning of this batch
  10024. {
  10025. conv_states = ggml_mul(ctx0,
  10026. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  10027. state_mask);
  10028. ssm_states = ggml_mul(ctx0,
  10029. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  10030. state_mask);
  10031. }
  10032. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  10033. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  10034. // norm
  10035. cur = llm_build_norm(ctx0, inpL, hparams,
  10036. model.layers[il].attn_norm, NULL,
  10037. LLM_NORM_RMS, cb, il);
  10038. cb(cur, "attn_norm", il);
  10039. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  10040. struct ggml_tensor * xz = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_in, cur);
  10041. // split the above in two
  10042. // => {d_inner, n_tokens}
  10043. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  10044. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  10045. // conv
  10046. {
  10047. // Custom operator which is needed only to ease simultaneous sequence processing.
  10048. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  10049. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  10050. // then element-wise multiply that with the conv1d weigth,
  10051. // then sum the elements of each row,
  10052. // (the last two steps are a dot product over rows (also doable with mul_mat))
  10053. // then permute away the ne[0] dimension,
  10054. // and then you're left with the resulting x tensor.
  10055. // The new conv_states is the last (d_conv - 1) columns
  10056. // of the last 3rd dimensional "layer" of the self-overlapping view.
  10057. // For simultaneous sequences, it's more complicated.
  10058. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  10059. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  10060. ggml_build_forward_expand(gf,
  10061. ggml_cpy(ctx0,
  10062. ggml_view_2d(ctx0, x_conv, d_conv - 1, d_inner*n_kv, d_conv*ggml_element_size(x_conv), (1+d_inner*n_tokens)*ggml_element_size(x_conv)),
  10063. ggml_view_1d(ctx0, kv_self.k_l[il], (d_conv - 1)*(d_inner)*(n_kv), kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(x_conv))));
  10064. // extract x from x_conv
  10065. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  10066. // bias
  10067. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  10068. x = ggml_silu(ctx0, x);
  10069. }
  10070. // ssm
  10071. {
  10072. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  10073. struct ggml_tensor * x_db = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_x, x);
  10074. // split
  10075. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  10076. struct ggml_tensor * B = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*dt_rank);
  10077. struct ggml_tensor * C = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*(dt_rank+d_state));
  10078. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  10079. dt = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_dt, dt);
  10080. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  10081. // Custom operator to optimize the parallel associative scan
  10082. // as described in the Annex D of the Mamba paper.
  10083. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  10084. // because only a single tensor can be returned.
  10085. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  10086. // store last states (the second part of y_ssm_states)
  10087. ggml_build_forward_expand(gf,
  10088. ggml_cpy(ctx0,
  10089. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  10090. ggml_view_1d(ctx0, kv_self.v_l[il], d_state*d_inner*n_kv, kv_head*d_state*d_inner*ggml_element_size(ssm_states))));
  10091. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  10092. if (il == n_layer - 1) {
  10093. // skip computing output for unused tokens
  10094. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10095. x = ggml_get_rows(ctx0, x, inp_out_ids);
  10096. y = ggml_get_rows(ctx0, y, inp_out_ids);
  10097. z = ggml_get_rows(ctx0, z, inp_out_ids);
  10098. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10099. }
  10100. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  10101. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  10102. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  10103. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  10104. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ssm_out, y);
  10105. }
  10106. // residual
  10107. cur = ggml_add(ctx0, cur, inpL);
  10108. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10109. cb(cur, "l_out", il);
  10110. // input for next layer
  10111. inpL = cur;
  10112. }
  10113. // final rmsnorm
  10114. cur = llm_build_norm(ctx0, inpL, hparams,
  10115. model.output_norm, NULL,
  10116. LLM_NORM_RMS, cb, -1);
  10117. cb(cur, "result_norm", -1);
  10118. // lm_head
  10119. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10120. cb(cur, "result_output", -1);
  10121. ggml_build_forward_expand(gf, cur);
  10122. return gf;
  10123. }
  10124. struct ggml_cgraph * build_command_r() {
  10125. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10126. const int64_t n_embd_head = hparams.n_embd_head_v;
  10127. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10128. const float f_logit_scale = hparams.f_logit_scale;
  10129. struct ggml_tensor * cur;
  10130. struct ggml_tensor * inpL;
  10131. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10132. // inp_pos - contains the positions
  10133. struct ggml_tensor * inp_pos = build_inp_pos();
  10134. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10135. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10136. for (int il = 0; il < n_layer; ++il) {
  10137. // norm
  10138. cur = llm_build_norm(ctx0, inpL, hparams,
  10139. model.layers[il].attn_norm, NULL,
  10140. LLM_NORM, cb, il);
  10141. cb(cur, "attn_norm", il);
  10142. struct ggml_tensor * ffn_inp = cur;
  10143. // self-attention
  10144. {
  10145. // compute Q and K and RoPE them
  10146. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10147. cb(Qcur, "Qcur", il);
  10148. if (model.layers[il].bq) {
  10149. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10150. cb(Qcur, "Qcur", il);
  10151. }
  10152. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10153. cb(Kcur, "Kcur", il);
  10154. if (model.layers[il].bk) {
  10155. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10156. cb(Kcur, "Kcur", il);
  10157. }
  10158. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10159. cb(Vcur, "Vcur", il);
  10160. if (model.layers[il].bv) {
  10161. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10162. cb(Vcur, "Vcur", il);
  10163. }
  10164. if (model.layers[il].attn_q_norm) {
  10165. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  10166. ggml_element_size(Qcur) * n_embd_head,
  10167. ggml_element_size(Qcur) * n_embd_head * n_head,
  10168. 0);
  10169. cb(Qcur, "Qcur", il);
  10170. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  10171. ggml_element_size(Kcur) * n_embd_head,
  10172. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  10173. 0);
  10174. cb(Kcur, "Kcur", il);
  10175. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10176. model.layers[il].attn_q_norm,
  10177. NULL,
  10178. LLM_NORM, cb, il);
  10179. cb(Qcur, "Qcur", il);
  10180. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10181. model.layers[il].attn_k_norm,
  10182. NULL,
  10183. LLM_NORM, cb, il);
  10184. cb(Kcur, "Kcur", il);
  10185. }
  10186. Qcur = ggml_rope_ext(
  10187. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10188. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10189. ext_factor, attn_factor, beta_fast, beta_slow
  10190. );
  10191. cb(Qcur, "Qcur", il);
  10192. Kcur = ggml_rope_ext(
  10193. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10194. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10195. ext_factor, attn_factor, beta_fast, beta_slow
  10196. );
  10197. cb(Kcur, "Kcur", il);
  10198. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10199. model.layers[il].wo, model.layers[il].bo,
  10200. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10201. }
  10202. if (il == n_layer - 1) {
  10203. // skip computing output for unused tokens
  10204. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10205. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10206. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10207. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  10208. }
  10209. struct ggml_tensor * attn_out = cur;
  10210. // feed-forward network
  10211. {
  10212. cur = llm_build_ffn(ctx0, lctx, ffn_inp,
  10213. model.layers[il].ffn_up, NULL, NULL,
  10214. model.layers[il].ffn_gate, NULL, NULL,
  10215. model.layers[il].ffn_down, NULL, NULL,
  10216. NULL,
  10217. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10218. cb(cur, "ffn_out", il);
  10219. }
  10220. // add together residual + FFN + self-attention
  10221. cur = ggml_add(ctx0, cur, inpL);
  10222. cur = ggml_add(ctx0, cur, attn_out);
  10223. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10224. cb(cur, "l_out", il);
  10225. // input for next layer
  10226. inpL = cur;
  10227. }
  10228. cur = inpL;
  10229. cur = llm_build_norm(ctx0, cur, hparams,
  10230. model.output_norm, NULL,
  10231. LLM_NORM, cb, -1);
  10232. cb(cur, "result_norm", -1);
  10233. // lm_head
  10234. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10235. if (f_logit_scale) {
  10236. cur = ggml_scale(ctx0, cur, f_logit_scale);
  10237. }
  10238. cb(cur, "result_output", -1);
  10239. ggml_build_forward_expand(gf, cur);
  10240. return gf;
  10241. }
  10242. // ref: https://allenai.org/olmo
  10243. // based on the original build_llama() function, changes:
  10244. // * non-parametric layer norm
  10245. // * clamp qkv
  10246. // * removed bias
  10247. // * removed MoE
  10248. struct ggml_cgraph * build_olmo() {
  10249. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10250. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10251. int32_t n_tokens = this->n_tokens;
  10252. const int64_t n_embd_head = hparams.n_embd_head_v;
  10253. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10254. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10255. struct ggml_tensor * cur;
  10256. struct ggml_tensor * inpL;
  10257. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10258. // inp_pos - contains the positions
  10259. struct ggml_tensor * inp_pos = build_inp_pos();
  10260. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10261. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10262. for (int il = 0; il < n_layer; ++il) {
  10263. struct ggml_tensor * inpSA = inpL;
  10264. // norm
  10265. cur = llm_build_norm(ctx0, inpL, hparams,
  10266. NULL, NULL,
  10267. LLM_NORM, cb, il);
  10268. cb(cur, "attn_norm", il);
  10269. // self-attention
  10270. {
  10271. // compute Q and K and RoPE them
  10272. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10273. cb(Qcur, "Qcur", il);
  10274. if (hparams.f_clamp_kqv > 0.0f) {
  10275. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10276. cb(Qcur, "Qcur", il);
  10277. }
  10278. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10279. cb(Kcur, "Kcur", il);
  10280. if (hparams.f_clamp_kqv > 0.0f) {
  10281. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10282. cb(Kcur, "Kcur", il);
  10283. }
  10284. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10285. cb(Vcur, "Vcur", il);
  10286. if (hparams.f_clamp_kqv > 0.0f) {
  10287. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  10288. cb(Vcur, "Vcur", il);
  10289. }
  10290. Qcur = ggml_rope_ext(
  10291. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10292. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10293. ext_factor, attn_factor, beta_fast, beta_slow
  10294. );
  10295. cb(Qcur, "Qcur", il);
  10296. Kcur = ggml_rope_ext(
  10297. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10298. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10299. ext_factor, attn_factor, beta_fast, beta_slow
  10300. );
  10301. cb(Kcur, "Kcur", il);
  10302. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10303. model.layers[il].wo, nullptr,
  10304. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10305. }
  10306. if (il == n_layer - 1) {
  10307. // skip computing output for unused tokens
  10308. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10309. n_tokens = n_outputs;
  10310. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10311. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10312. }
  10313. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10314. cb(ffn_inp, "ffn_inp", il);
  10315. // feed-forward network
  10316. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10317. NULL, NULL,
  10318. LLM_NORM, cb, il);
  10319. cb(cur, "ffn_norm", il);
  10320. cur = llm_build_ffn(ctx0, lctx, cur,
  10321. model.layers[il].ffn_up, NULL, NULL,
  10322. model.layers[il].ffn_gate, NULL, NULL,
  10323. model.layers[il].ffn_down, NULL, NULL,
  10324. NULL,
  10325. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10326. cb(cur, "ffn_out", il);
  10327. cur = ggml_add(ctx0, cur, ffn_inp);
  10328. cb(cur, "ffn_out", il);
  10329. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10330. cb(cur, "l_out", il);
  10331. // input for next layer
  10332. inpL = cur;
  10333. }
  10334. cur = inpL;
  10335. cur = llm_build_norm(ctx0, cur, hparams,
  10336. NULL, NULL,
  10337. LLM_NORM, cb, -1);
  10338. cb(cur, "result_norm", -1);
  10339. // lm_head
  10340. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10341. cb(cur, "result_output", -1);
  10342. ggml_build_forward_expand(gf, cur);
  10343. return gf;
  10344. }
  10345. struct ggml_cgraph * build_openelm() {
  10346. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10347. const int64_t n_embd_head = hparams.n_embd_head_v;
  10348. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10349. struct ggml_tensor * cur;
  10350. struct ggml_tensor * inpL;
  10351. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10352. // inp_pos - contains the positions
  10353. struct ggml_tensor * inp_pos = build_inp_pos();
  10354. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10355. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10356. for (int il = 0; il < n_layer; ++il) {
  10357. const int64_t n_head = hparams.n_head(il);
  10358. const int64_t n_head_kv = hparams.n_head_kv(il);
  10359. const int64_t n_head_qkv = 2*n_head_kv + n_head;
  10360. cur = inpL;
  10361. struct ggml_tensor * residual = cur;
  10362. // norm
  10363. cur = llm_build_norm(ctx0, inpL, hparams,
  10364. model.layers[il].attn_norm, NULL,
  10365. LLM_NORM_RMS, cb, il);
  10366. cb(cur, "attn_norm", il);
  10367. // self-attention
  10368. {
  10369. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10370. cb(cur, "wqkv", il);
  10371. cur = ggml_reshape_3d(ctx0, cur, n_embd_head_k, n_head_qkv, n_tokens);
  10372. 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));
  10373. cb(Qcur, "Qcur", il);
  10374. 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));
  10375. cb(Kcur, "Kcur", il);
  10376. 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)));
  10377. cb(Vcur, "Vcur", il);
  10378. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  10379. model.layers[il].attn_q_norm, NULL,
  10380. LLM_NORM_RMS, cb, il);
  10381. cb(Qcur, "Qcur", il);
  10382. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  10383. model.layers[il].attn_k_norm, NULL,
  10384. LLM_NORM_RMS, cb, il);
  10385. cb(Kcur, "Kcur", il);
  10386. Qcur = ggml_rope_ext(
  10387. ctx0, Qcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10388. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10389. );
  10390. cb(Qcur, "Qcur", il);
  10391. Kcur = ggml_rope_ext(
  10392. ctx0, Kcur, inp_pos, NULL, n_rot, rope_type, n_ctx_orig,
  10393. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  10394. );
  10395. cb(Kcur, "Kcur", il);
  10396. Vcur = ggml_reshape_2d(ctx0, Vcur, n_embd_head * n_head_kv, n_tokens);
  10397. cb(Qcur, "Vcur", il);
  10398. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10399. model.layers[il].wo, NULL,
  10400. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10401. }
  10402. if (il == n_layer - 1) {
  10403. // skip computing output for unused tokens
  10404. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10405. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  10406. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10407. }
  10408. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  10409. cb(ffn_inp, "ffn_inp", il);
  10410. // feed-forward network
  10411. {
  10412. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10413. model.layers[il].ffn_norm, NULL,
  10414. LLM_NORM_RMS, cb, il);
  10415. cb(cur, "ffn_norm", il);
  10416. cur = llm_build_ffn(ctx0, lctx, cur,
  10417. model.layers[il].ffn_up, NULL, NULL,
  10418. model.layers[il].ffn_gate, NULL, NULL,
  10419. model.layers[il].ffn_down, NULL, NULL,
  10420. NULL,
  10421. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10422. cb(cur, "ffn_out", il);
  10423. }
  10424. cur = ggml_add(ctx0, cur, ffn_inp);
  10425. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10426. cb(cur, "l_out", il);
  10427. inpL = cur;
  10428. }
  10429. cur = inpL;
  10430. // norm
  10431. cur = llm_build_norm(ctx0, cur, hparams,
  10432. model.output_norm, NULL,
  10433. LLM_NORM_RMS, cb, -1);
  10434. cb(cur, "result_norm", -1);
  10435. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10436. cb(cur, "result_output", -1);
  10437. ggml_build_forward_expand(gf, cur);
  10438. return gf;
  10439. }
  10440. struct ggml_cgraph * build_gptneox() {
  10441. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10442. const int64_t n_embd_head = hparams.n_embd_head_v;
  10443. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10444. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10445. struct ggml_tensor * cur;
  10446. struct ggml_tensor * inpL;
  10447. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10448. // inp_pos - contains the positions
  10449. struct ggml_tensor * inp_pos = build_inp_pos();
  10450. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10451. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10452. for (int il = 0; il < n_layer; ++il) {
  10453. cur = llm_build_norm(ctx0, inpL, hparams,
  10454. model.layers[il].attn_norm,
  10455. model.layers[il].attn_norm_b,
  10456. LLM_NORM, cb, il);
  10457. cb(cur, "attn_norm", il);
  10458. // self-attention
  10459. {
  10460. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  10461. cb(cur, "wqkv", il);
  10462. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  10463. cb(cur, "bqkv", il);
  10464. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  10465. 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)));
  10466. 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)));
  10467. cb(Qcur, "Qcur", il);
  10468. cb(Kcur, "Kcur", il);
  10469. cb(Vcur, "Vcur", il);
  10470. Qcur = ggml_rope_ext(
  10471. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10472. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10473. ext_factor, attn_factor, beta_fast, beta_slow
  10474. );
  10475. cb(Qcur, "Qcur", il);
  10476. Kcur = ggml_rope_ext(
  10477. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10478. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10479. ext_factor, attn_factor, beta_fast, beta_slow
  10480. );
  10481. cb(Kcur, "Kcur", il);
  10482. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10483. model.layers[il].wo, model.layers[il].bo,
  10484. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10485. }
  10486. if (il == n_layer - 1) {
  10487. // skip computing output for unused tokens
  10488. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10489. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10490. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  10491. }
  10492. // ffn
  10493. if (hparams.use_par_res) {
  10494. // attention and ffn are computed in parallel
  10495. // x = x + attn(ln1(x)) + ffn(ln2(x))
  10496. struct ggml_tensor * attn_out = cur;
  10497. cur = llm_build_norm(ctx0, inpL, hparams,
  10498. model.layers[il].ffn_norm,
  10499. model.layers[il].ffn_norm_b,
  10500. LLM_NORM, cb, il);
  10501. cb(cur, "ffn_norm", il);
  10502. cur = llm_build_ffn(ctx0, lctx, cur,
  10503. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10504. NULL, NULL, NULL,
  10505. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10506. NULL,
  10507. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10508. cb(cur, "ffn_out", il);
  10509. cur = ggml_add(ctx0, cur, inpL);
  10510. cb(cur, "ffn_out", il);
  10511. cur = ggml_add(ctx0, cur, attn_out);
  10512. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10513. cb(cur, "l_out", il);
  10514. // input for next layer
  10515. inpL = cur;
  10516. } else {
  10517. // attention and ffn are computed sequentially
  10518. // x = x + attn(ln1(x))
  10519. // x = x + ffn(ln2(x))
  10520. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  10521. cb(ffn_inp, "ffn_inp", il);
  10522. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10523. model.layers[il].ffn_norm,
  10524. model.layers[il].ffn_norm_b,
  10525. LLM_NORM, cb, il);
  10526. cb(cur, "ffn_norm", il);
  10527. cur = llm_build_ffn(ctx0, lctx, cur,
  10528. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  10529. NULL, NULL, NULL,
  10530. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  10531. NULL,
  10532. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  10533. cb(cur, "ffn_out", il);
  10534. cur = ggml_add(ctx0, cur, ffn_inp);
  10535. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10536. cb(cur, "l_out", il);
  10537. // input for next layer
  10538. inpL = cur;
  10539. }
  10540. }
  10541. cur = llm_build_norm(ctx0, inpL, hparams,
  10542. model.output_norm,
  10543. model.output_norm_b,
  10544. LLM_NORM, cb, -1);
  10545. cb(cur, "result_norm", -1);
  10546. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10547. cb(cur, "result_output", -1);
  10548. ggml_build_forward_expand(gf, cur);
  10549. return gf;
  10550. }
  10551. struct ggml_cgraph * build_arctic() {
  10552. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10553. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10554. int32_t n_tokens = this->n_tokens;
  10555. const int64_t n_embd_head = hparams.n_embd_head_v;
  10556. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10557. GGML_ASSERT(n_embd_head == hparams.n_rot);
  10558. struct ggml_tensor * cur;
  10559. struct ggml_tensor * inpL;
  10560. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10561. // inp_pos - contains the positions
  10562. struct ggml_tensor * inp_pos = build_inp_pos();
  10563. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10564. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10565. for (int il = 0; il < n_layer; ++il) {
  10566. struct ggml_tensor * inpSA = inpL;
  10567. // norm
  10568. cur = llm_build_norm(ctx0, inpL, hparams,
  10569. model.layers[il].attn_norm, NULL,
  10570. LLM_NORM_RMS, cb, il);
  10571. cb(cur, "attn_norm", il);
  10572. // self-attention
  10573. {
  10574. // compute Q and K and RoPE them
  10575. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10576. cb(Qcur, "Qcur", il);
  10577. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10578. cb(Kcur, "Kcur", il);
  10579. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10580. cb(Vcur, "Vcur", il);
  10581. Qcur = ggml_rope_ext(
  10582. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10583. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10584. ext_factor, attn_factor, beta_fast, beta_slow
  10585. );
  10586. cb(Qcur, "Qcur", il);
  10587. Kcur = ggml_rope_ext(
  10588. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10589. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10590. ext_factor, attn_factor, beta_fast, beta_slow
  10591. );
  10592. cb(Kcur, "Kcur", il);
  10593. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10594. model.layers[il].wo, NULL,
  10595. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10596. }
  10597. if (il == n_layer - 1) {
  10598. // skip computing output for unused tokens
  10599. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10600. n_tokens = n_outputs;
  10601. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10602. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10603. }
  10604. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10605. cb(ffn_inp, "ffn_inp", il);
  10606. // feed-forward network
  10607. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10608. model.layers[il].ffn_norm, NULL,
  10609. LLM_NORM_RMS, cb, il);
  10610. cb(cur, "ffn_norm", il);
  10611. cur = llm_build_ffn(ctx0, lctx, cur,
  10612. model.layers[il].ffn_up, NULL, NULL,
  10613. model.layers[il].ffn_gate, NULL, NULL,
  10614. model.layers[il].ffn_down, NULL, NULL,
  10615. NULL,
  10616. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10617. cb(cur, "ffn_out", il);
  10618. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  10619. cb(ffn_out, "ffn_out", il);
  10620. // MoE
  10621. cur = llm_build_norm(ctx0, inpSA, hparams,
  10622. model.layers[il].ffn_norm_exps, NULL,
  10623. LLM_NORM_RMS, cb, il);
  10624. cb(cur, "ffn_norm_exps", il);
  10625. cur = llm_build_moe_ffn(ctx0, lctx, cur,
  10626. model.layers[il].ffn_gate_inp,
  10627. model.layers[il].ffn_up_exps,
  10628. model.layers[il].ffn_gate_exps,
  10629. model.layers[il].ffn_down_exps,
  10630. n_expert, n_expert_used,
  10631. LLM_FFN_SILU, true,
  10632. false, 0.0,
  10633. cb, il);
  10634. cb(cur, "ffn_moe_out", il);
  10635. cur = ggml_add(ctx0, cur, ffn_out);
  10636. cb(cur, "ffn_out", il);
  10637. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10638. cb(cur, "l_out", il);
  10639. // input for next layer
  10640. inpL = cur;
  10641. }
  10642. cur = inpL;
  10643. cur = llm_build_norm(ctx0, cur, hparams,
  10644. model.output_norm, NULL,
  10645. LLM_NORM_RMS, cb, -1);
  10646. cb(cur, "result_norm", -1);
  10647. // lm_head
  10648. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  10649. cb(cur, "result_output", -1);
  10650. ggml_build_forward_expand(gf, cur);
  10651. return gf;
  10652. }
  10653. struct ggml_cgraph * build_deepseek2() {
  10654. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10655. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10656. int32_t n_tokens = this->n_tokens;
  10657. bool is_lite = (hparams.n_layer == 27);
  10658. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  10659. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  10660. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  10661. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  10662. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  10663. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  10664. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  10665. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  10666. struct ggml_tensor * cur;
  10667. struct ggml_tensor * inpL;
  10668. // {n_embd, n_tokens}
  10669. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10670. // inp_pos - contains the positions
  10671. struct ggml_tensor * inp_pos = build_inp_pos();
  10672. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10673. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10674. for (int il = 0; il < n_layer; ++il) {
  10675. struct ggml_tensor * inpSA = inpL;
  10676. // norm
  10677. cur = llm_build_norm(ctx0, inpL, hparams,
  10678. model.layers[il].attn_norm, NULL,
  10679. LLM_NORM_RMS, cb, il);
  10680. cb(cur, "attn_norm", il);
  10681. // self_attention
  10682. {
  10683. struct ggml_tensor * q = NULL;
  10684. if (!is_lite) {
  10685. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  10686. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  10687. cb(q, "q", il);
  10688. q = llm_build_norm(ctx0, q, hparams,
  10689. model.layers[il].attn_q_a_norm, NULL,
  10690. LLM_NORM_RMS, cb, il);
  10691. cb(q, "q", il);
  10692. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  10693. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  10694. cb(q, "q", il);
  10695. } else {
  10696. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  10697. cb(q, "q", il);
  10698. }
  10699. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10700. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  10701. ggml_row_size(q->type, hparams.n_embd_head_k),
  10702. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10703. 0);
  10704. cb(q_nope, "q_nope", il);
  10705. // and {n_head * n_embd_head_qk_rope, n_tokens}
  10706. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  10707. ggml_row_size(q->type, hparams.n_embd_head_k),
  10708. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  10709. ggml_row_size(q->type, n_embd_head_qk_nope));
  10710. cb(q_pe, "q_pe", il);
  10711. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  10712. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  10713. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  10714. // split into {kv_lora_rank, n_tokens}
  10715. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  10716. kv_pe_compresseed->nb[1],
  10717. 0);
  10718. cb(kv_compressed, "kv_compressed", il);
  10719. // and {n_embd_head_qk_rope, n_tokens}
  10720. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  10721. kv_pe_compresseed->nb[1],
  10722. kv_pe_compresseed->nb[1],
  10723. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  10724. cb(k_pe, "k_pe", il);
  10725. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  10726. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  10727. model.layers[il].attn_kv_a_norm, NULL,
  10728. LLM_NORM_RMS, cb, il);
  10729. cb(kv_compressed, "kv_compressed", il);
  10730. // {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}
  10731. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  10732. cb(kv, "kv", il);
  10733. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  10734. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  10735. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  10736. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10737. 0);
  10738. cb(k_nope, "k_nope", il);
  10739. // and {n_head * n_embd_head_v, n_tokens}
  10740. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  10741. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  10742. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  10743. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  10744. cb(v_states, "v_states", il);
  10745. v_states = ggml_cont(ctx0, v_states);
  10746. cb(v_states, "v_states", il);
  10747. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  10748. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  10749. 0);
  10750. cb(v_states, "v_states", il);
  10751. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10752. q_pe = ggml_rope_ext(
  10753. ctx0, q_pe, inp_pos, nullptr,
  10754. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10755. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10756. );
  10757. cb(q_pe, "q_pe", il);
  10758. // shared RoPE key
  10759. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  10760. k_pe = ggml_rope_ext(
  10761. ctx0, k_pe, inp_pos, nullptr,
  10762. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10763. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  10764. );
  10765. cb(k_pe, "k_pe", il);
  10766. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  10767. cb(q_states, "q_states", il);
  10768. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  10769. cb(k_states, "k_states", il);
  10770. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10771. model.layers[il].wo, NULL,
  10772. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  10773. }
  10774. if (il == n_layer - 1) {
  10775. // skip computing output for unused tokens
  10776. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10777. n_tokens = n_outputs;
  10778. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10779. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10780. }
  10781. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10782. cb(ffn_inp, "ffn_inp", il);
  10783. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10784. model.layers[il].ffn_norm, NULL,
  10785. LLM_NORM_RMS, cb, il);
  10786. cb(cur, "ffn_norm", il);
  10787. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  10788. cur = llm_build_ffn(ctx0, lctx, cur,
  10789. model.layers[il].ffn_up, NULL, NULL,
  10790. model.layers[il].ffn_gate, NULL, NULL,
  10791. model.layers[il].ffn_down, NULL, NULL,
  10792. NULL,
  10793. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10794. cb(cur, "ffn_out", il);
  10795. } else {
  10796. // MoE branch
  10797. ggml_tensor * moe_out =
  10798. llm_build_moe_ffn(ctx0, lctx, cur,
  10799. model.layers[il].ffn_gate_inp,
  10800. model.layers[il].ffn_up_exps,
  10801. model.layers[il].ffn_gate_exps,
  10802. model.layers[il].ffn_down_exps,
  10803. n_expert, n_expert_used,
  10804. LLM_FFN_SILU, false,
  10805. true, hparams.expert_weights_scale,
  10806. cb, il);
  10807. cb(moe_out, "ffn_moe_out", il);
  10808. // FFN shared expert
  10809. {
  10810. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, lctx, cur,
  10811. model.layers[il].ffn_up_shexp, NULL, NULL,
  10812. model.layers[il].ffn_gate_shexp, NULL, NULL,
  10813. model.layers[il].ffn_down_shexp, NULL, NULL,
  10814. NULL,
  10815. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10816. cb(ffn_shexp, "ffn_shexp", il);
  10817. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  10818. cb(cur, "ffn_out", il);
  10819. }
  10820. }
  10821. cur = ggml_add(ctx0, cur, ffn_inp);
  10822. cur = lctx.cvec.apply_to(ctx0, cur, il);
  10823. cb(cur, "l_out", il);
  10824. // input for next layer
  10825. inpL = cur;
  10826. }
  10827. cur = inpL;
  10828. cur = llm_build_norm(ctx0, cur, hparams,
  10829. model.output_norm, NULL,
  10830. LLM_NORM_RMS, cb, -1);
  10831. cb(cur, "result_norm", -1);
  10832. // lm_head
  10833. cur = ggml_mul_mat(ctx0, model.output, cur);
  10834. cb(cur, "result_output", -1);
  10835. ggml_build_forward_expand(gf, cur);
  10836. return gf;
  10837. }
  10838. struct ggml_cgraph * build_bitnet() {
  10839. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10840. const int64_t n_embd_head = hparams.n_embd_head_v;
  10841. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10842. struct ggml_tensor * cur;
  10843. struct ggml_tensor * inpL;
  10844. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10845. // inp_pos - contains the positions
  10846. struct ggml_tensor * inp_pos = build_inp_pos();
  10847. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10848. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  10849. for (int il = 0; il < n_layer; ++il) {
  10850. struct ggml_tensor * inpSA = inpL;
  10851. cur = llm_build_norm(ctx0, inpL, hparams,
  10852. model.layers[il].attn_norm, NULL,
  10853. LLM_NORM_RMS, cb, il);
  10854. cb(cur, "attn_norm", il);
  10855. // self-attention
  10856. {
  10857. // compute Q and K and RoPE them
  10858. struct ggml_tensor * Qcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wq, cur);
  10859. Qcur = ggml_mul(ctx0, Qcur, model.layers[il].wq_scale);
  10860. cb(Qcur, "Qcur", il);
  10861. if (model.layers[il].bq) {
  10862. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  10863. cb(Qcur, "Qcur", il);
  10864. }
  10865. // B1.K
  10866. struct ggml_tensor * Kcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wk, cur);
  10867. Kcur = ggml_mul(ctx0, Kcur, model.layers[il].wk_scale);
  10868. cb(Kcur, "Kcur", il);
  10869. if (model.layers[il].bk) {
  10870. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  10871. cb(Kcur, "Kcur", il);
  10872. }
  10873. // B1.V
  10874. struct ggml_tensor * Vcur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wv, cur);
  10875. Vcur = ggml_mul(ctx0, Vcur, model.layers[il].wv_scale);
  10876. cb(Vcur, "Vcur", il);
  10877. if (model.layers[il].bv) {
  10878. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  10879. cb(Vcur, "Vcur", il);
  10880. }
  10881. Qcur = ggml_rope_ext(
  10882. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  10883. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10884. ext_factor, attn_factor, beta_fast, beta_slow
  10885. );
  10886. cb(Qcur, "Qcur", il);
  10887. Kcur = ggml_rope_ext(
  10888. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  10889. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  10890. ext_factor, attn_factor, beta_fast, beta_slow
  10891. );
  10892. cb(Kcur, "Kcur", il);
  10893. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  10894. NULL, NULL,
  10895. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  10896. cur = llm_build_norm(ctx0, cur, hparams,
  10897. model.layers[il].attn_sub_norm, NULL,
  10898. LLM_NORM_RMS, cb, il);
  10899. cb(cur, "attn_sub_norm", il);
  10900. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wo, cur);
  10901. cur = ggml_mul(ctx0, cur, model.layers[il].wo_scale);
  10902. if (model.layers[il].bo) {
  10903. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  10904. }
  10905. cb(cur, "attn_o_out", il);
  10906. }
  10907. if (il == n_layer - 1) {
  10908. // skip computing output for unused tokens
  10909. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  10910. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  10911. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  10912. }
  10913. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  10914. cb(ffn_inp, "ffn_inp", il);
  10915. // feed-forward forward
  10916. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  10917. model.layers[il].ffn_norm, NULL,
  10918. LLM_NORM_RMS, cb, il);
  10919. cb(cur, "ffn_norm", il);
  10920. cur = llm_build_ffn(ctx0, lctx, cur,
  10921. model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_scale,
  10922. model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_scale,
  10923. NULL, NULL, NULL,
  10924. NULL,
  10925. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  10926. cb(cur, "ffn_sub_out", il);
  10927. cur = llm_build_norm(ctx0, cur, hparams,
  10928. model.layers[il].ffn_sub_norm, NULL,
  10929. LLM_NORM_RMS, cb, il);
  10930. cb(cur, "ffn_sub_norm", il);
  10931. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].ffn_down, cur);
  10932. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_down_scale);
  10933. cb(cur, "ffn_down", il);
  10934. cur = ggml_add(ctx0, cur, ffn_inp);
  10935. cb(cur, "l_out", il);
  10936. // input for next layer
  10937. inpL = cur;
  10938. }
  10939. cur = inpL;
  10940. cur = llm_build_norm(ctx0, cur, hparams,
  10941. model.output_norm, NULL,
  10942. LLM_NORM_RMS, cb, -1);
  10943. cb(cur, "result_norm", -1);
  10944. // lm_head
  10945. cur = llm_build_lora_mm(lctx, ctx0, model.tok_embd, cur);
  10946. cb(cur, "result_output", -1);
  10947. ggml_build_forward_expand(gf, cur);
  10948. return gf;
  10949. }
  10950. struct ggml_cgraph * build_t5() {
  10951. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  10952. // mutable variable, needed during the last layer of the computation to skip unused tokens
  10953. int32_t n_tokens = this->n_tokens;
  10954. const int64_t n_embd_head = hparams.n_embd_head_v;
  10955. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  10956. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  10957. struct ggml_tensor * cur;
  10958. struct ggml_tensor * inpL;
  10959. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  10960. if (lctx.is_encoding) {
  10961. struct ggml_tensor * pos_bucket_enc = llm_build_pos_bucket(false);
  10962. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  10963. struct ggml_tensor * KQ_mask_enc = build_inp_KQ_mask(false);
  10964. for (int il = 0; il < n_layer; ++il) {
  10965. struct ggml_tensor * inpSA = inpL;
  10966. // norm
  10967. cur = llm_build_norm(ctx0, inpL, hparams,
  10968. model.layers[il].attn_norm_enc, NULL,
  10969. LLM_NORM_RMS, cb, il);
  10970. cb(cur, "attn_norm", il);
  10971. // self-attention
  10972. {
  10973. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_enc, cur);
  10974. cb(Qcur, "Qcur", il);
  10975. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_enc, cur);
  10976. cb(Kcur, "Kcur", il);
  10977. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_enc, cur);
  10978. cb(Vcur, "Vcur", il);
  10979. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  10980. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  10981. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  10982. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  10983. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  10984. cb(kq, "kq", il);
  10985. 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;
  10986. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_enc, attn_rel_b);
  10987. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  10988. cb(kq_b, "kq_b", il);
  10989. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_enc, 1.0f, hparams.f_max_alibi_bias);
  10990. cb(kq, "kq_soft_max_ext", il);
  10991. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  10992. cb(v, "v", il);
  10993. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  10994. cb(kqv, "kqv", il);
  10995. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  10996. cb(kqv_merged, "kqv_merged", il);
  10997. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  10998. cb(cur, "kqv_merged_cont", il);
  10999. ggml_build_forward_expand(gf, cur);
  11000. cur = ggml_mul_mat(ctx0, model.layers[il].wo_enc, cur);
  11001. cb(cur, "kqv_out", il);
  11002. }
  11003. if (il == n_layer - 1) {
  11004. // skip computing output for unused tokens
  11005. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11006. n_tokens = n_outputs;
  11007. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11008. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11009. }
  11010. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11011. cb(ffn_inp, "ffn_inp", il);
  11012. // feed-forward network
  11013. {
  11014. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11015. model.layers[il].ffn_norm_enc, NULL,
  11016. LLM_NORM_RMS, cb, il);
  11017. cb(cur, "ffn_norm", il);
  11018. // T5 uses relu, flan-T5 uses gelu-gated
  11019. cur = llm_build_ffn(ctx0, lctx, cur,
  11020. model.layers[il].ffn_up_enc, NULL, NULL,
  11021. model.layers[il].ffn_gate_enc, NULL, NULL,
  11022. model.layers[il].ffn_down_enc, NULL, NULL,
  11023. NULL,
  11024. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11025. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11026. cb, il);
  11027. cb(cur, "ffn_out", il);
  11028. }
  11029. cur = ggml_add(ctx0, cur, ffn_inp);
  11030. cb(cur, "ffn_out", il);
  11031. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11032. if (layer_dir != nullptr) {
  11033. cur = ggml_add(ctx0, cur, layer_dir);
  11034. }
  11035. cb(cur, "l_out", il);
  11036. // input for next layer
  11037. inpL = cur;
  11038. }
  11039. cur = inpL;
  11040. cb(cur, "result_embd", -1);
  11041. cur = llm_build_norm(ctx0, cur, hparams,
  11042. model.output_norm_enc, NULL,
  11043. LLM_NORM_RMS, cb, -1);
  11044. cb(cur, "result_norm", -1);
  11045. } else {
  11046. GGML_ASSERT(n_outputs_enc > 0 && "call llama_encode() first");
  11047. struct ggml_tensor * embd_enc = llm_build_inp_embd_enc();
  11048. struct ggml_tensor * pos_bucket_dec = llm_build_pos_bucket(true);
  11049. struct ggml_tensor * KQ_mask_dec = build_inp_KQ_mask();
  11050. struct ggml_tensor * KQ_mask_cross = llm_build_inp_KQ_mask_cross();
  11051. for (int il = 0; il < n_layer; ++il) {
  11052. struct ggml_tensor * inpSA = inpL;
  11053. // norm
  11054. cur = llm_build_norm(ctx0, inpL, hparams,
  11055. model.layers[il].attn_norm, NULL,
  11056. LLM_NORM_RMS, cb, il);
  11057. cb(cur, "attn_norm", il);
  11058. // self-attention
  11059. {
  11060. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  11061. cb(Qcur, "Qcur", il);
  11062. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  11063. cb(Kcur, "Kcur", il);
  11064. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  11065. cb(Vcur, "Vcur", il);
  11066. llm_build_kv_store(ctx0, hparams, cparams, kv_self, gf, Kcur, Vcur, n_tokens, kv_head, cb, il);
  11067. struct ggml_tensor * k =
  11068. ggml_view_3d(ctx0, kv_self.k_l[il],
  11069. n_embd_head_k, n_kv, n_head_kv,
  11070. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  11071. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  11072. 0);
  11073. cb(k, "k", il);
  11074. struct ggml_tensor * v =
  11075. ggml_view_3d(ctx0, kv_self.v_l[il],
  11076. n_kv, n_embd_head_v, n_head_kv,
  11077. ggml_element_size(kv_self.v_l[il])*n_ctx,
  11078. ggml_element_size(kv_self.v_l[il])*n_ctx*n_embd_head_v,
  11079. 0);
  11080. cb(v, "v", il);
  11081. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11082. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11083. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11084. cb(kq, "kq", il);
  11085. struct ggml_tensor * attn_rel_b = model.layers[il].attn_rel_b ? model.layers[il].attn_rel_b : model.layers[0].attn_rel_b;
  11086. struct ggml_tensor * pos_bias = llm_build_pos_bias(pos_bucket_dec, attn_rel_b);
  11087. struct ggml_tensor * kq_b = ggml_add(ctx0, kq, pos_bias);
  11088. cb(kq_b, "kq_b", il);
  11089. kq = ggml_soft_max_ext(ctx0, kq_b, KQ_mask_dec, 1.0f, hparams.f_max_alibi_bias);
  11090. cb(kq, "kq_soft_max_ext", il);
  11091. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
  11092. cb(kqv, "kqv", il);
  11093. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11094. cb(kqv_merged, "kqv_merged", il);
  11095. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11096. cb(cur, "kqv_merged_cont", il);
  11097. ggml_build_forward_expand(gf, cur);
  11098. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  11099. cb(cur, "kqv_out", il);
  11100. }
  11101. cur = ggml_add(ctx0, cur, inpSA);
  11102. cb(cur, "cross_inp", il);
  11103. struct ggml_tensor * inpCA = cur;
  11104. // norm
  11105. cur = llm_build_norm(ctx0, cur, hparams,
  11106. model.layers[il].attn_norm_cross, NULL,
  11107. LLM_NORM_RMS, cb, il);
  11108. cb(cur, "attn_norm_cross", il);
  11109. // cross-attention
  11110. {
  11111. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq_cross, cur);
  11112. cb(Qcur, "Qcur", il);
  11113. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk_cross, embd_enc);
  11114. cb(Kcur, "Kcur", il);
  11115. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv_cross, embd_enc);
  11116. cb(Vcur, "Vcur", il);
  11117. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11118. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_outputs_enc);
  11119. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  11120. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  11121. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  11122. cb(kq, "kq", il);
  11123. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask_cross, 1.0f, hparams.f_max_alibi_bias);
  11124. cb(kq, "kq_soft_max_ext", il);
  11125. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_outputs_enc)));
  11126. cb(v, "v", il);
  11127. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_outputs_enc, n_embd_head, n_head_kv), kq);
  11128. cb(kqv, "kqv", il);
  11129. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  11130. cb(kqv_merged, "kqv_merged", il);
  11131. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  11132. cb(cur, "kqv_merged_cont", il);
  11133. ggml_build_forward_expand(gf, cur);
  11134. cur = ggml_mul_mat(ctx0, model.layers[il].wo_cross, cur);
  11135. cb(cur, "kqv_out", il);
  11136. }
  11137. if (il == n_layer - 1) {
  11138. // skip computing output for unused tokens
  11139. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11140. n_tokens = n_outputs;
  11141. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11142. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11143. inpCA = ggml_get_rows(ctx0, inpCA, inp_out_ids);
  11144. }
  11145. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpCA);
  11146. cb(ffn_inp, "ffn_inp", il);
  11147. // feed-forward network
  11148. {
  11149. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11150. model.layers[il].ffn_norm, NULL,
  11151. LLM_NORM_RMS, cb, il);
  11152. cb(cur, "ffn_norm", il);
  11153. // T5 uses relu, flan-T5 uses gelu-gated
  11154. cur = llm_build_ffn(ctx0, lctx, cur,
  11155. model.layers[il].ffn_up, NULL, NULL,
  11156. model.layers[il].ffn_gate, NULL, NULL,
  11157. model.layers[il].ffn_down, NULL, NULL,
  11158. NULL,
  11159. model.layers[il].ffn_gate_enc ? LLM_FFN_GELU : LLM_FFN_RELU,
  11160. model.layers[il].ffn_gate_enc ? LLM_FFN_PAR : LLM_FFN_SEQ,
  11161. cb, il);
  11162. cb(cur, "ffn_out", il);
  11163. }
  11164. cur = ggml_add(ctx0, cur, ffn_inp);
  11165. cb(cur, "ffn_out", il);
  11166. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  11167. if (layer_dir != nullptr) {
  11168. cur = ggml_add(ctx0, cur, layer_dir);
  11169. }
  11170. cb(cur, "l_out", il);
  11171. // input for next layer
  11172. inpL = cur;
  11173. }
  11174. cur = inpL;
  11175. cb(cur, "result_embd", -1);
  11176. cur = llm_build_norm(ctx0, cur, hparams,
  11177. model.output_norm, NULL,
  11178. LLM_NORM_RMS, cb, -1);
  11179. cb(cur, "result_norm", -1);
  11180. // lm_head
  11181. cur = ggml_mul_mat(ctx0, model.output, cur);
  11182. cb(cur, "result_output", -1);
  11183. }
  11184. ggml_build_forward_expand(gf, cur);
  11185. return gf;
  11186. }
  11187. struct ggml_cgraph * build_jais() {
  11188. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11189. const int64_t n_embd_head = hparams.n_embd_head_v;
  11190. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11191. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11192. struct ggml_tensor * cur;
  11193. struct ggml_tensor * inpL;
  11194. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11195. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11196. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11197. for (int il = 0; il < n_layer; ++il) {
  11198. cur = llm_build_norm(ctx0, inpL, hparams,
  11199. model.layers[il].attn_norm,
  11200. model.layers[il].attn_norm_b,
  11201. LLM_NORM, cb, il);
  11202. cb(cur, "attn_norm", il);
  11203. // self-attention
  11204. {
  11205. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11206. cb(cur, "wqkv", il);
  11207. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11208. cb(cur, "bqkv", il);
  11209. 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)));
  11210. 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)));
  11211. 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)));
  11212. cb(Qcur, "Qcur", il);
  11213. cb(Kcur, "Kcur", il);
  11214. cb(Vcur, "Vcur", il);
  11215. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  11216. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11217. model.layers[il].wo, model.layers[il].bo,
  11218. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/float(n_embd_head), cb, il);
  11219. }
  11220. if (il == n_layer - 1) {
  11221. // skip computing output for unused tokens
  11222. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11223. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11224. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  11225. }
  11226. // add the input
  11227. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  11228. cb(ffn_inp, "ffn_inp", il);
  11229. // FF
  11230. {
  11231. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11232. model.layers[il].ffn_norm,
  11233. model.layers[il].ffn_norm_b,
  11234. LLM_NORM, cb, il);
  11235. cb(cur, "ffn_norm", il);
  11236. cur = llm_build_ffn(ctx0, lctx, cur,
  11237. model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
  11238. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
  11239. model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
  11240. NULL,
  11241. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  11242. cb(cur, "ffn_out", il);
  11243. }
  11244. inpL = ggml_add(ctx0, cur, ffn_inp);
  11245. cb(inpL, "l_out", il);
  11246. }
  11247. cur = llm_build_norm(ctx0, inpL, hparams,
  11248. model.output_norm,
  11249. model.output_norm_b,
  11250. LLM_NORM, cb, -1);
  11251. cb(cur, "result_norm", -1);
  11252. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11253. cb(cur, "result_output", -1);
  11254. ggml_build_forward_expand(gf, cur);
  11255. return gf;
  11256. }
  11257. struct ggml_cgraph * build_chatglm() {
  11258. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, llama_model_max_nodes(model), false);
  11259. const int64_t n_embd_head = hparams.n_embd_head_v;
  11260. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  11261. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  11262. struct ggml_tensor * cur;
  11263. struct ggml_tensor * inpL;
  11264. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  11265. // inp_pos - contains the positions
  11266. struct ggml_tensor * inp_pos = build_inp_pos();
  11267. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  11268. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  11269. for (int il = 0; il < n_layer; ++il) {
  11270. struct ggml_tensor * inpSA = inpL;
  11271. cur = llm_build_norm(ctx0, inpL, hparams,
  11272. model.layers[il].attn_norm,
  11273. NULL,
  11274. LLM_NORM_RMS, cb, il);
  11275. cb(cur, "attn_norm", il);
  11276. // self-attention
  11277. {
  11278. struct ggml_tensor * Qcur = nullptr;
  11279. struct ggml_tensor * Kcur = nullptr;
  11280. struct ggml_tensor * Vcur = nullptr;
  11281. cur = llm_build_lora_mm(lctx, ctx0, model.layers[il].wqkv, cur);
  11282. cb(cur, "wqkv", il);
  11283. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  11284. cb(cur, "bqkv", il);
  11285. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  11286. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  11287. 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)));
  11288. cb(Qcur, "Qcur", il);
  11289. cb(Kcur, "Kcur", il);
  11290. cb(Vcur, "Vcur", il);
  11291. //printf("freq_base: %f freq_scale: %f ext_factor: %f attn_factor: %f\n", freq_base, freq_scale, ext_factor, attn_factor);
  11292. Qcur = ggml_rope_ext(
  11293. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  11294. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11295. ext_factor, attn_factor, beta_fast, beta_slow
  11296. );
  11297. cb(Qcur, "Qcur_rope", il);
  11298. Kcur = ggml_rope_ext(
  11299. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  11300. n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
  11301. ext_factor, attn_factor, beta_fast, beta_slow
  11302. );
  11303. cb(Kcur, "Kcur_rope", il);
  11304. cur = llm_build_kv(ctx0, lctx, kv_self, gf,
  11305. model.layers[il].wo, NULL,
  11306. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  11307. }
  11308. if (il == n_layer - 1) {
  11309. // skip computing output for unused tokens
  11310. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  11311. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  11312. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  11313. }
  11314. // Add the input
  11315. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  11316. cb(ffn_inp, "ffn_inp", il);
  11317. // FF
  11318. {
  11319. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  11320. model.layers[il].ffn_norm,
  11321. NULL,
  11322. LLM_NORM_RMS, cb, il);
  11323. cb(cur, "ffn_norm", il);
  11324. cur = llm_build_ffn(ctx0, lctx, cur,
  11325. model.layers[il].ffn_up, NULL, NULL,
  11326. NULL, NULL, NULL,
  11327. model.layers[il].ffn_down, NULL, NULL,
  11328. NULL,
  11329. LLM_FFN_SWIGLU, LLM_FFN_SEQ, cb, il);
  11330. cb(cur, "ffn_out", il);
  11331. }
  11332. inpL = ggml_add(ctx0, cur, ffn_inp);
  11333. cb(inpL, "l_out", il);
  11334. }
  11335. cur = llm_build_norm(ctx0, inpL, hparams,
  11336. model.output_norm,
  11337. NULL,
  11338. LLM_NORM_RMS, cb, -1);
  11339. cb(cur, "result_norm", -1);
  11340. cur = llm_build_lora_mm(lctx, ctx0, model.output, cur);
  11341. cb(cur, "result_output", -1);
  11342. ggml_build_forward_expand(gf, cur);
  11343. return gf;
  11344. }
  11345. };
  11346. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  11347. llama_batch dummy;
  11348. dummy.n_tokens = 0;
  11349. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11350. struct llm_build_context llm(lctx, dummy, cb, false);
  11351. llm.init();
  11352. struct ggml_cgraph * result = llm.build_defrag(ids);
  11353. llm.free();
  11354. return result;
  11355. }
  11356. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  11357. llama_batch dummy;
  11358. dummy.n_tokens = 0;
  11359. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11360. struct llm_build_context llm(lctx, dummy, cb, false);
  11361. llm.init();
  11362. struct ggml_cgraph * result = llm.build_k_shift();
  11363. llm.free();
  11364. return result;
  11365. }
  11366. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  11367. llama_batch dummy;
  11368. dummy.n_tokens = 0;
  11369. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  11370. struct llm_build_context llm(lctx, dummy, cb, false);
  11371. llm.init();
  11372. struct ggml_cgraph * result = llm.build_s_copy();
  11373. llm.free();
  11374. return result;
  11375. }
  11376. static struct ggml_cgraph * llama_build_graph(
  11377. llama_context & lctx,
  11378. const llama_batch & batch,
  11379. bool worst_case) {
  11380. const auto & model = lctx.model;
  11381. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  11382. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  11383. if (il >= 0) {
  11384. ggml_format_name(cur, "%s-%d", name, il);
  11385. } else {
  11386. ggml_set_name(cur, name);
  11387. }
  11388. if (!lctx.cparams.offload_kqv) {
  11389. if (strcmp(name, "kqv_merged_cont") == 0) {
  11390. // all nodes between the KV store and the attention output are run on the CPU
  11391. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  11392. }
  11393. }
  11394. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  11395. // FIXME: fix in ggml_backend_sched
  11396. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  11397. if (batch.n_tokens < 32 || full_offload) {
  11398. if (il != -1 && strcmp(name, "norm") == 0) {
  11399. for (auto * backend : lctx.backends) {
  11400. if (ggml_backend_supports_buft(backend, lctx.model.buft_layer[il].buft) &&
  11401. (ggml_backend_supports_op(backend, cur) || ggml_backend_offload_op(backend, cur))) {
  11402. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  11403. break;
  11404. }
  11405. }
  11406. }
  11407. }
  11408. };
  11409. struct ggml_cgraph * result = NULL;
  11410. struct llm_build_context llm(lctx, batch, cb, worst_case);
  11411. llm.init();
  11412. switch (model.arch) {
  11413. case LLM_ARCH_LLAMA:
  11414. {
  11415. result = llm.build_llama();
  11416. } break;
  11417. case LLM_ARCH_BAICHUAN:
  11418. {
  11419. result = llm.build_baichuan();
  11420. } break;
  11421. case LLM_ARCH_FALCON:
  11422. {
  11423. result = llm.build_falcon();
  11424. } break;
  11425. case LLM_ARCH_GROK:
  11426. {
  11427. result = llm.build_grok();
  11428. } break;
  11429. case LLM_ARCH_STARCODER:
  11430. {
  11431. result = llm.build_starcoder();
  11432. } break;
  11433. case LLM_ARCH_REFACT:
  11434. {
  11435. result = llm.build_refact();
  11436. } break;
  11437. case LLM_ARCH_BERT:
  11438. case LLM_ARCH_JINA_BERT_V2:
  11439. case LLM_ARCH_NOMIC_BERT:
  11440. {
  11441. result = llm.build_bert();
  11442. } break;
  11443. case LLM_ARCH_BLOOM:
  11444. {
  11445. result = llm.build_bloom();
  11446. } break;
  11447. case LLM_ARCH_MPT:
  11448. {
  11449. result = llm.build_mpt();
  11450. } break;
  11451. case LLM_ARCH_STABLELM:
  11452. {
  11453. result = llm.build_stablelm();
  11454. } break;
  11455. case LLM_ARCH_QWEN:
  11456. {
  11457. result = llm.build_qwen();
  11458. } break;
  11459. case LLM_ARCH_QWEN2:
  11460. {
  11461. result = llm.build_qwen2();
  11462. } break;
  11463. case LLM_ARCH_QWEN2MOE:
  11464. {
  11465. result = llm.build_qwen2moe();
  11466. } break;
  11467. case LLM_ARCH_PHI2:
  11468. {
  11469. result = llm.build_phi2();
  11470. } break;
  11471. case LLM_ARCH_PHI3:
  11472. {
  11473. result = llm.build_phi3();
  11474. } break;
  11475. case LLM_ARCH_PLAMO:
  11476. {
  11477. result = llm.build_plamo();
  11478. } break;
  11479. case LLM_ARCH_GPT2:
  11480. {
  11481. result = llm.build_gpt2();
  11482. } break;
  11483. case LLM_ARCH_CODESHELL:
  11484. {
  11485. result = llm.build_codeshell();
  11486. } break;
  11487. case LLM_ARCH_ORION:
  11488. {
  11489. result = llm.build_orion();
  11490. } break;
  11491. case LLM_ARCH_INTERNLM2:
  11492. {
  11493. result = llm.build_internlm2();
  11494. } break;
  11495. case LLM_ARCH_MINICPM:
  11496. {
  11497. result = llm.build_minicpm();
  11498. } break;
  11499. case LLM_ARCH_GEMMA:
  11500. {
  11501. result = llm.build_gemma();
  11502. } break;
  11503. case LLM_ARCH_GEMMA2:
  11504. {
  11505. result = llm.build_gemma2();
  11506. } break;
  11507. case LLM_ARCH_STARCODER2:
  11508. {
  11509. result = llm.build_starcoder2();
  11510. } break;
  11511. case LLM_ARCH_MAMBA:
  11512. {
  11513. result = llm.build_mamba();
  11514. } break;
  11515. case LLM_ARCH_XVERSE:
  11516. {
  11517. result = llm.build_xverse();
  11518. } break;
  11519. case LLM_ARCH_COMMAND_R:
  11520. {
  11521. result = llm.build_command_r();
  11522. } break;
  11523. case LLM_ARCH_DBRX:
  11524. {
  11525. result = llm.build_dbrx();
  11526. } break;
  11527. case LLM_ARCH_OLMO:
  11528. {
  11529. result = llm.build_olmo();
  11530. } break;
  11531. case LLM_ARCH_OPENELM:
  11532. {
  11533. result = llm.build_openelm();
  11534. } break;
  11535. case LLM_ARCH_GPTNEOX:
  11536. {
  11537. result = llm.build_gptneox();
  11538. } break;
  11539. case LLM_ARCH_ARCTIC:
  11540. {
  11541. result = llm.build_arctic();
  11542. } break;
  11543. case LLM_ARCH_DEEPSEEK2:
  11544. {
  11545. result = llm.build_deepseek2();
  11546. } break;
  11547. case LLM_ARCH_CHATGLM:
  11548. {
  11549. result = llm.build_chatglm();
  11550. } break;
  11551. case LLM_ARCH_BITNET:
  11552. {
  11553. result = llm.build_bitnet();
  11554. } break;
  11555. case LLM_ARCH_T5:
  11556. {
  11557. result = llm.build_t5();
  11558. } break;
  11559. case LLM_ARCH_JAIS:
  11560. {
  11561. result = llm.build_jais();
  11562. } break;
  11563. default:
  11564. GGML_ABORT("fatal error");
  11565. }
  11566. // add on pooling layer
  11567. if (lctx.cparams.embeddings) {
  11568. result = llm.append_pooling(result);
  11569. }
  11570. llm.free();
  11571. return result;
  11572. }
  11573. static void llama_set_k_shift(llama_context & lctx) {
  11574. const int64_t kv_size = lctx.kv_self.size;
  11575. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  11576. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  11577. for (int i = 0; i < kv_size; ++i) {
  11578. data[i] = lctx.kv_self.cells[i].delta;
  11579. }
  11580. }
  11581. static void llama_set_s_copy(llama_context & lctx) {
  11582. const int64_t kv_size = lctx.kv_self.size;
  11583. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  11584. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  11585. for (int i = 0; i < kv_size; ++i) {
  11586. data[i] = lctx.kv_self.cells[i].src;
  11587. }
  11588. }
  11589. static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
  11590. // TODO move to hparams if a T5 variant appears that uses a different value
  11591. const int64_t max_distance = 128;
  11592. if (bidirectional) {
  11593. n_buckets >>= 1;
  11594. }
  11595. const int64_t max_exact = n_buckets >> 1;
  11596. int32_t relative_position = x - y;
  11597. int32_t relative_bucket = 0;
  11598. if (bidirectional) {
  11599. relative_bucket += (relative_position > 0) * n_buckets;
  11600. relative_position = abs(relative_position);
  11601. } else {
  11602. relative_position = -std::min<int32_t>(relative_position, 0);
  11603. }
  11604. 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));
  11605. relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
  11606. relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
  11607. return relative_bucket;
  11608. }
  11609. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  11610. //
  11611. // set input data
  11612. //
  11613. const auto & hparams = lctx.model.hparams;
  11614. const auto & cparams = lctx.cparams;
  11615. const auto & kv_self = lctx.kv_self;
  11616. if (batch.token) {
  11617. const int64_t n_tokens = batch.n_tokens;
  11618. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  11619. }
  11620. if (batch.embd) {
  11621. const int64_t n_embd = hparams.n_embd;
  11622. const int64_t n_tokens = batch.n_tokens;
  11623. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  11624. }
  11625. if (batch.pos && lctx.inp_pos) {
  11626. const int64_t n_tokens = batch.n_tokens;
  11627. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  11628. }
  11629. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  11630. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  11631. const int64_t n_tokens = batch.n_tokens;
  11632. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  11633. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  11634. if (lctx.n_outputs == n_tokens) {
  11635. for (int i = 0; i < n_tokens; ++i) {
  11636. data[i] = i;
  11637. }
  11638. } else if (batch.logits) {
  11639. int32_t n_outputs = 0;
  11640. for (int i = 0; i < n_tokens; ++i) {
  11641. if (batch.logits[i]) {
  11642. data[n_outputs++] = i;
  11643. }
  11644. }
  11645. // the graph needs to have been passed the correct number of outputs
  11646. GGML_ASSERT(lctx.n_outputs == n_outputs);
  11647. } else if (lctx.n_outputs == 1) {
  11648. // only keep last output
  11649. data[0] = n_tokens - 1;
  11650. } else {
  11651. GGML_ASSERT(lctx.n_outputs == 0);
  11652. }
  11653. }
  11654. GGML_ASSERT(
  11655. // (!a || b) is a logical implication (a -> b)
  11656. // !hparams.causal_attn -> !cparams.causal_attn
  11657. (hparams.causal_attn || !cparams.causal_attn) &&
  11658. "causal attention is not supported by this model"
  11659. );
  11660. if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
  11661. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  11662. if (cparams.causal_attn && !lctx.is_encoding) {
  11663. const int64_t n_kv = kv_self.n;
  11664. const int64_t n_tokens = batch.n_tokens;
  11665. float * data = nullptr;
  11666. float * data_swa = nullptr;
  11667. if (lctx.inp_KQ_mask) {
  11668. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11669. data = (float *) lctx.inp_KQ_mask->data;
  11670. }
  11671. if (lctx.inp_KQ_mask_swa) {
  11672. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
  11673. data_swa = (float *) lctx.inp_KQ_mask_swa->data;
  11674. }
  11675. // For causal attention, use only the previous KV cells
  11676. // of the correct sequence for each token of the batch.
  11677. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  11678. for (int h = 0; h < 1; ++h) {
  11679. for (int j = 0; j < n_tokens; ++j) {
  11680. const llama_pos pos = batch.pos[j];
  11681. const llama_seq_id seq_id = batch.seq_id[j][0];
  11682. for (int i = 0; i < n_kv; ++i) {
  11683. float f;
  11684. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  11685. f = -INFINITY;
  11686. } else {
  11687. if (hparams.use_alibi) {
  11688. f = -std::abs(lctx.kv_self.cells[i].pos - pos);
  11689. } else {
  11690. f = 0.0f;
  11691. }
  11692. }
  11693. if (data) {
  11694. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11695. }
  11696. // may need to cut off old tokens for sliding window
  11697. if (data_swa) {
  11698. if (pos - lctx.kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
  11699. f = -INFINITY;
  11700. }
  11701. data_swa[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  11702. }
  11703. }
  11704. }
  11705. if (data) {
  11706. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11707. for (int j = 0; j < n_kv; ++j) {
  11708. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11709. }
  11710. }
  11711. }
  11712. if (data_swa) {
  11713. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11714. for (int j = 0; j < n_kv; ++j) {
  11715. data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  11716. }
  11717. }
  11718. }
  11719. }
  11720. } else {
  11721. // when using kv cache, the mask needs to match the kv cache size
  11722. const int64_t n_tokens = batch.n_tokens;
  11723. const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
  11724. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  11725. float * data = (float *) lctx.inp_KQ_mask->data;
  11726. for (int h = 0; h < 1; ++h) {
  11727. for (int j = 0; j < n_tokens; ++j) {
  11728. const llama_seq_id seq_id = batch.seq_id[j][0];
  11729. for (int i = 0; i < n_tokens; ++i) {
  11730. float f = -INFINITY;
  11731. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  11732. if (batch.seq_id[i][s] == seq_id) {
  11733. if (hparams.use_alibi) {
  11734. f = -std::abs(batch.pos[i] - batch.pos[j]);
  11735. } else {
  11736. f = 0.0f;
  11737. }
  11738. break;
  11739. }
  11740. }
  11741. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  11742. }
  11743. for (int i = n_tokens; i < n_stride; ++i) {
  11744. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  11745. }
  11746. }
  11747. }
  11748. }
  11749. }
  11750. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  11751. const int64_t n_tokens = batch.n_tokens;
  11752. GGML_ASSERT(lctx.inp_mean);
  11753. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  11754. float * data = (float *) lctx.inp_mean->data;
  11755. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  11756. std::vector<uint64_t> sum(n_tokens, 0);
  11757. for (int i = 0; i < n_tokens; ++i) {
  11758. const llama_seq_id seq_id = batch.seq_id[i][0];
  11759. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  11760. sum[seq_id] += 1;
  11761. }
  11762. std::vector<float> div(n_tokens, 0.0f);
  11763. for (int i = 0; i < n_tokens; ++i) {
  11764. const uint64_t s = sum[i];
  11765. if (s > 0) {
  11766. div[i] = 1.0f/float(s);
  11767. }
  11768. }
  11769. for (int i = 0; i < n_tokens; ++i) {
  11770. const llama_seq_id seq_id = batch.seq_id[i][0];
  11771. data[seq_id*n_tokens + i] = div[seq_id];
  11772. }
  11773. }
  11774. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  11775. const int64_t n_tokens = batch.n_tokens;
  11776. GGML_ASSERT(lctx.inp_cls);
  11777. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11778. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11779. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11780. for (int i = 0; i < n_tokens; ++i) {
  11781. const llama_seq_id seq_id = batch.seq_id[i][0];
  11782. const llama_pos pos = batch.pos[i];
  11783. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  11784. if (pos == 0) {
  11785. data[seq_id] = i;
  11786. }
  11787. }
  11788. }
  11789. if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
  11790. const int64_t n_tokens = batch.n_tokens;
  11791. GGML_ASSERT(lctx.inp_cls);
  11792. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  11793. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  11794. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  11795. std::vector<int> last_pos(n_tokens, -1);
  11796. std::vector<int> last_row(n_tokens, -1);
  11797. for (int i = 0; i < n_tokens; ++i) {
  11798. const llama_seq_id seq_id = batch.seq_id[i][0];
  11799. const llama_pos pos = batch.pos[i];
  11800. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
  11801. if (pos >= last_pos[seq_id]) {
  11802. last_pos[seq_id] = pos;
  11803. last_row[seq_id] = i;
  11804. }
  11805. }
  11806. for (int i = 0; i < n_tokens; ++i) {
  11807. if (last_row[i] >= 0) {
  11808. data[i] = last_row[i];
  11809. }
  11810. }
  11811. }
  11812. if (kv_self.recurrent) {
  11813. const int64_t n_kv = kv_self.n;
  11814. if (lctx.inp_s_mask) {
  11815. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  11816. float * data = (float *) lctx.inp_s_mask->data;
  11817. // states which are not affected by the current batch are left untouched
  11818. for (int i = 0; i < n_kv; ++i) {
  11819. llama_seq_id seq_id = i + lctx.kv_self.head;
  11820. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  11821. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  11822. data[i] = (float) has_self_seq;
  11823. // ensure current sequences will be kept
  11824. if (!has_self_seq && kv_cell.pos >= 0) {
  11825. kv_cell.seq_id.insert(seq_id);
  11826. }
  11827. }
  11828. }
  11829. // For Mamba (and other recurrent architectures),
  11830. // update the correct state(s)/sequence(s) for each token of the batch.
  11831. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  11832. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  11833. if (lctx.inp_s_seq) {
  11834. const int64_t n_tokens = batch.n_tokens;
  11835. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  11836. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  11837. for (int j = 0; j < n_tokens; ++j) {
  11838. const int32_t n_seq = batch.n_seq_id[j];
  11839. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  11840. for (int i = 0; i < n_kv; ++i) {
  11841. if (i < n_seq) {
  11842. // for this type of model, the head is the minimum seq_id of the batch
  11843. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  11844. } else {
  11845. data[j*n_kv + i] = -1;
  11846. }
  11847. }
  11848. }
  11849. }
  11850. }
  11851. if (lctx.inp_pos_bucket) {
  11852. const int64_t n_tokens = batch.n_tokens;
  11853. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
  11854. int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
  11855. if (!lctx.is_encoding) {
  11856. const int64_t n_kv = kv_self.n;
  11857. for (int h = 0; h < 1; ++h) {
  11858. for (int j = 0; j < n_tokens; ++j) {
  11859. for (int i = 0; i < n_kv; ++i) {
  11860. 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);
  11861. }
  11862. }
  11863. }
  11864. } else {
  11865. for (int h = 0; h < 1; ++h) {
  11866. for (int j = 0; j < n_tokens; ++j) {
  11867. for (int i = 0; i < n_tokens; ++i) {
  11868. 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);
  11869. }
  11870. }
  11871. }
  11872. }
  11873. }
  11874. if (!lctx.is_encoding && lctx.inp_embd_enc) {
  11875. assert(lctx.inp_embd_enc->type == GGML_TYPE_F32);
  11876. assert((size_t) ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
  11877. ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, ggml_nbytes(lctx.inp_embd_enc));
  11878. }
  11879. if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
  11880. const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
  11881. const int64_t n_tokens = batch.n_tokens;
  11882. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
  11883. float * data = (float *) lctx.inp_KQ_mask_cross->data;
  11884. for (int h = 0; h < 1; ++h) {
  11885. for (int j = 0; j < n_tokens; ++j) {
  11886. for (int i = 0; i < n_output_enc; ++i) {
  11887. float f = -INFINITY;
  11888. for (int s = 0; s < batch.n_seq_id[j]; ++s) {
  11889. const llama_seq_id seq_id = batch.seq_id[j][s];
  11890. if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
  11891. f = 0.0f;
  11892. }
  11893. }
  11894. data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
  11895. }
  11896. }
  11897. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  11898. for (int j = 0; j < n_output_enc; ++j) {
  11899. data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
  11900. }
  11901. }
  11902. }
  11903. }
  11904. }
  11905. // Make sure enough space is available for outputs.
  11906. // Returns max number of outputs for which space was reserved.
  11907. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  11908. const auto & cparams = lctx.cparams;
  11909. const auto & hparams = lctx.model.hparams;
  11910. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  11911. const auto n_batch = cparams.n_batch;
  11912. const auto n_vocab = hparams.n_vocab;
  11913. const auto n_embd = hparams.n_embd;
  11914. // TODO: use a per-batch flag for logits presence instead
  11915. const bool has_logits = cparams.causal_attn;
  11916. const bool has_embd = lctx.is_encoding || (cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE));
  11917. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  11918. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  11919. if (lctx.output_ids.empty()) {
  11920. // init, never resized afterwards
  11921. lctx.output_ids.resize(n_batch);
  11922. }
  11923. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  11924. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  11925. // alloc only when more than the current capacity is required
  11926. // TODO: also consider shrinking the buffer
  11927. if (!lctx.buf_output || prev_size < new_size) {
  11928. if (lctx.buf_output) {
  11929. #ifndef NDEBUG
  11930. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  11931. 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);
  11932. #endif
  11933. ggml_backend_buffer_free(lctx.buf_output);
  11934. lctx.buf_output = nullptr;
  11935. lctx.logits = nullptr;
  11936. lctx.embd = nullptr;
  11937. }
  11938. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  11939. if (lctx.buf_output == nullptr) {
  11940. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  11941. return 0;
  11942. }
  11943. }
  11944. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  11945. lctx.logits = has_logits ? output_base : nullptr;
  11946. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  11947. lctx.output_size = n_outputs_max;
  11948. lctx.logits_size = logits_size;
  11949. lctx.embd_size = embd_size;
  11950. // set all ids as invalid (negative)
  11951. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  11952. ggml_backend_buffer_clear(lctx.buf_output, 0);
  11953. lctx.n_outputs = 0;
  11954. return n_outputs_max;
  11955. }
  11956. static void llama_graph_compute(
  11957. llama_context & lctx,
  11958. ggml_cgraph * gf,
  11959. int n_threads) {
  11960. #ifdef GGML_USE_METAL
  11961. if (ggml_backend_is_metal(lctx.backend_metal)) {
  11962. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  11963. }
  11964. #endif
  11965. if (lctx.backend_cpu != nullptr) {
  11966. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  11967. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  11968. }
  11969. #ifdef GGML_USE_BLAS
  11970. if (lctx.backend_blas != nullptr) {
  11971. ggml_backend_blas_set_n_threads(lctx.backend_blas, n_threads);
  11972. }
  11973. #endif
  11974. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  11975. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  11976. }
  11977. // decode a batch of tokens by evaluating the transformer
  11978. //
  11979. // - lctx: llama context
  11980. // - batch: batch to evaluate
  11981. //
  11982. // return 0 on success
  11983. // return positive int on warning
  11984. // return negative int on error
  11985. //
  11986. static int llama_decode_internal(
  11987. llama_context & lctx,
  11988. llama_batch batch_all) { // TODO: rename back to batch
  11989. lctx.is_encoding = false;
  11990. const uint32_t n_tokens_all = batch_all.n_tokens;
  11991. if (n_tokens_all == 0) {
  11992. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  11993. return -1;
  11994. }
  11995. const auto & model = lctx.model;
  11996. const auto & hparams = model.hparams;
  11997. const auto & cparams = lctx.cparams;
  11998. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  11999. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  12000. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  12001. if (lctx.t_compute_start_us == 0) {
  12002. lctx.t_compute_start_us = ggml_time_us();
  12003. }
  12004. lctx.n_queued_tokens += n_tokens_all;
  12005. auto & kv_self = lctx.kv_self;
  12006. const int64_t n_embd = hparams.n_embd;
  12007. const int64_t n_vocab = hparams.n_vocab;
  12008. uint32_t n_outputs = 0;
  12009. uint32_t n_outputs_prev = 0;
  12010. const auto n_ubatch = cparams.n_ubatch;
  12011. // TODO: simplify or deprecate
  12012. std::vector<llama_pos> pos;
  12013. std::vector<int32_t> n_seq_id;
  12014. std::vector<llama_seq_id *> seq_id_arr;
  12015. std::vector<std::vector<llama_seq_id>> seq_id;
  12016. // this indicates we are doing pooled embedding, so we ignore batch.logits and output all tokens
  12017. const bool embd_pooled = cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE;
  12018. // count outputs
  12019. if (batch_all.logits && !embd_pooled) {
  12020. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12021. n_outputs += batch_all.logits[i] != 0;
  12022. }
  12023. } else if (lctx.logits_all || embd_pooled) {
  12024. n_outputs = n_tokens_all;
  12025. } else {
  12026. // keep last output only
  12027. n_outputs = 1;
  12028. }
  12029. // reserve output buffer
  12030. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  12031. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  12032. return -2;
  12033. };
  12034. // set output mappings
  12035. if (batch_all.logits) {
  12036. int32_t i_logits = 0;
  12037. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  12038. if (batch_all.logits[i]) {
  12039. lctx.output_ids[i] = i_logits++;
  12040. }
  12041. }
  12042. } else {
  12043. for (uint32_t i = 0; i < n_outputs; ++i) {
  12044. lctx.output_ids[i] = i;
  12045. }
  12046. }
  12047. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  12048. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  12049. llama_batch u_batch = {
  12050. /* .n_tokens = */ (int32_t) n_tokens,
  12051. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  12052. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  12053. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  12054. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  12055. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  12056. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  12057. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  12058. /* .all_pos_1 = */ batch_all.all_pos_1,
  12059. /* .all_seq_id = */ batch_all.all_seq_id,
  12060. };
  12061. // count the outputs in this u_batch
  12062. {
  12063. int32_t n_outputs_new = 0;
  12064. if (u_batch.logits && !embd_pooled) {
  12065. for (uint32_t i = 0; i < n_tokens; i++) {
  12066. n_outputs_new += u_batch.logits[i] != 0;
  12067. }
  12068. } else if (n_outputs == n_tokens_all) {
  12069. n_outputs_new = n_tokens;
  12070. } else {
  12071. // keep last output only
  12072. if (cur_token + n_tokens >= n_tokens_all) {
  12073. n_outputs_new = 1;
  12074. }
  12075. }
  12076. // needs to happen before the graph is built
  12077. lctx.n_outputs = n_outputs_new;
  12078. }
  12079. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12080. GGML_ASSERT(n_threads > 0);
  12081. // helpers for smoother batch API transition
  12082. // after deprecating the llama_eval calls, these will be removed
  12083. if (u_batch.pos == nullptr) {
  12084. pos.resize(n_tokens);
  12085. for (uint32_t i = 0; i < n_tokens; i++) {
  12086. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  12087. }
  12088. u_batch.pos = pos.data();
  12089. }
  12090. if (u_batch.seq_id == nullptr) {
  12091. n_seq_id.resize(n_tokens);
  12092. seq_id.resize(n_tokens);
  12093. seq_id_arr.resize(n_tokens);
  12094. for (uint32_t i = 0; i < n_tokens; i++) {
  12095. n_seq_id[i] = 1;
  12096. seq_id[i].resize(1);
  12097. seq_id[i][0] = u_batch.all_seq_id;
  12098. seq_id_arr[i] = seq_id[i].data();
  12099. }
  12100. u_batch.n_seq_id = n_seq_id.data();
  12101. u_batch.seq_id = seq_id_arr.data();
  12102. }
  12103. // non-causal masks do not use the KV cache
  12104. if (hparams.causal_attn) {
  12105. llama_kv_cache_update(&lctx);
  12106. // if we have enough unused cells before the current head ->
  12107. // better to start searching from the beginning of the cache, hoping to fill it
  12108. if (kv_self.head > kv_self.used + 2*n_tokens) {
  12109. kv_self.head = 0;
  12110. }
  12111. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  12112. return 1;
  12113. }
  12114. if (!kv_self.recurrent) {
  12115. // a heuristic, to avoid attending the full cache if it is not yet utilized
  12116. // after enough generations, the benefit from this heuristic disappears
  12117. // if we start defragmenting the cache, the benefit from this will be more important
  12118. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  12119. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  12120. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  12121. }
  12122. }
  12123. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  12124. ggml_backend_sched_reset(lctx.sched);
  12125. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12126. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  12127. // the output is always the last tensor in the graph
  12128. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  12129. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  12130. if (lctx.n_outputs == 0) {
  12131. // no output
  12132. res = nullptr;
  12133. embd = nullptr;
  12134. }
  12135. if (cparams.embeddings) {
  12136. for (int i = gf->n_nodes - 1; i >= 0; --i) {
  12137. embd = gf->nodes[i];
  12138. if (strcmp(embd->name, "result_embd_pooled") == 0) {
  12139. break;
  12140. }
  12141. }
  12142. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0 && "missing embeddings tensor");
  12143. } else {
  12144. embd = nullptr; // do not extract embeddings when not needed
  12145. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  12146. }
  12147. if (!cparams.causal_attn) {
  12148. res = nullptr; // do not extract logits when not needed
  12149. }
  12150. // 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);
  12151. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12152. llama_set_inputs(lctx, u_batch);
  12153. llama_graph_compute(lctx, gf, n_threads);
  12154. // update the kv ring buffer
  12155. {
  12156. kv_self.head += n_tokens;
  12157. // Ensure kv cache head points to a valid index.
  12158. if (kv_self.head >= kv_self.size) {
  12159. kv_self.head = 0;
  12160. }
  12161. }
  12162. // plot the computation graph in dot format (for debugging purposes)
  12163. //if (n_past%100 == 0) {
  12164. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  12165. //}
  12166. // extract logits
  12167. if (res) {
  12168. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  12169. GGML_ASSERT(backend_res != nullptr);
  12170. GGML_ASSERT(lctx.logits != nullptr);
  12171. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  12172. const int32_t n_outputs_new = lctx.n_outputs;
  12173. if (n_outputs_new) {
  12174. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12175. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  12176. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  12177. }
  12178. }
  12179. // extract embeddings
  12180. if (embd) {
  12181. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12182. GGML_ASSERT(backend_embd != nullptr);
  12183. switch (cparams.pooling_type) {
  12184. case LLAMA_POOLING_TYPE_NONE:
  12185. {
  12186. // extract token embeddings
  12187. GGML_ASSERT(lctx.embd != nullptr);
  12188. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  12189. const int32_t n_outputs_new = lctx.n_outputs;
  12190. if (n_outputs_new) {
  12191. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  12192. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  12193. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  12194. }
  12195. } break;
  12196. case LLAMA_POOLING_TYPE_MEAN:
  12197. case LLAMA_POOLING_TYPE_CLS:
  12198. case LLAMA_POOLING_TYPE_LAST:
  12199. {
  12200. // extract sequence embeddings
  12201. auto & embd_seq_out = lctx.embd_seq;
  12202. embd_seq_out.clear();
  12203. for (uint32_t i = 0; i < n_tokens; i++) {
  12204. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  12205. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  12206. continue;
  12207. }
  12208. embd_seq_out[seq_id].resize(n_embd);
  12209. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  12210. }
  12211. } break;
  12212. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  12213. {
  12214. GGML_ABORT("unknown pooling type");
  12215. }
  12216. }
  12217. }
  12218. n_outputs_prev += lctx.n_outputs;
  12219. }
  12220. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  12221. lctx.n_outputs = n_outputs;
  12222. // wait for the computation to finish (automatically done when obtaining the model output)
  12223. //llama_synchronize(&lctx);
  12224. // decide if we need to defrag the kv cache
  12225. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  12226. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  12227. // queue defragmentation for next llama_kv_cache_update
  12228. if (fragmentation > cparams.defrag_thold) {
  12229. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  12230. llama_kv_cache_defrag(kv_self);
  12231. }
  12232. }
  12233. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12234. // overlap with device computation.
  12235. ggml_backend_sched_reset(lctx.sched);
  12236. return 0;
  12237. }
  12238. // encode a batch of tokens by evaluating the encoder part of the transformer
  12239. //
  12240. // - lctx: llama context
  12241. // - batch: batch to evaluate
  12242. //
  12243. // return 0 on success
  12244. // return positive int on warning
  12245. // return negative int on error
  12246. //
  12247. static int llama_encode_internal(
  12248. llama_context & lctx,
  12249. llama_batch batch) {
  12250. lctx.is_encoding = true;
  12251. const uint32_t n_tokens = batch.n_tokens;
  12252. if (n_tokens == 0) {
  12253. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  12254. return -1;
  12255. }
  12256. const auto & model = lctx.model;
  12257. const auto & hparams = model.hparams;
  12258. const auto & cparams = lctx.cparams;
  12259. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  12260. // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
  12261. GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
  12262. if (lctx.t_compute_start_us == 0) {
  12263. lctx.t_compute_start_us = ggml_time_us();
  12264. }
  12265. lctx.n_queued_tokens += n_tokens;
  12266. const int64_t n_embd = hparams.n_embd;
  12267. // TODO: simplify or deprecate
  12268. std::vector<llama_pos> pos;
  12269. std::vector<int32_t> n_seq_id;
  12270. std::vector<llama_seq_id *> seq_id_arr;
  12271. std::vector<std::vector<llama_seq_id>> seq_id;
  12272. // reserve output buffer
  12273. if (llama_output_reserve(lctx, n_tokens) < n_tokens) {
  12274. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
  12275. return -2;
  12276. };
  12277. for (uint32_t i = 0; i < n_tokens; ++i) {
  12278. lctx.output_ids[i] = i;
  12279. }
  12280. lctx.inp_embd_enc = NULL;
  12281. lctx.n_outputs = n_tokens;
  12282. const int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  12283. GGML_ASSERT(n_threads > 0);
  12284. // helpers for smoother batch API transition
  12285. // after deprecating the llama_eval calls, these will be removed
  12286. if (batch.pos == nullptr) {
  12287. pos.resize(n_tokens);
  12288. for (uint32_t i = 0; i < n_tokens; i++) {
  12289. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  12290. }
  12291. batch.pos = pos.data();
  12292. }
  12293. if (batch.seq_id == nullptr) {
  12294. n_seq_id.resize(n_tokens);
  12295. seq_id.resize(n_tokens);
  12296. seq_id_arr.resize(n_tokens);
  12297. for (uint32_t i = 0; i < n_tokens; i++) {
  12298. n_seq_id[i] = 1;
  12299. seq_id[i].resize(1);
  12300. seq_id[i][0] = batch.all_seq_id;
  12301. seq_id_arr[i] = seq_id[i].data();
  12302. }
  12303. batch.n_seq_id = n_seq_id.data();
  12304. batch.seq_id = seq_id_arr.data();
  12305. }
  12306. ggml_backend_sched_reset(lctx.sched);
  12307. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  12308. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  12309. // the output embeddings after the final encoder normalization
  12310. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 1];
  12311. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  12312. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12313. llama_set_inputs(lctx, batch);
  12314. llama_graph_compute(lctx, gf, n_threads);
  12315. // extract embeddings
  12316. if (embd) {
  12317. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  12318. GGML_ASSERT(backend_embd != nullptr);
  12319. // extract token embeddings
  12320. GGML_ASSERT(lctx.embd != nullptr);
  12321. lctx.embd_enc.resize(n_tokens*n_embd);
  12322. float * embd_out = lctx.embd_enc.data();
  12323. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_tokens*n_embd*sizeof(float));
  12324. // remember the sequence ids used during the encoding - needed for cross attention later
  12325. lctx.seq_ids_enc.resize(n_tokens);
  12326. for (uint32_t i = 0; i < n_tokens; i++) {
  12327. for (int s = 0; s < batch.n_seq_id[i]; s++) {
  12328. llama_seq_id seq_id = batch.seq_id[i][s];
  12329. lctx.seq_ids_enc[i].insert(seq_id);
  12330. }
  12331. }
  12332. }
  12333. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  12334. // overlap with device computation.
  12335. ggml_backend_sched_reset(lctx.sched);
  12336. return 0;
  12337. }
  12338. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  12339. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  12340. auto & kv_self = lctx.kv_self;
  12341. const auto & hparams = lctx.model.hparams;
  12342. const uint32_t n_layer = hparams.n_layer;
  12343. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  12344. const uint32_t n_used = kv_self.used;
  12345. assert(n_used <= n_kv);
  12346. //const int64_t t_start = ggml_time_us();
  12347. // number of cells moved
  12348. uint32_t n_moves = 0;
  12349. // each move requires 6*n_layer tensors (see build_defrag)
  12350. // - source view, destination view, copy operation
  12351. // - x2 for keys and values
  12352. //const uint32_t max_moves = llama_model_max_nodes(model)/(6*n_layer);
  12353. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  12354. const uint32_t max_moves = (llama_model_max_nodes(lctx.model) - 2*n_layer)/(6*n_layer);
  12355. // determine which KV cells to move where
  12356. //
  12357. // cell i moves to ids[i]
  12358. //
  12359. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  12360. //
  12361. std::vector<uint32_t> ids(n_kv, n_kv);
  12362. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  12363. const auto & cell0 = kv_self.cells[i0];
  12364. if (!cell0.is_empty()) {
  12365. ids[i0] = i0;
  12366. continue;
  12367. }
  12368. // found a hole - fill it with data from the end of the cache
  12369. uint32_t nh = 1;
  12370. // determine the size of the hole
  12371. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  12372. nh++;
  12373. }
  12374. uint32_t nf = 0;
  12375. uint32_t is = n_kv - 1;
  12376. // starting from the end, find nh non-empty cells
  12377. for (; is > i0; --is) {
  12378. const auto & cell1 = kv_self.cells[is];
  12379. if (cell1.is_empty() || ids[is] != n_kv) {
  12380. continue;
  12381. }
  12382. // non-empty cell which is not yet moved
  12383. nf++;
  12384. if (nf == nh) {
  12385. break;
  12386. }
  12387. }
  12388. // this can only happen if `n_used` is not accurate, which would be a bug
  12389. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  12390. nf = 0;
  12391. uint32_t i1 = is;
  12392. // are we moving a continuous block of memory?
  12393. bool cont = false;
  12394. // should we stop searching for the next move?
  12395. bool stop = false;
  12396. // go back and move the nf cells to the hole
  12397. for (; i1 < n_kv; ++i1) {
  12398. auto & cell1 = kv_self.cells[i1];
  12399. if (cell1.is_empty() || ids[i1] != n_kv) {
  12400. if (n_moves == max_moves) {
  12401. stop = true;
  12402. break;
  12403. }
  12404. cont = false;
  12405. continue;
  12406. }
  12407. // this cell goes to (i0 + nf)
  12408. ids[i1] = i0 + nf;
  12409. // move the cell meta data
  12410. kv_self.cells[i0 + nf] = cell1;
  12411. // clear the old cell and move the head there
  12412. cell1 = llama_kv_cell();
  12413. kv_self.head = n_used;
  12414. if (!cont) {
  12415. n_moves++;
  12416. cont = true;
  12417. }
  12418. nf++;
  12419. if (nf == nh) {
  12420. break;
  12421. }
  12422. }
  12423. if (stop || n_moves == max_moves) {
  12424. break;
  12425. }
  12426. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  12427. i0 += nh - 1;
  12428. }
  12429. if (n_moves == 0) {
  12430. return;
  12431. }
  12432. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  12433. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  12434. #if 0
  12435. // CPU defrag
  12436. //
  12437. // TODO: optimizations are possible:
  12438. // - multiple threads
  12439. // - avoid copying to the host memory when already there
  12440. //
  12441. // likely not worth the effort, as we have ggml_graph based defrag
  12442. //
  12443. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  12444. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  12445. const uint32_t kv_size = kv_self.size;
  12446. std::vector<uint8_t> buf_k;
  12447. std::vector<uint8_t> buf_v;
  12448. for (uint32_t il = 0; il < n_layer; ++il) {
  12449. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12450. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  12451. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12452. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  12453. buf_k.resize(k_size);
  12454. buf_v.resize(v_size);
  12455. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12456. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12457. // batch move [i, i+nm) to [id, id+nm)
  12458. // note: cells can move only to a lower index
  12459. for (uint32_t i = 0; i < n_kv; ++i) {
  12460. const uint32_t id = ids[i];
  12461. if (i == id || id == n_kv) {
  12462. continue;
  12463. }
  12464. uint32_t nm = 1;
  12465. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  12466. nm++;
  12467. }
  12468. // move keys
  12469. {
  12470. const int64_t os = i*k_size_row;
  12471. const int64_t od = id*k_size_row;
  12472. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  12473. }
  12474. // move values (note: they are transposed)
  12475. {
  12476. const int64_t os = i;
  12477. const int64_t od = id;
  12478. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  12479. 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);
  12480. }
  12481. }
  12482. i += nm - 1;
  12483. }
  12484. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  12485. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  12486. }
  12487. #else
  12488. // ggml_graph defrag
  12489. ggml_backend_sched_reset(lctx.sched);
  12490. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  12491. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12492. #endif
  12493. //const int64_t t_end = ggml_time_us();
  12494. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  12495. }
  12496. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  12497. bool need_reserve = false;
  12498. // apply K-shift if needed
  12499. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  12500. if (lctx.model.arch == LLM_ARCH_DEEPSEEK2) { // not supported due to MLA
  12501. GGML_ABORT("Deepseek2 does not support K-shift");
  12502. }
  12503. {
  12504. ggml_backend_sched_reset(lctx.sched);
  12505. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  12506. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12507. llama_set_k_shift(lctx);
  12508. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12509. need_reserve = true;
  12510. }
  12511. {
  12512. auto & kv_self = lctx.kv_self;
  12513. kv_self.has_shift = false;
  12514. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12515. kv_self.cells[i].delta = 0;
  12516. }
  12517. }
  12518. }
  12519. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  12520. {
  12521. ggml_backend_sched_reset(lctx.sched);
  12522. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  12523. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  12524. llama_set_s_copy(lctx);
  12525. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  12526. need_reserve = true;
  12527. }
  12528. {
  12529. auto & kv_self = lctx.kv_self;
  12530. kv_self.do_copy = false;
  12531. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12532. kv_self.cells[i].src = i;
  12533. }
  12534. }
  12535. }
  12536. // defragment the KV cache if needed
  12537. if (lctx.kv_self.do_defrag) {
  12538. llama_kv_cache_defrag_internal(lctx);
  12539. need_reserve = true;
  12540. lctx.kv_self.do_defrag = false;
  12541. }
  12542. // reserve a worst case graph again
  12543. if (need_reserve) {
  12544. // TODO: extract to a function
  12545. // build worst-case graph
  12546. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  12547. int n_past = lctx.cparams.n_ctx - n_tokens;
  12548. 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
  12549. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12550. // initialize scheduler with the worst-case graph
  12551. ggml_backend_sched_reset(lctx.sched);
  12552. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  12553. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12554. }
  12555. }
  12556. }
  12557. //
  12558. // quantization
  12559. //
  12560. struct quantize_state_internal {
  12561. const llama_model & model;
  12562. const llama_model_quantize_params * params;
  12563. int n_attention_wv = 0;
  12564. int n_ffn_down = 0;
  12565. int n_ffn_gate = 0;
  12566. int n_ffn_up = 0;
  12567. int i_attention_wv = 0;
  12568. int i_ffn_down = 0;
  12569. int i_ffn_gate = 0;
  12570. int i_ffn_up = 0;
  12571. int n_k_quantized = 0;
  12572. int n_fallback = 0;
  12573. bool has_imatrix = false;
  12574. // used to figure out if a model shares tok_embd with the output weight
  12575. bool has_output = false;
  12576. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  12577. : model(model)
  12578. , params(params)
  12579. {}
  12580. };
  12581. static void llama_tensor_dequantize_internal(
  12582. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  12583. const size_t nelements, const int nthread
  12584. ) {
  12585. if (output.size() < nelements) {
  12586. output.resize(nelements);
  12587. }
  12588. float * f32_output = (float *) output.data();
  12589. ggml_type_traits_t qtype;
  12590. if (ggml_is_quantized(tensor->type)) {
  12591. qtype = ggml_internal_get_type_traits(tensor->type);
  12592. if (qtype.to_float == NULL) {
  12593. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  12594. }
  12595. } else if (tensor->type != GGML_TYPE_F16 &&
  12596. tensor->type != GGML_TYPE_BF16) {
  12597. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  12598. }
  12599. if (nthread < 2) {
  12600. if (tensor->type == GGML_TYPE_F16) {
  12601. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  12602. } else if (tensor->type == GGML_TYPE_BF16) {
  12603. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  12604. } else if (ggml_is_quantized(tensor->type)) {
  12605. qtype.to_float(tensor->data, f32_output, nelements);
  12606. } else {
  12607. GGML_ABORT("fatal error"); // unreachable
  12608. }
  12609. return;
  12610. }
  12611. size_t block_size;
  12612. if (tensor->type == GGML_TYPE_F16 ||
  12613. tensor->type == GGML_TYPE_BF16) {
  12614. block_size = 1;
  12615. } else {
  12616. block_size = (size_t)ggml_blck_size(tensor->type);
  12617. }
  12618. size_t block_size_bytes = ggml_type_size(tensor->type);
  12619. GGML_ASSERT(nelements % block_size == 0);
  12620. size_t nblocks = nelements / block_size;
  12621. size_t blocks_per_thread = nblocks / nthread;
  12622. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  12623. size_t in_buff_offs = 0;
  12624. size_t out_buff_offs = 0;
  12625. for (int tnum = 0; tnum < nthread; tnum++) {
  12626. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  12627. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  12628. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  12629. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  12630. if (typ == GGML_TYPE_F16) {
  12631. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  12632. } else if (typ == GGML_TYPE_BF16) {
  12633. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  12634. } else {
  12635. qtype.to_float(inbuf, outbuf, nels);
  12636. }
  12637. };
  12638. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  12639. in_buff_offs += thr_block_bytes;
  12640. out_buff_offs += thr_elems;
  12641. }
  12642. for (auto & w : workers) { w.join(); }
  12643. workers.clear();
  12644. }
  12645. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  12646. const std::string name = ggml_get_name(tensor);
  12647. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12648. const llm_arch arch = qs.model.arch;
  12649. const auto tn = LLM_TN(arch);
  12650. auto use_more_bits = [](int i_layer, int n_layers) -> bool {
  12651. return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2;
  12652. };
  12653. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  12654. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  12655. if (n_expert > 1) {
  12656. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  12657. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  12658. // for getting the current layer as I initially thought, and we need to resort to parsing the
  12659. // tensor name.
  12660. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  12661. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  12662. }
  12663. if (i_layer < 0 || i_layer >= n_layer) {
  12664. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  12665. }
  12666. }
  12667. return std::make_pair(i_layer, n_layer);
  12668. };
  12669. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  12670. // with the quantization of the output tensor
  12671. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  12672. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  12673. new_type = qs.params->output_tensor_type;
  12674. } else {
  12675. int nx = tensor->ne[0];
  12676. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  12677. new_type = GGML_TYPE_Q8_0;
  12678. }
  12679. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12680. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  12681. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12682. new_type = GGML_TYPE_Q5_K;
  12683. }
  12684. else if (new_type != GGML_TYPE_Q8_0) {
  12685. new_type = GGML_TYPE_Q6_K;
  12686. }
  12687. }
  12688. } else if (name == "token_embd.weight") {
  12689. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  12690. new_type = qs.params->token_embedding_type;
  12691. } else {
  12692. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  12693. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12694. new_type = GGML_TYPE_Q2_K;
  12695. }
  12696. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  12697. new_type = GGML_TYPE_IQ3_S;
  12698. }
  12699. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12700. new_type = GGML_TYPE_IQ3_S;
  12701. }
  12702. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8 ||
  12703. new_type == GGML_TYPE_Q4_0_8_8) {
  12704. new_type = GGML_TYPE_Q4_0;
  12705. }
  12706. }
  12707. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  12708. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12709. if (name.find("attn_v.weight") != std::string::npos) {
  12710. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  12711. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12712. ++qs.i_attention_wv;
  12713. }
  12714. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  12715. new_type = GGML_TYPE_Q4_K;
  12716. }
  12717. else if (name.find("ffn_down") != std::string::npos) {
  12718. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  12719. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12720. }
  12721. ++qs.i_ffn_down;
  12722. }
  12723. else if (name.find("attn_output.weight") != std::string::npos) {
  12724. if (qs.model.hparams.n_expert == 8) {
  12725. new_type = GGML_TYPE_Q5_K;
  12726. } else {
  12727. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  12728. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  12729. }
  12730. }
  12731. } else if (name.find("attn_v.weight") != std::string::npos) {
  12732. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  12733. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12734. }
  12735. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  12736. new_type = GGML_TYPE_Q4_K;
  12737. }
  12738. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12739. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  12740. }
  12741. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  12742. new_type = GGML_TYPE_Q4_K;
  12743. }
  12744. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12745. new_type = GGML_TYPE_Q4_K;
  12746. }
  12747. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12748. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12749. }
  12750. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  12751. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  12752. new_type = GGML_TYPE_Q5_K;
  12753. }
  12754. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  12755. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  12756. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  12757. if (qs.model.type == MODEL_70B) {
  12758. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  12759. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  12760. // nearly negligible increase in model size by quantizing this tensor with more bits:
  12761. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  12762. }
  12763. if (qs.model.hparams.n_expert == 8) {
  12764. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12765. // TODO: explore better strategies
  12766. new_type = GGML_TYPE_Q8_0;
  12767. }
  12768. ++qs.i_attention_wv;
  12769. } else if (name.find("attn_k.weight") != std::string::npos) {
  12770. if (qs.model.hparams.n_expert == 8) {
  12771. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12772. // TODO: explore better strategies
  12773. new_type = GGML_TYPE_Q8_0;
  12774. }
  12775. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12776. new_type = GGML_TYPE_IQ3_XXS;
  12777. }
  12778. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12779. new_type = GGML_TYPE_IQ2_S;
  12780. }
  12781. } else if (name.find("attn_q.weight") != std::string::npos) {
  12782. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12783. new_type = GGML_TYPE_IQ3_XXS;
  12784. }
  12785. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12786. new_type = GGML_TYPE_IQ2_S;
  12787. }
  12788. } else if (name.find("ffn_down") != std::string::npos) {
  12789. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  12790. int i_layer = info.first, n_layer = info.second;
  12791. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12792. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  12793. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  12794. }
  12795. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  12796. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12797. }
  12798. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12799. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  12800. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  12801. : GGML_TYPE_Q3_K;
  12802. }
  12803. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  12804. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  12805. new_type = GGML_TYPE_Q4_K;
  12806. }
  12807. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  12808. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  12809. }
  12810. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  12811. if (arch == LLM_ARCH_FALCON) {
  12812. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  12813. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12814. } else {
  12815. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12816. }
  12817. }
  12818. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  12819. new_type = GGML_TYPE_Q5_K;
  12820. }
  12821. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12822. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  12823. new_type = GGML_TYPE_Q5_K;
  12824. }
  12825. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  12826. && qs.has_imatrix && i_layer < n_layer/8) {
  12827. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  12828. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  12829. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  12830. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  12831. }
  12832. ++qs.i_ffn_down;
  12833. } else if (name.find("attn_output.weight") != std::string::npos) {
  12834. if (arch != LLM_ARCH_FALCON) {
  12835. if (qs.model.hparams.n_expert == 8) {
  12836. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12837. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  12838. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  12839. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  12840. new_type = GGML_TYPE_Q5_K;
  12841. }
  12842. } else {
  12843. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  12844. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  12845. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  12846. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  12847. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  12848. }
  12849. } else {
  12850. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  12851. }
  12852. }
  12853. else if (name.find("attn_qkv.weight") != std::string::npos) {
  12854. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12855. new_type = GGML_TYPE_Q4_K;
  12856. }
  12857. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  12858. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  12859. }
  12860. else if (name.find("ffn_gate") != std::string::npos) {
  12861. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  12862. int i_layer = info.first, n_layer = info.second;
  12863. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12864. new_type = GGML_TYPE_IQ3_XXS;
  12865. }
  12866. ++qs.i_ffn_gate;
  12867. }
  12868. else if (name.find("ffn_up") != std::string::npos) {
  12869. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  12870. int i_layer = info.first, n_layer = info.second;
  12871. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12872. new_type = GGML_TYPE_IQ3_XXS;
  12873. }
  12874. ++qs.i_ffn_up;
  12875. }
  12876. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12877. //}
  12878. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  12879. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  12880. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12881. //}
  12882. // This can be used to reduce the size of the Q5_K_S model.
  12883. // The associated PPL increase is fully in line with the size reduction
  12884. //else {
  12885. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  12886. //}
  12887. bool convert_incompatible_tensor = false;
  12888. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  12889. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  12890. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  12891. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  12892. new_type == GGML_TYPE_IQ1_M) {
  12893. int nx = tensor->ne[0];
  12894. int ny = tensor->ne[1];
  12895. if (nx % QK_K != 0) {
  12896. 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));
  12897. convert_incompatible_tensor = true;
  12898. } else {
  12899. ++qs.n_k_quantized;
  12900. }
  12901. }
  12902. if (convert_incompatible_tensor) {
  12903. switch (new_type) {
  12904. case GGML_TYPE_IQ2_XXS:
  12905. case GGML_TYPE_IQ2_XS:
  12906. case GGML_TYPE_IQ2_S:
  12907. case GGML_TYPE_IQ3_XXS:
  12908. case GGML_TYPE_IQ3_S:
  12909. case GGML_TYPE_IQ1_S:
  12910. case GGML_TYPE_IQ1_M:
  12911. case GGML_TYPE_Q2_K:
  12912. case GGML_TYPE_Q3_K:
  12913. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  12914. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  12915. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  12916. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  12917. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  12918. }
  12919. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  12920. ++qs.n_fallback;
  12921. }
  12922. return new_type;
  12923. }
  12924. 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) {
  12925. if (nthread < 2) {
  12926. // single-thread
  12927. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  12928. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  12929. throw std::runtime_error("quantized data validation failed");
  12930. }
  12931. return new_size;
  12932. }
  12933. std::mutex mutex;
  12934. int64_t counter = 0;
  12935. size_t new_size = 0;
  12936. bool valid = true;
  12937. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  12938. nrows, n_per_row, imatrix]() {
  12939. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  12940. size_t local_size = 0;
  12941. while (true) {
  12942. std::unique_lock<std::mutex> lock(mutex);
  12943. int64_t first_row = counter; counter += nrows_per_chunk;
  12944. if (first_row >= nrows) {
  12945. if (local_size > 0) {
  12946. new_size += local_size;
  12947. }
  12948. break;
  12949. }
  12950. lock.unlock();
  12951. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  12952. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  12953. local_size += this_size;
  12954. // validate the quantized data
  12955. const size_t row_size = ggml_row_size(new_type, n_per_row);
  12956. void * this_data = (char *) new_data + first_row * row_size;
  12957. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  12958. std::unique_lock<std::mutex> lock(mutex);
  12959. valid = false;
  12960. break;
  12961. }
  12962. }
  12963. };
  12964. for (int it = 0; it < nthread - 1; ++it) {
  12965. workers.emplace_back(compute);
  12966. }
  12967. compute();
  12968. for (auto & w : workers) { w.join(); }
  12969. workers.clear();
  12970. if (!valid) {
  12971. throw std::runtime_error("quantized data validation failed");
  12972. }
  12973. return new_size;
  12974. }
  12975. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  12976. ggml_type default_type;
  12977. llama_ftype ftype = params->ftype;
  12978. switch (params->ftype) {
  12979. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  12980. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  12981. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  12982. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  12983. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  12984. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  12985. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  12986. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  12987. // K-quants
  12988. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  12989. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  12990. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  12991. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  12992. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  12993. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  12994. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  12995. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  12996. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  12997. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  12998. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  12999. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  13000. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  13001. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  13002. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  13003. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  13004. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  13005. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  13006. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  13007. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  13008. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  13009. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  13010. case LLAMA_FTYPE_MOSTLY_Q4_0_4_4: default_type = GGML_TYPE_Q4_0_4_4; break;
  13011. case LLAMA_FTYPE_MOSTLY_Q4_0_4_8: default_type = GGML_TYPE_Q4_0_4_8; break;
  13012. case LLAMA_FTYPE_MOSTLY_Q4_0_8_8: default_type = GGML_TYPE_Q4_0_8_8; break;
  13013. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  13014. }
  13015. int nthread = params->nthread;
  13016. if (nthread <= 0) {
  13017. nthread = std::thread::hardware_concurrency();
  13018. }
  13019. // mmap consistently increases speed Linux, and also increases speed on Windows with
  13020. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  13021. #if defined(__linux__) || defined(_WIN32)
  13022. constexpr bool use_mmap = true;
  13023. #else
  13024. constexpr bool use_mmap = false;
  13025. #endif
  13026. llama_model_kv_override * kv_overrides = nullptr;
  13027. if (params->kv_overrides) {
  13028. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  13029. kv_overrides = v->data();
  13030. }
  13031. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  13032. ml.init_mappings(false); // no prefetching
  13033. llama_model model;
  13034. llm_load_arch(ml, model);
  13035. llm_load_hparams(ml, model);
  13036. struct quantize_state_internal qs(model, params);
  13037. if (params->only_copy) {
  13038. ftype = model.ftype;
  13039. }
  13040. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  13041. if (params->imatrix) {
  13042. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  13043. if (imatrix_data) {
  13044. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  13045. qs.has_imatrix = true;
  13046. // check imatrix for nans or infs
  13047. for (const auto & kv : *imatrix_data) {
  13048. for (float f : kv.second) {
  13049. if (!std::isfinite(f)) {
  13050. throw std::runtime_error(format("imatrix contains non-finite value %f\n", f));
  13051. }
  13052. }
  13053. }
  13054. }
  13055. }
  13056. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  13057. struct gguf_context * ctx_out = gguf_init_empty();
  13058. // copy the KV pairs from the input file
  13059. gguf_set_kv (ctx_out, ml.meta);
  13060. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION); // TODO: use LLM_KV
  13061. gguf_set_val_u32(ctx_out, "general.file_type", ftype); // TODO: use LLM_KV
  13062. // Remove split metadata
  13063. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  13064. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  13065. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  13066. if (params->kv_overrides) {
  13067. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  13068. for (auto & o : overrides) {
  13069. if (o.key[0] == 0) break;
  13070. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  13071. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  13072. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  13073. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  13074. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  13075. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  13076. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  13077. gguf_set_val_str(ctx_out, o.key, o.val_str);
  13078. } else {
  13079. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  13080. }
  13081. }
  13082. }
  13083. for (int i = 0; i < ml.n_tensors; ++i) {
  13084. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  13085. const std::string name = ggml_get_name(meta);
  13086. // TODO: avoid hardcoded tensor names - use the TN_* constants
  13087. if (name.find("attn_v.weight") != std::string::npos ||
  13088. name.find("attn_qkv.weight") != std::string::npos) {
  13089. ++qs.n_attention_wv;
  13090. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  13091. qs.has_output = true;
  13092. }
  13093. }
  13094. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  13095. // sanity checks
  13096. //
  13097. // - qs.n_attention_wv == 0 for Mamba models
  13098. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  13099. // - qs.n_attention_wv == 3 * model.hparams.n_layer for Encoder-Decoder models
  13100. //
  13101. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer || qs.n_attention_wv == 3 * (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  13102. size_t total_size_org = 0;
  13103. size_t total_size_new = 0;
  13104. std::vector<std::thread> workers;
  13105. workers.reserve(nthread);
  13106. int idx = 0;
  13107. std::vector<no_init<uint8_t>> read_data;
  13108. std::vector<no_init<uint8_t>> work;
  13109. std::vector<no_init<float>> f32_conv_buf;
  13110. uint16_t n_split = 1;
  13111. // Assume split index is continuous
  13112. if (params->keep_split) {
  13113. for (int i = 0; i < ml.n_tensors; ++i) {
  13114. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  13115. }
  13116. }
  13117. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  13118. ctx_outs[0] = ctx_out;
  13119. // populate the original tensors so we get an initial meta data
  13120. for (int i = 0; i < ml.n_tensors; ++i) {
  13121. auto weight = ml.get_weight(i);
  13122. uint16_t i_split = params->keep_split ? weight->idx : 0;
  13123. struct ggml_tensor * tensor = weight->tensor;
  13124. if (ctx_outs[i_split] == NULL) {
  13125. ctx_outs[i_split] = gguf_init_empty();
  13126. }
  13127. gguf_add_tensor(ctx_outs[i_split], tensor);
  13128. }
  13129. // Set split info if needed
  13130. if (n_split > 1) {
  13131. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  13132. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  13133. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  13134. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  13135. }
  13136. }
  13137. int cur_split = -1;
  13138. std::ofstream fout;
  13139. auto close_ofstream = [&]() {
  13140. // Write metadata and close file handler
  13141. if (fout.is_open()) {
  13142. fout.seekp(0);
  13143. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  13144. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  13145. fout.write((const char *) data.data(), data.size());
  13146. fout.close();
  13147. }
  13148. };
  13149. auto new_ofstream = [&](int index) {
  13150. cur_split = index;
  13151. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  13152. std::string fname = fname_out;
  13153. if (params->keep_split) {
  13154. char split_path[PATH_MAX] = {0};
  13155. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  13156. fname = std::string(split_path);
  13157. }
  13158. fout = std::ofstream(fname, std::ios::binary);
  13159. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  13160. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  13161. // placeholder for the meta data
  13162. ::zeros(fout, meta_size);
  13163. };
  13164. const auto tn = LLM_TN(model.arch);
  13165. new_ofstream(0);
  13166. for (int i = 0; i < ml.n_tensors; ++i) {
  13167. auto weight = ml.get_weight(i);
  13168. struct ggml_tensor * tensor = weight->tensor;
  13169. if (weight->idx != cur_split && params->keep_split) {
  13170. close_ofstream();
  13171. new_ofstream(weight->idx);
  13172. }
  13173. const std::string name = ggml_get_name(tensor);
  13174. if (!ml.use_mmap) {
  13175. if (read_data.size() < ggml_nbytes(tensor)) {
  13176. read_data.resize(ggml_nbytes(tensor));
  13177. }
  13178. tensor->data = read_data.data();
  13179. }
  13180. ml.load_data_for(tensor);
  13181. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  13182. ++idx, ml.n_tensors,
  13183. ggml_get_name(tensor),
  13184. llama_format_tensor_shape(tensor).c_str(),
  13185. ggml_type_name(tensor->type));
  13186. // This used to be a regex, but <regex> has an extreme cost to compile times.
  13187. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  13188. // quantize only 2D and 3D tensors (experts)
  13189. quantize &= (ggml_n_dims(tensor) >= 2);
  13190. // do not quantize norm tensors
  13191. quantize &= name.find("_norm.weight") == std::string::npos;
  13192. quantize &= params->quantize_output_tensor || name != "output.weight";
  13193. quantize &= !params->only_copy;
  13194. // do not quantize expert gating tensors
  13195. // NOTE: can't use LLM_TN here because the layer number is not known
  13196. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  13197. // do not quantize positional embeddings and token types (BERT)
  13198. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  13199. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  13200. // do not quantize Mamba's small yet 2D weights
  13201. // NOTE: can't use LLM_TN here because the layer number is not known
  13202. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  13203. quantize &= name.find("ssm_x.weight") == std::string::npos;
  13204. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  13205. // do not quantize relative position bias (T5)
  13206. quantize &= name.find("attn_rel_b.weight") == std::string::npos;
  13207. enum ggml_type new_type;
  13208. void * new_data;
  13209. size_t new_size;
  13210. if (quantize) {
  13211. new_type = default_type;
  13212. // get more optimal quantization type based on the tensor shape, layer, etc.
  13213. if (!params->pure && ggml_is_quantized(default_type)) {
  13214. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  13215. }
  13216. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  13217. new_type = params->token_embedding_type;
  13218. }
  13219. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  13220. new_type = params->output_tensor_type;
  13221. }
  13222. // If we've decided to quantize to the same type the tensor is already
  13223. // in then there's nothing to do.
  13224. quantize = tensor->type != new_type;
  13225. }
  13226. if (!quantize) {
  13227. new_type = tensor->type;
  13228. new_data = tensor->data;
  13229. new_size = ggml_nbytes(tensor);
  13230. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  13231. } else {
  13232. const int64_t nelements = ggml_nelements(tensor);
  13233. const float * imatrix = nullptr;
  13234. if (imatrix_data) {
  13235. auto it = imatrix_data->find(tensor->name);
  13236. if (it == imatrix_data->end()) {
  13237. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  13238. } else {
  13239. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  13240. imatrix = it->second.data();
  13241. } else {
  13242. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  13243. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  13244. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  13245. // this is a significant error and it may be good idea to abort the process if this happens,
  13246. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  13247. // tok_embd should be ignored in this case, since it always causes this warning
  13248. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  13249. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  13250. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  13251. }
  13252. }
  13253. }
  13254. }
  13255. if ((new_type == GGML_TYPE_IQ2_XXS ||
  13256. new_type == GGML_TYPE_IQ2_XS ||
  13257. new_type == GGML_TYPE_IQ2_S ||
  13258. new_type == GGML_TYPE_IQ1_S ||
  13259. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  13260. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  13261. LLAMA_LOG_ERROR("\n\n============================================================\n");
  13262. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  13263. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  13264. LLAMA_LOG_ERROR("============================================================\n\n");
  13265. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  13266. }
  13267. float * f32_data;
  13268. if (tensor->type == GGML_TYPE_F32) {
  13269. f32_data = (float *) tensor->data;
  13270. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  13271. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  13272. } else {
  13273. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  13274. f32_data = (float *) f32_conv_buf.data();
  13275. }
  13276. int chunk_size_multiplier = 1;
  13277. 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) {
  13278. if ((new_type == GGML_TYPE_Q4_0_8_8) && (tensor->ne[1] % 8 != 0)) new_type = GGML_TYPE_Q4_0;
  13279. else if (tensor->ne[1] % 4 != 0) new_type = GGML_TYPE_Q4_0;
  13280. if (new_type == GGML_TYPE_Q4_0_8_8) chunk_size_multiplier = 8;
  13281. else if (new_type == GGML_TYPE_Q4_0_4_4 || new_type == GGML_TYPE_Q4_0_4_8) chunk_size_multiplier = 4;
  13282. }
  13283. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  13284. fflush(stdout);
  13285. if (work.size() < (size_t)nelements * 4) {
  13286. work.resize(nelements * 4); // upper bound on size
  13287. }
  13288. new_data = work.data();
  13289. const int64_t n_per_row = tensor->ne[0];
  13290. const int64_t nrows = tensor->ne[1];
  13291. static const int64_t min_chunk_size = 32 * 512;
  13292. 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)) *
  13293. chunk_size_multiplier;
  13294. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  13295. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  13296. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  13297. // quantize each expert separately since they have different importance matrices
  13298. new_size = 0;
  13299. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  13300. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  13301. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  13302. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  13303. 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);
  13304. }
  13305. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  13306. }
  13307. total_size_org += ggml_nbytes(tensor);
  13308. total_size_new += new_size;
  13309. // update the gguf meta data as we go
  13310. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  13311. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  13312. // write tensor data + padding
  13313. fout.write((const char *) new_data, new_size);
  13314. zeros(fout, GGML_PAD(new_size, align) - new_size);
  13315. }
  13316. close_ofstream();
  13317. for (auto & c:ctx_outs) {
  13318. gguf_free(c);
  13319. }
  13320. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  13321. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  13322. if (qs.n_fallback > 0) {
  13323. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  13324. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  13325. }
  13326. }
  13327. static void llama_lora_adapter_init_internal(struct llama_model * model, const char * path_lora, struct llama_lora_adapter & adapter) {
  13328. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  13329. ggml_context * ctx = nullptr;
  13330. struct gguf_init_params meta_gguf_params = {
  13331. /* .no_alloc = */ true,
  13332. /* .ctx = */ &ctx,
  13333. };
  13334. struct gguf_context * ctx_gguf = gguf_init_from_file(path_lora, meta_gguf_params);
  13335. if (!ctx_gguf) {
  13336. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  13337. }
  13338. // check metadata
  13339. {
  13340. auto get_kv_str = [&](const std::string & key) -> std::string {
  13341. int id = gguf_find_key(ctx_gguf, key.c_str());
  13342. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf, id));
  13343. };
  13344. auto get_kv_f32 = [&](const std::string & key) -> float {
  13345. int id = gguf_find_key(ctx_gguf, key.c_str());
  13346. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf, id);
  13347. };
  13348. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  13349. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  13350. if (general_type != "adapter") {
  13351. gguf_free(ctx_gguf);
  13352. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  13353. }
  13354. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  13355. auto general_arch = llm_arch_from_string(general_arch_str);
  13356. if (general_arch != model->arch) {
  13357. gguf_free(ctx_gguf);
  13358. throw std::runtime_error("model arch and LoRA arch mismatch");
  13359. }
  13360. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  13361. if (adapter_type != "lora") {
  13362. gguf_free(ctx_gguf);
  13363. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  13364. }
  13365. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  13366. }
  13367. int n_tensors = gguf_get_n_tensors(ctx_gguf);
  13368. // contexts for each buffer type
  13369. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  13370. auto get_ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  13371. auto it = ctx_map.find(buft);
  13372. if (it == ctx_map.end()) {
  13373. // add a new context
  13374. struct ggml_init_params params = {
  13375. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  13376. /*.mem_buffer =*/ NULL,
  13377. /*.no_alloc =*/ true,
  13378. };
  13379. ggml_context * buft_ctx = ggml_init(params);
  13380. ctx_map[buft] = buft_ctx;
  13381. return buft_ctx;
  13382. };
  13383. return it->second;
  13384. };
  13385. // bundle lora_a and lora_b into pairs
  13386. std::map<std::string, llama_lora_weight> ab_map;
  13387. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  13388. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  13389. };
  13390. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  13391. std::string name(cur->name);
  13392. if (str_endswith(name, ".lora_a")) {
  13393. replace_all(name, ".lora_a", "");
  13394. if (ab_map.find(name) == ab_map.end()) {
  13395. ab_map[name] = llama_lora_weight(cur, nullptr);
  13396. } else {
  13397. ab_map[name].a = cur;
  13398. }
  13399. } else if (str_endswith(name, ".lora_b")) {
  13400. replace_all(name, ".lora_b", "");
  13401. if (ab_map.find(name) == ab_map.end()) {
  13402. ab_map[name] = llama_lora_weight(nullptr, cur);
  13403. } else {
  13404. ab_map[name].b = cur;
  13405. }
  13406. } else {
  13407. gguf_free(ctx_gguf);
  13408. ggml_free(ctx);
  13409. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  13410. }
  13411. }
  13412. // add tensors
  13413. for (auto & it : ab_map) {
  13414. const std::string & name = it.first;
  13415. llama_lora_weight & w = it.second;
  13416. if (!w.a || !w.b) {
  13417. gguf_free(ctx_gguf);
  13418. ggml_free(ctx);
  13419. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  13420. }
  13421. // device buft and device ctx
  13422. auto * model_tensor = llama_get_model_tensor(model, name.c_str());
  13423. if (!model_tensor) {
  13424. gguf_free(ctx_gguf);
  13425. ggml_free(ctx);
  13426. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  13427. }
  13428. struct ggml_context * dev_ctx = get_ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  13429. // validate tensor shape
  13430. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  13431. gguf_free(ctx_gguf);
  13432. ggml_free(ctx);
  13433. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  13434. }
  13435. if (w.a->ne[1] != w.b->ne[0]) {
  13436. gguf_free(ctx_gguf);
  13437. ggml_free(ctx);
  13438. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  13439. }
  13440. // save tensor to adapter
  13441. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  13442. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  13443. ggml_set_name(tensor_a, w.a->name);
  13444. ggml_set_name(tensor_b, w.b->name);
  13445. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  13446. }
  13447. // allocate tensors / buffers and zero
  13448. {
  13449. adapter.ctxs.reserve(ctx_map.size());
  13450. adapter.bufs.reserve(ctx_map.size());
  13451. for (auto it : ctx_map) {
  13452. ggml_backend_buffer_type_t buft = it.first;
  13453. ggml_context * ctx_dev = it.second;
  13454. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft);
  13455. if (!buf) {
  13456. gguf_free(ctx_gguf);
  13457. ggml_free(ctx);
  13458. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  13459. }
  13460. 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);
  13461. adapter.ctxs.push_back(ctx_dev);
  13462. adapter.bufs.push_back(buf);
  13463. }
  13464. }
  13465. // set tensor data
  13466. {
  13467. llama_file gguf_file(path_lora, "rb");
  13468. std::vector<uint8_t> read_buf;
  13469. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  13470. size_t offs = gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, gguf_find_tensor(ctx_gguf, orig->name));
  13471. size_t size = ggml_nbytes(orig);
  13472. read_buf.resize(size);
  13473. gguf_file.seek(offs, SEEK_SET);
  13474. gguf_file.read_raw(read_buf.data(), size);
  13475. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  13476. };
  13477. for (auto & it : adapter.ab_map) {
  13478. auto orig = ab_map[it.first];
  13479. auto dev = it.second;
  13480. set_tensor(orig.a, dev.a);
  13481. set_tensor(orig.b, dev.b);
  13482. }
  13483. }
  13484. LLAMA_LOG_INFO("%s: loaded %ld tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  13485. // free ctx for reading gguf
  13486. gguf_free(ctx_gguf);
  13487. ggml_free(ctx);
  13488. }
  13489. int32_t llama_lora_adapter_set(
  13490. struct llama_context * ctx,
  13491. struct llama_lora_adapter * adapter,
  13492. float scale) {
  13493. if (ctx->cparams.flash_attn) {
  13494. LLAMA_LOG_ERROR("%s: flash_attn is not compatible with LoRA\n", __func__);
  13495. return -1;
  13496. }
  13497. ctx->lora_adapters[adapter] = scale;
  13498. return 0;
  13499. }
  13500. int32_t llama_lora_adapter_remove(
  13501. struct llama_context * ctx,
  13502. struct llama_lora_adapter * adapter) {
  13503. auto pos = ctx->lora_adapters.find(adapter);
  13504. if (pos != ctx->lora_adapters.end()) {
  13505. ctx->lora_adapters.erase(pos);
  13506. return 0;
  13507. }
  13508. return -1;
  13509. }
  13510. void llama_lora_adapter_clear(struct llama_context * ctx) {
  13511. ctx->lora_adapters.clear();
  13512. }
  13513. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  13514. delete adapter;
  13515. }
  13516. //
  13517. // interface implementation
  13518. //
  13519. struct llama_model_params llama_model_default_params() {
  13520. struct llama_model_params result = {
  13521. /*.n_gpu_layers =*/ 0,
  13522. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  13523. /*.main_gpu =*/ 0,
  13524. /*.tensor_split =*/ nullptr,
  13525. /*.rpc_servers =*/ nullptr,
  13526. /*.progress_callback =*/ nullptr,
  13527. /*.progress_callback_user_data =*/ nullptr,
  13528. /*.kv_overrides =*/ nullptr,
  13529. /*.vocab_only =*/ false,
  13530. /*.use_mmap =*/ true,
  13531. /*.use_mlock =*/ false,
  13532. /*.check_tensors =*/ false,
  13533. };
  13534. #ifdef GGML_USE_METAL
  13535. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  13536. result.n_gpu_layers = 999;
  13537. #endif
  13538. return result;
  13539. }
  13540. struct llama_context_params llama_context_default_params() {
  13541. struct llama_context_params result = {
  13542. /*.seed =*/ LLAMA_DEFAULT_SEED,
  13543. /*.n_ctx =*/ 512,
  13544. /*.n_batch =*/ 2048,
  13545. /*.n_ubatch =*/ 512,
  13546. /*.n_seq_max =*/ 1,
  13547. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  13548. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  13549. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  13550. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  13551. /*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
  13552. /*.rope_freq_base =*/ 0.0f,
  13553. /*.rope_freq_scale =*/ 0.0f,
  13554. /*.yarn_ext_factor =*/ -1.0f,
  13555. /*.yarn_attn_factor =*/ 1.0f,
  13556. /*.yarn_beta_fast =*/ 32.0f,
  13557. /*.yarn_beta_slow =*/ 1.0f,
  13558. /*.yarn_orig_ctx =*/ 0,
  13559. /*.defrag_thold =*/ -1.0f,
  13560. /*.cb_eval =*/ nullptr,
  13561. /*.cb_eval_user_data =*/ nullptr,
  13562. /*.type_k =*/ GGML_TYPE_F16,
  13563. /*.type_v =*/ GGML_TYPE_F16,
  13564. /*.logits_all =*/ false,
  13565. /*.embeddings =*/ false,
  13566. /*.offload_kqv =*/ true,
  13567. /*.flash_attn =*/ false,
  13568. /*.abort_callback =*/ nullptr,
  13569. /*.abort_callback_data =*/ nullptr,
  13570. };
  13571. return result;
  13572. }
  13573. struct llama_model_quantize_params llama_model_quantize_default_params() {
  13574. struct llama_model_quantize_params result = {
  13575. /*.nthread =*/ 0,
  13576. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  13577. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  13578. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  13579. /*.allow_requantize =*/ false,
  13580. /*.quantize_output_tensor =*/ true,
  13581. /*.only_copy =*/ false,
  13582. /*.pure =*/ false,
  13583. /*.keep_split =*/ false,
  13584. /*.imatrix =*/ nullptr,
  13585. /*.kv_overrides =*/ nullptr,
  13586. };
  13587. return result;
  13588. }
  13589. size_t llama_max_devices(void) {
  13590. #if defined(GGML_USE_RPC)
  13591. return GGML_RPC_MAX_SERVERS;
  13592. #elif defined(GGML_USE_METAL)
  13593. return 1;
  13594. #elif defined(GGML_USE_CUDA)
  13595. return GGML_CUDA_MAX_DEVICES;
  13596. #elif defined(GGML_USE_SYCL)
  13597. return GGML_SYCL_MAX_DEVICES;
  13598. #elif defined(GGML_USE_VULKAN)
  13599. return GGML_VK_MAX_DEVICES;
  13600. #elif defined(GGML_USE_CANN)
  13601. return GGML_CANN_MAX_DEVICES;
  13602. #else
  13603. return 1;
  13604. #endif
  13605. }
  13606. bool llama_supports_mmap(void) {
  13607. return llama_mmap::SUPPORTED;
  13608. }
  13609. bool llama_supports_mlock(void) {
  13610. return llama_mlock::SUPPORTED;
  13611. }
  13612. bool llama_supports_gpu_offload(void) {
  13613. #if defined(GGML_USE_CUDA) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  13614. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  13615. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  13616. return true;
  13617. #else
  13618. return false;
  13619. #endif
  13620. }
  13621. void llama_backend_init(void) {
  13622. ggml_time_init();
  13623. // needed to initialize f16 tables
  13624. {
  13625. struct ggml_init_params params = { 0, NULL, false };
  13626. struct ggml_context * ctx = ggml_init(params);
  13627. ggml_free(ctx);
  13628. }
  13629. }
  13630. void llama_numa_init(enum ggml_numa_strategy numa) {
  13631. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  13632. ggml_numa_init(numa);
  13633. }
  13634. }
  13635. void llama_backend_free(void) {
  13636. ggml_quantize_free();
  13637. }
  13638. int64_t llama_time_us(void) {
  13639. return ggml_time_us();
  13640. }
  13641. struct llama_model * llama_load_model_from_file(
  13642. const char * path_model,
  13643. struct llama_model_params params) {
  13644. ggml_time_init();
  13645. llama_model * model = new llama_model;
  13646. unsigned cur_percentage = 0;
  13647. if (params.progress_callback == NULL) {
  13648. params.progress_callback_user_data = &cur_percentage;
  13649. params.progress_callback = [](float progress, void * ctx) {
  13650. unsigned * cur_percentage_p = (unsigned *) ctx;
  13651. unsigned percentage = (unsigned) (100 * progress);
  13652. while (percentage > *cur_percentage_p) {
  13653. *cur_percentage_p = percentage;
  13654. LLAMA_LOG_INFO(".");
  13655. if (percentage >= 100) {
  13656. LLAMA_LOG_INFO("\n");
  13657. }
  13658. }
  13659. return true;
  13660. };
  13661. }
  13662. if (params.rpc_servers != nullptr && params.rpc_servers[0] != '\0') {
  13663. // split the servers set them into model->rpc_servers
  13664. std::string servers(params.rpc_servers);
  13665. size_t pos = 0;
  13666. while ((pos = servers.find(",")) != std::string::npos) {
  13667. std::string server = servers.substr(0, pos);
  13668. model->rpc_servers.push_back(server);
  13669. servers.erase(0, pos + 1);
  13670. }
  13671. model->rpc_servers.push_back(servers);
  13672. }
  13673. int status = llama_model_load(path_model, *model, params);
  13674. GGML_ASSERT(status <= 0);
  13675. if (status < 0) {
  13676. if (status == -1) {
  13677. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  13678. } else if (status == -2) {
  13679. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  13680. }
  13681. delete model;
  13682. return nullptr;
  13683. }
  13684. return model;
  13685. }
  13686. void llama_free_model(struct llama_model * model) {
  13687. delete model;
  13688. }
  13689. struct llama_context * llama_new_context_with_model(
  13690. struct llama_model * model,
  13691. struct llama_context_params params) {
  13692. if (!model) {
  13693. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  13694. return nullptr;
  13695. }
  13696. if (params.n_batch == 0 && params.n_ubatch == 0) {
  13697. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  13698. return nullptr;
  13699. }
  13700. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  13701. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  13702. return nullptr;
  13703. }
  13704. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  13705. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  13706. params.flash_attn = false;
  13707. }
  13708. if (params.flash_attn && model->hparams.attn_soft_cap) {
  13709. LLAMA_LOG_WARN("%s: flash_attn is not compatible with attn_soft_cap - forcing off\n", __func__);
  13710. params.flash_attn = false;
  13711. }
  13712. if (params.flash_attn && model->hparams.n_embd_head_k != model->hparams.n_embd_head_v) {
  13713. LLAMA_LOG_WARN("%s: flash_attn requires n_embd_head_k == n_embd_head_v - forcing off\n", __func__);
  13714. params.flash_attn = false;
  13715. }
  13716. if (params.type_v != GGML_TYPE_F16 && !params.flash_attn) {
  13717. LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
  13718. return nullptr;
  13719. }
  13720. llama_context * ctx = new llama_context(*model);
  13721. const auto & hparams = model->hparams;
  13722. auto & cparams = ctx->cparams;
  13723. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  13724. cparams.n_threads = params.n_threads;
  13725. cparams.n_threads_batch = params.n_threads_batch;
  13726. cparams.yarn_ext_factor = params.yarn_ext_factor;
  13727. cparams.yarn_attn_factor = params.yarn_attn_factor;
  13728. cparams.yarn_beta_fast = params.yarn_beta_fast;
  13729. cparams.yarn_beta_slow = params.yarn_beta_slow;
  13730. cparams.defrag_thold = params.defrag_thold;
  13731. cparams.embeddings = params.embeddings;
  13732. cparams.offload_kqv = params.offload_kqv;
  13733. cparams.flash_attn = params.flash_attn;
  13734. cparams.pooling_type = params.pooling_type;
  13735. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  13736. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  13737. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  13738. // this is necessary due to kv_self.n being padded later during inference
  13739. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  13740. // with causal attention, the batch size is limited by the context size
  13741. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  13742. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  13743. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  13744. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  13745. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  13746. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  13747. cparams.n_batch = GGML_KQ_MASK_PAD;
  13748. }
  13749. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  13750. cparams.n_ctx_orig_yarn = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  13751. hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
  13752. hparams.n_ctx_train;
  13753. cparams.cb_eval = params.cb_eval;
  13754. cparams.cb_eval_user_data = params.cb_eval_user_data;
  13755. auto rope_scaling_type = params.rope_scaling_type;
  13756. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  13757. rope_scaling_type = hparams.rope_scaling_type_train;
  13758. }
  13759. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  13760. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  13761. }
  13762. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  13763. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  13764. }
  13765. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  13766. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13767. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13768. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  13769. } else {
  13770. cparams.pooling_type = hparams.pooling_type;
  13771. }
  13772. }
  13773. if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
  13774. cparams.causal_attn = hparams.causal_attn;
  13775. } else {
  13776. cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
  13777. }
  13778. if (params.seed == LLAMA_DEFAULT_SEED) {
  13779. params.seed = time(NULL);
  13780. }
  13781. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  13782. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  13783. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  13784. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  13785. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  13786. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  13787. ctx->abort_callback = params.abort_callback;
  13788. ctx->abort_callback_data = params.abort_callback_data;
  13789. ctx->sampling.rng = std::mt19937(params.seed);
  13790. ctx->logits_all = params.logits_all;
  13791. uint32_t kv_size = cparams.n_ctx;
  13792. ggml_type type_k = params.type_k;
  13793. ggml_type type_v = params.type_v;
  13794. // Mamba only needs a constant number of KV cache cells per sequence
  13795. if (model->arch == LLM_ARCH_MAMBA) {
  13796. // Mamba needs at least as many KV cells as there are sequences kept at any time
  13797. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  13798. // it's probably best to keep as much precision as possible for the states
  13799. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  13800. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  13801. }
  13802. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  13803. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  13804. if (!hparams.vocab_only) {
  13805. // initialize backends
  13806. #if defined(GGML_USE_METAL)
  13807. if (model->n_gpu_layers > 0) {
  13808. ctx->backend_metal = ggml_backend_metal_init();
  13809. if (ctx->backend_metal == nullptr) {
  13810. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  13811. llama_free(ctx);
  13812. return nullptr;
  13813. }
  13814. ctx->backends.push_back(ctx->backend_metal);
  13815. }
  13816. #elif defined(GGML_USE_CUDA)
  13817. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13818. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13819. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  13820. if (backend == nullptr) {
  13821. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  13822. llama_free(ctx);
  13823. return nullptr;
  13824. }
  13825. ctx->backends.push_back(backend);
  13826. } else {
  13827. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13828. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  13829. ggml_backend_t backend = ggml_backend_cuda_init(device);
  13830. if (backend == nullptr) {
  13831. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  13832. llama_free(ctx);
  13833. return nullptr;
  13834. }
  13835. ctx->backends.push_back(backend);
  13836. }
  13837. }
  13838. #elif defined(GGML_USE_VULKAN)
  13839. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13840. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  13841. llama_free(ctx);
  13842. return nullptr;
  13843. }
  13844. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  13845. ggml_backend_t backend = ggml_backend_vk_init(model->main_gpu);
  13846. if (backend == nullptr) {
  13847. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  13848. llama_free(ctx);
  13849. return nullptr;
  13850. }
  13851. ctx->backends.push_back(backend);
  13852. } else {
  13853. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  13854. ggml_backend_t backend = ggml_backend_vk_init(device);
  13855. if (backend == nullptr) {
  13856. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  13857. llama_free(ctx);
  13858. return nullptr;
  13859. }
  13860. ctx->backends.push_back(backend);
  13861. }
  13862. }
  13863. #elif defined(GGML_USE_SYCL)
  13864. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13865. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13866. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  13867. if (backend == nullptr) {
  13868. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  13869. llama_free(ctx);
  13870. return nullptr;
  13871. }
  13872. ctx->backends.push_back(backend);
  13873. } else {
  13874. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  13875. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  13876. ggml_backend_t backend = ggml_backend_sycl_init(i);
  13877. if (backend == nullptr) {
  13878. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d for No.%d backend\n", __func__, i, i);
  13879. llama_free(ctx);
  13880. return nullptr;
  13881. }
  13882. ctx->backends.push_back(backend);
  13883. }
  13884. }
  13885. #elif defined(GGML_USE_KOMPUTE)
  13886. if (model->n_gpu_layers > 0) {
  13887. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  13888. if (backend == nullptr) {
  13889. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  13890. llama_free(ctx);
  13891. return nullptr;
  13892. }
  13893. ctx->backends.push_back(backend);
  13894. }
  13895. #elif defined(GGML_USE_CANN)
  13896. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13897. // TODO: ggml_backend_cann is not support split tensor now, just leave code here.
  13898. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13899. ggml_backend_t backend = ggml_backend_cann_init(model->main_gpu);
  13900. if (backend == nullptr) {
  13901. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, model->main_gpu);
  13902. llama_free(ctx);
  13903. return nullptr;
  13904. }
  13905. ctx->backends.push_back(backend);
  13906. } else {
  13907. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13908. // TODO: currently, CANN can't use multi-gpus, just leave code here for further cann version.
  13909. for (int32_t device = 0; device < ggml_backend_cann_get_device_count(); ++device) {
  13910. ggml_backend_t backend = ggml_backend_cann_init(device);
  13911. if (backend == nullptr) {
  13912. LLAMA_LOG_ERROR("%s: failed to initialize CANN%d backend\n", __func__, device);
  13913. llama_free(ctx);
  13914. return nullptr;
  13915. }
  13916. ctx->backends.push_back(backend);
  13917. }
  13918. }
  13919. #endif
  13920. #ifdef GGML_USE_BLAS
  13921. ctx->backend_blas = ggml_backend_blas_init();
  13922. if (ctx->backend_blas == nullptr) {
  13923. LLAMA_LOG_WARN("%s: failed to initialize BLAS backend\n", __func__);
  13924. } else {
  13925. ctx->backends.push_back(ctx->backend_blas);
  13926. }
  13927. #endif
  13928. #if defined(GGML_USE_RPC)
  13929. if (model->n_gpu_layers > 0) {
  13930. for (const auto & endpoint : model->rpc_servers) {
  13931. ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str());
  13932. if (backend == nullptr) {
  13933. LLAMA_LOG_ERROR("%s: failed to initialize RPC to '%s'\n", __func__, endpoint.c_str());
  13934. llama_free(ctx);
  13935. return nullptr;
  13936. }
  13937. ctx->backends.push_back(backend);
  13938. }
  13939. }
  13940. #endif
  13941. ctx->backend_cpu = ggml_backend_cpu_init();
  13942. if (ctx->backend_cpu == nullptr) {
  13943. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  13944. llama_free(ctx);
  13945. return nullptr;
  13946. }
  13947. ctx->backends.push_back(ctx->backend_cpu);
  13948. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  13949. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  13950. llama_free(ctx);
  13951. return nullptr;
  13952. }
  13953. {
  13954. size_t memory_size_k = 0;
  13955. size_t memory_size_v = 0;
  13956. for (auto & k : ctx->kv_self.k_l) {
  13957. memory_size_k += ggml_nbytes(k);
  13958. }
  13959. for (auto & v : ctx->kv_self.v_l) {
  13960. memory_size_v += ggml_nbytes(v);
  13961. }
  13962. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  13963. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  13964. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  13965. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  13966. }
  13967. // graph outputs buffer
  13968. {
  13969. // resized during inference when a batch uses more outputs
  13970. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  13971. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  13972. llama_free(ctx);
  13973. return nullptr;
  13974. }
  13975. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  13976. ggml_backend_buffer_name(ctx->buf_output),
  13977. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  13978. }
  13979. // scheduler and compute buffers
  13980. {
  13981. // buffer types used for the compute buffer of each backend
  13982. std::vector<ggml_backend_buffer_type_t> backend_buft;
  13983. for (auto * backend : ctx->backends) {
  13984. if (ggml_backend_is_cpu(backend)) {
  13985. // use host buffers for the CPU backend compute buffer
  13986. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  13987. } else {
  13988. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  13989. }
  13990. }
  13991. const size_t max_nodes = llama_model_max_nodes(*model);
  13992. // buffer used to store the computation graph and the tensor meta data
  13993. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false));
  13994. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  13995. bool pipeline_parallel =
  13996. llama_get_device_count(*model) > 1 &&
  13997. model->n_gpu_layers > (int)model->hparams.n_layer &&
  13998. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  13999. params.offload_kqv;
  14000. #ifndef GGML_USE_CUDA
  14001. // pipeline parallelism requires support for async compute and events
  14002. // currently this is only implemented in the CUDA backend
  14003. pipeline_parallel = false;
  14004. #endif
  14005. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), max_nodes, pipeline_parallel);
  14006. if (pipeline_parallel) {
  14007. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  14008. }
  14009. // build worst-case graph
  14010. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  14011. int n_past = cparams.n_ctx - n_tokens;
  14012. 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
  14013. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  14014. // initialize scheduler with the worst-case graph
  14015. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  14016. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  14017. llama_free(ctx);
  14018. return nullptr;
  14019. }
  14020. for (size_t i = 0; i < ctx->backends.size(); i++) {
  14021. ggml_backend_t backend = ctx->backends[i];
  14022. ggml_backend_buffer_type_t buft = backend_buft[i];
  14023. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  14024. if (size > 1) {
  14025. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  14026. ggml_backend_buft_name(buft),
  14027. size / 1024.0 / 1024.0);
  14028. }
  14029. }
  14030. // note: the number of splits during measure is higher than during inference due to the kv shift
  14031. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  14032. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  14033. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  14034. }
  14035. }
  14036. return ctx;
  14037. }
  14038. void llama_free(struct llama_context * ctx) {
  14039. delete ctx;
  14040. }
  14041. const struct llama_model * llama_get_model(const struct llama_context * ctx) {
  14042. return &ctx->model;
  14043. }
  14044. const struct llama_vocab * llama_get_vocab(const struct llama_context * ctx) {
  14045. return &ctx->model.vocab;
  14046. }
  14047. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  14048. return ctx->cparams.n_ctx;
  14049. }
  14050. uint32_t llama_n_batch(const struct llama_context * ctx) {
  14051. return ctx->cparams.n_batch;
  14052. }
  14053. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  14054. return ctx->cparams.n_ubatch;
  14055. }
  14056. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  14057. return ctx->kv_self.size;
  14058. }
  14059. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  14060. return model->vocab.type;
  14061. }
  14062. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  14063. switch (model->arch) {
  14064. // these models do not use RoPE
  14065. case LLM_ARCH_GPT2:
  14066. case LLM_ARCH_GPTJ:
  14067. case LLM_ARCH_MPT:
  14068. case LLM_ARCH_REFACT:
  14069. case LLM_ARCH_BLOOM:
  14070. case LLM_ARCH_MAMBA:
  14071. case LLM_ARCH_JINA_BERT_V2:
  14072. case LLM_ARCH_T5:
  14073. case LLM_ARCH_JAIS:
  14074. return LLAMA_ROPE_TYPE_NONE;
  14075. // use what we call a normal RoPE, operating on pairs of consecutive head values
  14076. case LLM_ARCH_LLAMA:
  14077. case LLM_ARCH_BAICHUAN:
  14078. case LLM_ARCH_STARCODER:
  14079. case LLM_ARCH_PLAMO:
  14080. case LLM_ARCH_ORION:
  14081. case LLM_ARCH_INTERNLM2:
  14082. case LLM_ARCH_MINICPM:
  14083. case LLM_ARCH_XVERSE:
  14084. case LLM_ARCH_COMMAND_R:
  14085. case LLM_ARCH_OLMO:
  14086. case LLM_ARCH_ARCTIC:
  14087. case LLM_ARCH_DEEPSEEK2:
  14088. case LLM_ARCH_CHATGLM:
  14089. return LLAMA_ROPE_TYPE_NORM;
  14090. // the pairs of head values are offset by n_rot/2
  14091. case LLM_ARCH_FALCON:
  14092. case LLM_ARCH_GROK:
  14093. case LLM_ARCH_DBRX:
  14094. case LLM_ARCH_BERT:
  14095. case LLM_ARCH_NOMIC_BERT:
  14096. case LLM_ARCH_STABLELM:
  14097. case LLM_ARCH_BITNET:
  14098. case LLM_ARCH_QWEN:
  14099. case LLM_ARCH_QWEN2:
  14100. case LLM_ARCH_QWEN2MOE:
  14101. case LLM_ARCH_PHI2:
  14102. case LLM_ARCH_PHI3:
  14103. case LLM_ARCH_GEMMA:
  14104. case LLM_ARCH_GEMMA2:
  14105. case LLM_ARCH_STARCODER2:
  14106. case LLM_ARCH_OPENELM:
  14107. case LLM_ARCH_GPTNEOX:
  14108. case LLM_ARCH_CODESHELL:
  14109. return LLAMA_ROPE_TYPE_NEOX;
  14110. // all model arches should be listed explicitly here
  14111. case LLM_ARCH_UNKNOWN:
  14112. GGML_ABORT("unknown architecture");
  14113. }
  14114. return LLAMA_ROPE_TYPE_NONE;
  14115. }
  14116. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  14117. return ctx->cparams.pooling_type;
  14118. }
  14119. int32_t llama_n_vocab(const struct llama_model * model) {
  14120. return model->hparams.n_vocab;
  14121. }
  14122. int32_t llama_n_ctx_train(const struct llama_model * model) {
  14123. return model->hparams.n_ctx_train;
  14124. }
  14125. int32_t llama_n_embd(const struct llama_model * model) {
  14126. return model->hparams.n_embd;
  14127. }
  14128. int32_t llama_n_layer(const struct llama_model * model) {
  14129. return model->hparams.n_layer;
  14130. }
  14131. float llama_rope_freq_scale_train(const struct llama_model * model) {
  14132. return model->hparams.rope_freq_scale_train;
  14133. }
  14134. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  14135. const auto & it = model->gguf_kv.find(key);
  14136. if (it == model->gguf_kv.end()) {
  14137. if (buf_size > 0) {
  14138. buf[0] = '\0';
  14139. }
  14140. return -1;
  14141. }
  14142. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14143. }
  14144. int32_t llama_model_meta_count(const struct llama_model * model) {
  14145. return (int)model->gguf_kv.size();
  14146. }
  14147. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  14148. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14149. if (buf_size > 0) {
  14150. buf[0] = '\0';
  14151. }
  14152. return -1;
  14153. }
  14154. auto it = model->gguf_kv.begin();
  14155. std::advance(it, i);
  14156. return snprintf(buf, buf_size, "%s", it->first.c_str());
  14157. }
  14158. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  14159. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  14160. if (buf_size > 0) {
  14161. buf[0] = '\0';
  14162. }
  14163. return -1;
  14164. }
  14165. auto it = model->gguf_kv.begin();
  14166. std::advance(it, i);
  14167. return snprintf(buf, buf_size, "%s", it->second.c_str());
  14168. }
  14169. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  14170. return snprintf(buf, buf_size, "%s %s %s",
  14171. llama_model_arch_name(model->arch),
  14172. llama_model_type_name(model->type),
  14173. llama_model_ftype_name(model->ftype).c_str());
  14174. }
  14175. uint64_t llama_model_size(const struct llama_model * model) {
  14176. uint64_t size = 0;
  14177. for (const auto & it : model->tensors_by_name) {
  14178. size += ggml_nbytes(it.second);
  14179. }
  14180. return size;
  14181. }
  14182. uint64_t llama_model_n_params(const struct llama_model * model) {
  14183. uint64_t nparams = 0;
  14184. for (const auto & it : model->tensors_by_name) {
  14185. nparams += ggml_nelements(it.second);
  14186. }
  14187. return nparams;
  14188. }
  14189. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  14190. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  14191. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  14192. return it.first == name;
  14193. });
  14194. if (it == model->tensors_by_name.end()) {
  14195. return nullptr;
  14196. }
  14197. return it->second;
  14198. }
  14199. bool llama_model_has_encoder(const struct llama_model * model) {
  14200. switch (model->arch) {
  14201. case LLM_ARCH_T5: return true;
  14202. default: return false;
  14203. }
  14204. }
  14205. llama_token llama_model_decoder_start_token(const struct llama_model * model) {
  14206. return model->hparams.dec_start_token_id;
  14207. }
  14208. uint32_t llama_model_quantize(
  14209. const char * fname_inp,
  14210. const char * fname_out,
  14211. const llama_model_quantize_params * params) {
  14212. try {
  14213. llama_model_quantize_internal(fname_inp, fname_out, params);
  14214. return 0;
  14215. } catch (const std::exception & err) {
  14216. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  14217. return 1;
  14218. }
  14219. }
  14220. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  14221. try {
  14222. struct llama_lora_adapter * adapter = new llama_lora_adapter(model);
  14223. llama_lora_adapter_init_internal(model, path_lora, *adapter);
  14224. return adapter;
  14225. } catch (const std::exception & err) {
  14226. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  14227. return nullptr;
  14228. }
  14229. }
  14230. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  14231. GGML_ASSERT(cvec.tensors.empty());
  14232. GGML_ASSERT(cvec.ctxs.empty());
  14233. GGML_ASSERT(cvec.bufs.empty());
  14234. // count layer buffer types
  14235. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  14236. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  14237. buft_layer_count[model.buft_layer[i].buft]++;
  14238. }
  14239. // allocate contexts
  14240. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  14241. for (auto & it : buft_layer_count) {
  14242. int n_layers = it.second;
  14243. struct ggml_init_params params = {
  14244. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  14245. /*.mem_buffer =*/ NULL,
  14246. /*.no_alloc =*/ true,
  14247. };
  14248. ggml_context * ctx = ggml_init(params);
  14249. if (!ctx) {
  14250. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  14251. return 1;
  14252. }
  14253. ctx_map[it.first] = ctx;
  14254. }
  14255. // make tensors
  14256. cvec.tensors.reserve(model.hparams.n_layer);
  14257. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  14258. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14259. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  14260. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  14261. cvec.tensors.push_back(tensor);
  14262. }
  14263. // allocate tensors / buffers and zero
  14264. cvec.ctxs.reserve(ctx_map.size());
  14265. cvec.bufs.reserve(ctx_map.size());
  14266. for (auto it : ctx_map) {
  14267. ggml_backend_buffer_type_t buft = it.first;
  14268. ggml_context * ctx = it.second;
  14269. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  14270. if (!buf) {
  14271. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  14272. return false;
  14273. }
  14274. ggml_backend_buffer_clear(buf, 0);
  14275. cvec.ctxs.push_back(ctx);
  14276. cvec.bufs.push_back(buf);
  14277. }
  14278. return true;
  14279. }
  14280. 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) {
  14281. const llama_model & model = lctx->model;
  14282. llama_control_vector & cvec = lctx->cvec;
  14283. if (data == nullptr) {
  14284. // disable the current control vector (but leave allocated for later)
  14285. cvec.layer_start = -1;
  14286. cvec.layer_end = -1;
  14287. return 0;
  14288. }
  14289. if (n_embd != (int) model.hparams.n_embd) {
  14290. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  14291. return 1;
  14292. }
  14293. if (cvec.tensors.empty()) {
  14294. if (!llama_control_vector_init(cvec, model)) {
  14295. return 1;
  14296. }
  14297. }
  14298. cvec.layer_start = il_start;
  14299. cvec.layer_end = il_end;
  14300. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14301. assert(cvec.tensors[il] != nullptr);
  14302. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  14303. if (off + n_embd <= len) {
  14304. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  14305. }
  14306. }
  14307. return 0;
  14308. }
  14309. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  14310. struct llama_kv_cache_view result = {
  14311. /*.n_cells = */ 0,
  14312. /*.n_seq_max = */ n_seq_max,
  14313. /*.token_count = */ 0,
  14314. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  14315. /*.max_contiguous = */ 0,
  14316. /*.max_contiguous_idx = */ -1,
  14317. /*.cells = */ nullptr,
  14318. /*.cells_sequences = */ nullptr,
  14319. };
  14320. return result;
  14321. }
  14322. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  14323. if (view->cells != nullptr) {
  14324. free(view->cells);
  14325. view->cells = nullptr;
  14326. }
  14327. if (view->cells_sequences != nullptr) {
  14328. free(view->cells_sequences);
  14329. view->cells_sequences = nullptr;
  14330. }
  14331. }
  14332. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  14333. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  14334. view->n_cells = int32_t(ctx->kv_self.size);
  14335. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  14336. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  14337. view->cells = (struct llama_kv_cache_view_cell *)p;
  14338. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  14339. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  14340. view->cells_sequences = (llama_seq_id *)p;
  14341. }
  14342. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  14343. llama_kv_cache_view_cell * c_curr = view->cells;
  14344. llama_seq_id * cs_curr = view->cells_sequences;
  14345. int32_t used_cells = 0;
  14346. int32_t token_count = 0;
  14347. int32_t curr_contig_idx = -1;
  14348. uint32_t max_contig = 0;
  14349. int32_t max_contig_idx = -1;
  14350. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  14351. const size_t curr_size = kv_cells[i].seq_id.size();
  14352. token_count += curr_size;
  14353. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  14354. if (curr_size > 0) {
  14355. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  14356. max_contig = i - curr_contig_idx;
  14357. max_contig_idx = curr_contig_idx;
  14358. }
  14359. curr_contig_idx = -1;
  14360. } else if (curr_contig_idx < 0) {
  14361. curr_contig_idx = i;
  14362. }
  14363. int seq_idx = 0;
  14364. for (const llama_seq_id it : kv_cells[i].seq_id) {
  14365. if (seq_idx >= view->n_seq_max) {
  14366. break;
  14367. }
  14368. cs_curr[seq_idx] = it;
  14369. seq_idx++;
  14370. }
  14371. if (seq_idx != 0) {
  14372. used_cells++;
  14373. }
  14374. for (; seq_idx < view->n_seq_max; seq_idx++) {
  14375. cs_curr[seq_idx] = -1;
  14376. }
  14377. }
  14378. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  14379. max_contig_idx = curr_contig_idx;
  14380. max_contig = kv_cells.size() - curr_contig_idx;
  14381. }
  14382. view->max_contiguous = max_contig;
  14383. view->max_contiguous_idx = max_contig_idx;
  14384. view->token_count = token_count;
  14385. view->used_cells = used_cells;
  14386. if (uint32_t(used_cells) != ctx->kv_self.used) {
  14387. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  14388. __func__, ctx->kv_self.used, used_cells);
  14389. }
  14390. }
  14391. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  14392. int result = 0;
  14393. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  14394. result += ctx->kv_self.cells[i].seq_id.size();
  14395. }
  14396. return result;
  14397. }
  14398. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  14399. return ctx->kv_self.used;
  14400. }
  14401. void llama_kv_cache_clear(struct llama_context * ctx) {
  14402. llama_kv_cache_clear(ctx->kv_self);
  14403. }
  14404. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  14405. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  14406. }
  14407. 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) {
  14408. if (seq_id_src == seq_id_dst) {
  14409. return;
  14410. }
  14411. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  14412. }
  14413. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  14414. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  14415. }
  14416. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  14417. if (delta == 0) {
  14418. return;
  14419. }
  14420. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  14421. }
  14422. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  14423. if (d == 1) {
  14424. return;
  14425. }
  14426. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  14427. }
  14428. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  14429. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  14430. }
  14431. void llama_kv_cache_defrag(struct llama_context * ctx) {
  14432. llama_kv_cache_defrag(ctx->kv_self);
  14433. }
  14434. void llama_kv_cache_update(struct llama_context * ctx) {
  14435. llama_kv_cache_update_internal(*ctx);
  14436. }
  14437. // deprecated
  14438. size_t llama_get_state_size(struct llama_context * ctx) {
  14439. return llama_state_get_size(ctx);
  14440. }
  14441. // deprecated
  14442. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  14443. return llama_state_get_data(ctx, dst, -1);
  14444. }
  14445. // deprecated
  14446. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  14447. return llama_state_set_data(ctx, src, -1);
  14448. }
  14449. // deprecated
  14450. 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) {
  14451. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14452. }
  14453. // deprecated
  14454. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14455. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  14456. }
  14457. // TODO: replace all non-fatal assertions with returned errors or exceptions
  14458. struct llama_data_write {
  14459. virtual void write(const void * src, size_t size) = 0;
  14460. virtual size_t get_size_written() = 0;
  14461. virtual ~llama_data_write() = default;
  14462. void write_string(const std::string & str) {
  14463. uint32_t str_size = str.size();
  14464. write(&str_size, sizeof(str_size));
  14465. write(str.data(), str_size);
  14466. }
  14467. void write_model_info(const struct llama_context * ctx) {
  14468. std::string arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14469. write_string(arch_str);
  14470. // TODO: add more model-specific info which should prevent loading the session file if not identical
  14471. }
  14472. void write_rng(const std::mt19937 & rng) {
  14473. std::ostringstream rng_ss;
  14474. rng_ss << rng;
  14475. const std::string & rng_str = rng_ss.str();
  14476. write_string(rng_str);
  14477. }
  14478. void write_output_ids(const struct llama_context * ctx) {
  14479. const uint32_t n_outputs = ctx->n_outputs;
  14480. std::vector<int32_t> output_pos;
  14481. const size_t n_batch = ctx->cparams.n_batch;
  14482. const auto & output_ids = ctx->output_ids;
  14483. GGML_ASSERT(n_outputs <= ctx->output_size);
  14484. output_pos.resize(n_outputs);
  14485. // build a more compact representation of the output ids
  14486. for (size_t i = 0; i < n_batch; ++i) {
  14487. // map an output id to a position in the batch
  14488. int32_t pos = output_ids[i];
  14489. if (pos >= 0) {
  14490. GGML_ASSERT((uint32_t) pos < n_outputs);
  14491. output_pos[pos] = i;
  14492. }
  14493. }
  14494. write(&n_outputs, sizeof(n_outputs));
  14495. if (n_outputs) {
  14496. write(output_pos.data(), n_outputs * sizeof(int32_t));
  14497. }
  14498. }
  14499. void write_logits(const struct llama_context * ctx) {
  14500. const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
  14501. write(&logits_size, sizeof(logits_size));
  14502. if (logits_size) {
  14503. write(ctx->logits, logits_size * sizeof(float));
  14504. }
  14505. }
  14506. void write_embeddings(const struct llama_context * ctx) {
  14507. const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
  14508. write(&embeddings_size, sizeof(embeddings_size));
  14509. if (embeddings_size) {
  14510. write(ctx->embd, embeddings_size * sizeof(float));
  14511. }
  14512. }
  14513. 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) {
  14514. for (const auto & range : cell_ranges) {
  14515. for (uint32_t i = range.first; i < range.second; ++i) {
  14516. const auto & cell = kv_self.cells[i];
  14517. const llama_pos pos = cell.pos;
  14518. const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
  14519. write(&pos, sizeof(pos));
  14520. write(&n_seq_id, sizeof(n_seq_id));
  14521. if (n_seq_id) {
  14522. for (auto seq_id : cell.seq_id) {
  14523. write(&seq_id, sizeof(seq_id));
  14524. }
  14525. }
  14526. }
  14527. }
  14528. }
  14529. void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
  14530. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14531. const struct llama_hparams & hparams = ctx->model.hparams;
  14532. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  14533. const uint32_t n_layer = hparams.n_layer;
  14534. write(&v_trans, sizeof(v_trans));
  14535. write(&n_layer, sizeof(n_layer));
  14536. std::vector<uint8_t> tmp_buf;
  14537. // Iterate and write all the keys first, each row is a cell
  14538. // Get whole range at a time
  14539. for (uint32_t il = 0; il < n_layer; ++il) {
  14540. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14541. // Write key type
  14542. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14543. write(&k_type_i, sizeof(k_type_i));
  14544. // Write row size of key
  14545. const uint64_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14546. write(&k_size_row, sizeof(k_size_row));
  14547. // Read each range of cells of k_size length each into tmp_buf and write out
  14548. for (const auto & range : cell_ranges) {
  14549. const size_t range_size = range.second - range.first;
  14550. tmp_buf.resize(range_size * k_size_row);
  14551. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  14552. write(tmp_buf.data(), tmp_buf.size());
  14553. }
  14554. }
  14555. if (!kv_self.v_trans) {
  14556. for (uint32_t il = 0; il < n_layer; ++il) {
  14557. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14558. // Write value type
  14559. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14560. write(&v_type_i, sizeof(v_type_i));
  14561. // Write row size of value
  14562. const uint64_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14563. write(&v_size_row, sizeof(v_size_row));
  14564. // Read each range of cells of v_size length each into tmp_buf and write out
  14565. for (const auto & range : cell_ranges) {
  14566. const size_t range_size = range.second - range.first;
  14567. tmp_buf.resize(range_size * v_size_row);
  14568. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), range.first * v_size_row, range_size * v_size_row);
  14569. write(tmp_buf.data(), tmp_buf.size());
  14570. }
  14571. }
  14572. } else {
  14573. // When v is transposed, we also need the element size and get the element ranges from each row
  14574. const uint32_t kv_size = kv_self.size;
  14575. for (uint32_t il = 0; il < n_layer; ++il) {
  14576. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14577. // Write value type
  14578. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14579. write(&v_type_i, sizeof(v_type_i));
  14580. // Write element size
  14581. const uint32_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14582. write(&v_size_el, sizeof(v_size_el));
  14583. // Write GQA embedding size
  14584. write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  14585. // For each row, we get the element values of each cell
  14586. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14587. // Read each range of cells of v_size_el length each into tmp_buf and write out
  14588. for (const auto & range : cell_ranges) {
  14589. const size_t range_size = range.second - range.first;
  14590. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  14591. tmp_buf.resize(range_size * v_size_el);
  14592. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  14593. write(tmp_buf.data(), tmp_buf.size());
  14594. }
  14595. }
  14596. }
  14597. }
  14598. }
  14599. void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14600. const struct llama_kv_cache & kv_self = ctx->kv_self;
  14601. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  14602. uint32_t cell_count = 0;
  14603. // Count the number of cells with the specified seq_id
  14604. // Find all the ranges of cells with this seq id (or all, when -1)
  14605. uint32_t cell_range_begin = kv_self.size;
  14606. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14607. const auto & cell = kv_self.cells[i];
  14608. if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
  14609. ++cell_count;
  14610. if (cell_range_begin == kv_self.size) {
  14611. cell_range_begin = i;
  14612. }
  14613. } else {
  14614. if (cell_range_begin != kv_self.size) {
  14615. cell_ranges.emplace_back(cell_range_begin, i);
  14616. cell_range_begin = kv_self.size;
  14617. }
  14618. }
  14619. }
  14620. if (cell_range_begin != kv_self.size) {
  14621. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  14622. }
  14623. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  14624. uint32_t cell_count_check = 0;
  14625. for (const auto & range : cell_ranges) {
  14626. cell_count_check += range.second - range.first;
  14627. }
  14628. GGML_ASSERT(cell_count == cell_count_check);
  14629. write(&cell_count, sizeof(cell_count));
  14630. write_kv_cache_meta(kv_self, cell_ranges, seq_id);
  14631. write_kv_cache_data(ctx, cell_ranges);
  14632. }
  14633. };
  14634. struct llama_data_read {
  14635. virtual const uint8_t * read(size_t size) = 0;
  14636. virtual void read_to(void * dst, size_t size) = 0;
  14637. virtual size_t get_size_read() = 0;
  14638. virtual ~llama_data_read() = default;
  14639. void read_string(std::string & str) {
  14640. uint32_t str_size;
  14641. read_to(&str_size, sizeof(str_size));
  14642. str.assign((const char *) read(str_size), str_size);
  14643. }
  14644. // validate model information
  14645. void read_model_info(const struct llama_context * ctx) {
  14646. std::string cur_arch_str = LLM_ARCH_NAMES.at(ctx->model.arch);
  14647. std::string arch_str;
  14648. read_string(arch_str);
  14649. if (cur_arch_str != arch_str) {
  14650. throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
  14651. }
  14652. // TODO: add more info which needs to be identical but which is not verified otherwise
  14653. }
  14654. void read_rng(std::mt19937 & rng) {
  14655. std::string rng_str;
  14656. read_string(rng_str);
  14657. std::istringstream rng_ss(rng_str);
  14658. rng_ss >> rng;
  14659. if (rng_ss.fail()) {
  14660. throw std::runtime_error("failed to load RNG state");
  14661. }
  14662. }
  14663. void read_output_ids(struct llama_context * ctx) {
  14664. std::vector<int32_t> output_pos;
  14665. uint32_t n_outputs;
  14666. read_to(&n_outputs, sizeof(n_outputs));
  14667. if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
  14668. throw std::runtime_error("could not reserve outputs");
  14669. }
  14670. if (n_outputs) {
  14671. output_pos.resize(n_outputs);
  14672. read_to(output_pos.data(), n_outputs * sizeof(int32_t));
  14673. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  14674. int32_t id = output_pos[i];
  14675. if ((uint32_t) id >= ctx->cparams.n_batch) {
  14676. throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
  14677. }
  14678. ctx->output_ids[id] = i;
  14679. }
  14680. ctx->n_outputs = n_outputs;
  14681. }
  14682. }
  14683. void read_logits(struct llama_context * ctx) {
  14684. uint64_t logits_size;
  14685. read_to(&logits_size, sizeof(logits_size));
  14686. if (ctx->logits_size < logits_size) {
  14687. throw std::runtime_error("logits buffer too small");
  14688. }
  14689. if (logits_size) {
  14690. read_to(ctx->logits, logits_size * sizeof(float));
  14691. }
  14692. }
  14693. void read_embeddings(struct llama_context * ctx) {
  14694. uint64_t embeddings_size;
  14695. read_to(&embeddings_size, sizeof(embeddings_size));
  14696. if (ctx->embd_size < embeddings_size) {
  14697. throw std::runtime_error("embeddings buffer too small");
  14698. }
  14699. if (embeddings_size) {
  14700. read_to(ctx->embd, embeddings_size * sizeof(float));
  14701. }
  14702. }
  14703. bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
  14704. struct llama_kv_cache & kv_self = ctx->kv_self;
  14705. if (dest_seq_id != -1) {
  14706. // single sequence
  14707. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14708. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  14709. batch.n_tokens = cell_count;
  14710. for (uint32_t i = 0; i < cell_count; ++i) {
  14711. llama_pos pos;
  14712. uint32_t n_seq_id;
  14713. read_to(&pos, sizeof(pos));
  14714. read_to(&n_seq_id, sizeof(n_seq_id));
  14715. if (n_seq_id != 0) {
  14716. LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
  14717. return false;
  14718. }
  14719. batch.pos[i] = pos;
  14720. batch.n_seq_id[i] = 1;
  14721. batch.seq_id[i][0] = dest_seq_id;
  14722. }
  14723. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  14724. llama_batch_free(batch);
  14725. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  14726. return false;
  14727. }
  14728. // 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)
  14729. // Assume that this is one contiguous block of cells
  14730. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  14731. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  14732. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  14733. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  14734. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  14735. // Cleanup
  14736. llama_batch_free(batch);
  14737. } else {
  14738. // whole KV cache restore
  14739. if (cell_count > kv_self.size) {
  14740. LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
  14741. return false;
  14742. }
  14743. llama_kv_cache_clear(kv_self);
  14744. for (uint32_t i = 0; i < cell_count; ++i) {
  14745. llama_kv_cell & cell = kv_self.cells[i];
  14746. llama_pos pos;
  14747. uint32_t n_seq_id;
  14748. read_to(&pos, sizeof(pos));
  14749. read_to(&n_seq_id, sizeof(n_seq_id));
  14750. cell.pos = pos;
  14751. for (uint32_t j = 0; j < n_seq_id; ++j) {
  14752. llama_seq_id seq_id;
  14753. read_to(&seq_id, sizeof(seq_id));
  14754. if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
  14755. LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
  14756. return false;
  14757. }
  14758. cell.seq_id.insert(seq_id);
  14759. }
  14760. }
  14761. kv_self.head = 0;
  14762. kv_self.used = cell_count;
  14763. }
  14764. return true;
  14765. }
  14766. bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
  14767. const struct llama_hparams & hparams = ctx->model.hparams;
  14768. struct llama_kv_cache & kv_self = ctx->kv_self;
  14769. uint32_t v_trans;
  14770. uint32_t n_layer;
  14771. read_to(&v_trans, sizeof(v_trans));
  14772. read_to(&n_layer, sizeof(n_layer));
  14773. if (n_layer != hparams.n_layer) {
  14774. LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
  14775. return false;
  14776. }
  14777. if (cell_count > kv_self.size) {
  14778. LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
  14779. return false;
  14780. }
  14781. if (kv_self.v_trans != (bool) v_trans) {
  14782. LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
  14783. return false;
  14784. }
  14785. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
  14786. for (uint32_t il = 0; il < n_layer; ++il) {
  14787. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
  14788. // Read type of key
  14789. int32_t k_type_i_ref;
  14790. read_to(&k_type_i_ref, sizeof(k_type_i_ref));
  14791. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14792. if (k_type_i != k_type_i_ref) {
  14793. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  14794. return false;
  14795. }
  14796. // Read row size of key
  14797. uint64_t k_size_row_ref;
  14798. read_to(&k_size_row_ref, sizeof(k_size_row_ref));
  14799. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14800. if (k_size_row != k_size_row_ref) {
  14801. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
  14802. return false;
  14803. }
  14804. if (cell_count) {
  14805. // Read and set the keys for the whole cell range
  14806. 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);
  14807. }
  14808. }
  14809. if (!kv_self.v_trans) {
  14810. for (uint32_t il = 0; il < n_layer; ++il) {
  14811. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14812. // Read type of value
  14813. int32_t v_type_i_ref;
  14814. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14815. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14816. if (v_type_i != v_type_i_ref) {
  14817. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14818. return false;
  14819. }
  14820. // Read row size of value
  14821. uint64_t v_size_row_ref;
  14822. read_to(&v_size_row_ref, sizeof(v_size_row_ref));
  14823. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14824. if (v_size_row != v_size_row_ref) {
  14825. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
  14826. return false;
  14827. }
  14828. if (cell_count) {
  14829. // Read and set the values for the whole cell range
  14830. 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);
  14831. }
  14832. }
  14833. } else {
  14834. // For each layer, read the values for each cell (transposed)
  14835. for (uint32_t il = 0; il < n_layer; ++il) {
  14836. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
  14837. // Read type of value
  14838. int32_t v_type_i_ref;
  14839. read_to(&v_type_i_ref, sizeof(v_type_i_ref));
  14840. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14841. if (v_type_i != v_type_i_ref) {
  14842. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14843. return false;
  14844. }
  14845. // Read element size of value
  14846. uint32_t v_size_el_ref;
  14847. read_to(&v_size_el_ref, sizeof(v_size_el_ref));
  14848. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14849. if (v_size_el != v_size_el_ref) {
  14850. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
  14851. return false;
  14852. }
  14853. // Read GQA embedding size
  14854. uint32_t n_embd_v_gqa_ref;
  14855. read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
  14856. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  14857. LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
  14858. return false;
  14859. }
  14860. if (cell_count) {
  14861. // For each row in the transposed matrix, read the values for the whole cell range
  14862. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14863. const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
  14864. ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
  14865. }
  14866. }
  14867. }
  14868. }
  14869. return true;
  14870. }
  14871. void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
  14872. uint32_t cell_count;
  14873. read_to(&cell_count, sizeof(cell_count));
  14874. bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
  14875. if (!res) {
  14876. if (seq_id == -1) {
  14877. llama_kv_cache_clear(ctx);
  14878. } else {
  14879. llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
  14880. }
  14881. throw std::runtime_error("failed to restore kv cache");
  14882. }
  14883. }
  14884. };
  14885. struct llama_data_write_dummy : llama_data_write {
  14886. size_t size_written = 0;
  14887. llama_data_write_dummy() {}
  14888. // TODO: avoid unnecessary calls to ggml_backend_tensor_get in a dummy context
  14889. void write(const void * /* src */, size_t size) override {
  14890. size_written += size;
  14891. }
  14892. size_t get_size_written() override {
  14893. return size_written;
  14894. }
  14895. };
  14896. struct llama_data_write_buffer : llama_data_write {
  14897. uint8_t * ptr;
  14898. size_t buf_size = 0;
  14899. size_t size_written = 0;
  14900. llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14901. void write(const void * src, size_t size) override {
  14902. if (size > buf_size) {
  14903. throw std::runtime_error("unexpectedly reached end of buffer");
  14904. }
  14905. memcpy(ptr, src, size);
  14906. ptr += size;
  14907. size_written += size;
  14908. buf_size -= size;
  14909. }
  14910. size_t get_size_written() override {
  14911. return size_written;
  14912. }
  14913. };
  14914. struct llama_data_read_buffer : llama_data_read {
  14915. const uint8_t * ptr;
  14916. size_t buf_size = 0;
  14917. size_t size_read = 0;
  14918. llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
  14919. const uint8_t * read(size_t size) override {
  14920. const uint8_t * base_ptr = ptr;
  14921. if (size > buf_size) {
  14922. throw std::runtime_error("unexpectedly reached end of buffer");
  14923. }
  14924. ptr += size;
  14925. size_read += size;
  14926. buf_size -= size;
  14927. return base_ptr;
  14928. }
  14929. void read_to(void * dst, size_t size) override {
  14930. memcpy(dst, read(size), size);
  14931. }
  14932. size_t get_size_read() override {
  14933. return size_read;
  14934. }
  14935. };
  14936. struct llama_data_write_file : llama_data_write {
  14937. llama_file * file;
  14938. size_t size_written = 0;
  14939. llama_data_write_file(llama_file * f) : file(f) {}
  14940. void write(const void * src, size_t size) override {
  14941. file->write_raw(src, size);
  14942. size_written += size;
  14943. }
  14944. size_t get_size_written() override {
  14945. return size_written;
  14946. }
  14947. };
  14948. struct llama_data_read_file : llama_data_read {
  14949. llama_file * file;
  14950. size_t size_read = 0;
  14951. std::vector<uint8_t> temp_buffer;
  14952. llama_data_read_file(llama_file * f) : file(f) {}
  14953. void read_to(void * dst, size_t size) override {
  14954. file->read_raw(dst, size);
  14955. size_read += size;
  14956. }
  14957. const uint8_t * read(size_t size) override {
  14958. temp_buffer.resize(size);
  14959. read_to(temp_buffer.data(), size);
  14960. return temp_buffer.data();
  14961. }
  14962. size_t get_size_read() override {
  14963. return size_read;
  14964. }
  14965. };
  14966. /** copy state data into either a buffer or file depending on the passed in context
  14967. *
  14968. * file context:
  14969. * llama_file file("/path", "wb");
  14970. * llama_data_write_file data_ctx(&file);
  14971. * llama_state_get_data_internal(ctx, data_ctx);
  14972. *
  14973. * buffer context:
  14974. * std::vector<uint8_t> buf(max_size, 0);
  14975. * llama_data_write_buffer data_ctx(buf.data(), max_size);
  14976. * llama_state_get_data_internal(ctx, data_ctx);
  14977. *
  14978. */
  14979. static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
  14980. llama_synchronize(ctx);
  14981. data_ctx.write_model_info(ctx);
  14982. data_ctx.write_rng(ctx->sampling.rng);
  14983. // copy outputs
  14984. data_ctx.write_output_ids(ctx);
  14985. data_ctx.write_logits(ctx);
  14986. data_ctx.write_embeddings(ctx);
  14987. data_ctx.write_kv_cache(ctx);
  14988. return data_ctx.get_size_written();
  14989. }
  14990. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
  14991. llama_data_write_buffer data_ctx(dst, size);
  14992. try {
  14993. return llama_state_get_data_internal(ctx, data_ctx);
  14994. } catch (const std::exception & err) {
  14995. LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
  14996. return 0;
  14997. }
  14998. }
  14999. // Returns the *actual* size of the state.
  15000. // Intended to be used when saving to state to a buffer.
  15001. size_t llama_state_get_size(struct llama_context * ctx) {
  15002. llama_data_write_dummy data_ctx;
  15003. try {
  15004. return llama_state_get_data_internal(ctx, data_ctx);
  15005. } catch (const std::exception & err) {
  15006. LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
  15007. return 0;
  15008. }
  15009. }
  15010. static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
  15011. llama_synchronize(ctx);
  15012. data_ctx.read_model_info(ctx);
  15013. // set rng
  15014. data_ctx.read_rng(ctx->sampling.rng);
  15015. // set outputs
  15016. data_ctx.read_output_ids(ctx);
  15017. data_ctx.read_logits(ctx);
  15018. data_ctx.read_embeddings(ctx);
  15019. data_ctx.read_kv_cache(ctx);
  15020. return data_ctx.get_size_read();
  15021. }
  15022. // Sets the state reading from the specified source address
  15023. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
  15024. llama_data_read_buffer data_ctx(src, size);
  15025. try {
  15026. return llama_state_set_data_internal(ctx, data_ctx);
  15027. } catch (const std::exception & err) {
  15028. LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
  15029. return 0;
  15030. }
  15031. }
  15032. 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) {
  15033. llama_file file(path_session, "rb");
  15034. // sanity checks
  15035. {
  15036. const uint32_t magic = file.read_u32();
  15037. const uint32_t version = file.read_u32();
  15038. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  15039. LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  15040. return false;
  15041. }
  15042. }
  15043. // load the prompt
  15044. {
  15045. const uint32_t n_token_count = file.read_u32();
  15046. if (n_token_count > n_token_capacity) {
  15047. LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15048. return false;
  15049. }
  15050. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15051. *n_token_count_out = n_token_count;
  15052. }
  15053. // restore the context state
  15054. {
  15055. const size_t n_state_size_cur = file.size - file.tell();
  15056. llama_data_read_file data_ctx(&file);
  15057. const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
  15058. if (n_read != n_state_size_cur) {
  15059. 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);
  15060. return false;
  15061. }
  15062. }
  15063. return true;
  15064. }
  15065. 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) {
  15066. try {
  15067. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  15068. } catch (const std::exception & err) {
  15069. LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
  15070. return false;
  15071. }
  15072. }
  15073. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15074. llama_file file(path_session, "wb");
  15075. file.write_u32(LLAMA_SESSION_MAGIC);
  15076. file.write_u32(LLAMA_SESSION_VERSION);
  15077. // save the prompt
  15078. file.write_u32((uint32_t) n_token_count);
  15079. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15080. // save the context state using stream saving
  15081. llama_data_write_file data_ctx(&file);
  15082. llama_state_get_data_internal(ctx, data_ctx);
  15083. return true;
  15084. }
  15085. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  15086. try {
  15087. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  15088. } catch (const std::exception & err) {
  15089. LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
  15090. return false;
  15091. }
  15092. }
  15093. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
  15094. llama_synchronize(ctx);
  15095. data_ctx.write_kv_cache(ctx, seq_id);
  15096. return data_ctx.get_size_written();
  15097. }
  15098. size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
  15099. llama_data_write_dummy data_ctx;
  15100. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15101. }
  15102. size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
  15103. llama_data_write_buffer data_ctx(dst, size);
  15104. try {
  15105. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15106. } catch (const std::exception & err) {
  15107. LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
  15108. return 0;
  15109. }
  15110. }
  15111. static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
  15112. llama_synchronize(ctx);
  15113. data_ctx.read_kv_cache(ctx, dest_seq_id);
  15114. return data_ctx.get_size_read();
  15115. }
  15116. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
  15117. llama_data_read_buffer data_ctx(src, size);
  15118. try {
  15119. return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15120. } catch (const std::exception & err) {
  15121. LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
  15122. return 0;
  15123. }
  15124. }
  15125. 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) {
  15126. llama_file file(filepath, "wb");
  15127. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  15128. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  15129. // save the prompt
  15130. file.write_u32((uint32_t) n_token_count);
  15131. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  15132. // save the context state using stream saving
  15133. llama_data_write_file data_ctx(&file);
  15134. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  15135. const size_t res = file.tell();
  15136. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  15137. return res;
  15138. }
  15139. 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) {
  15140. llama_file file(filepath, "rb");
  15141. // version checks
  15142. {
  15143. const uint32_t magic = file.read_u32();
  15144. const uint32_t version = file.read_u32();
  15145. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  15146. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  15147. return 0;
  15148. }
  15149. }
  15150. // load the prompt
  15151. {
  15152. const uint32_t n_token_count = file.read_u32();
  15153. if (n_token_count > n_token_capacity) {
  15154. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  15155. return 0;
  15156. }
  15157. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  15158. *n_token_count_out = n_token_count;
  15159. }
  15160. // restore the context state
  15161. {
  15162. const size_t state_size = file.size - file.tell();
  15163. llama_data_read_file data_ctx(&file);
  15164. const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
  15165. if (!nread) {
  15166. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  15167. return 0;
  15168. }
  15169. GGML_ASSERT(nread <= state_size);
  15170. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  15171. }
  15172. return file.tell();
  15173. }
  15174. 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) {
  15175. try {
  15176. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  15177. } catch (const std::exception & err) {
  15178. LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
  15179. return 0;
  15180. }
  15181. }
  15182. 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) {
  15183. try {
  15184. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  15185. } catch (const std::exception & err) {
  15186. LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
  15187. return 0;
  15188. }
  15189. }
  15190. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  15191. ctx->cparams.n_threads = n_threads;
  15192. ctx->cparams.n_threads_batch = n_threads_batch;
  15193. }
  15194. uint32_t llama_n_threads(struct llama_context * ctx) {
  15195. return ctx->cparams.n_threads;
  15196. }
  15197. uint32_t llama_n_threads_batch(struct llama_context * ctx) {
  15198. return ctx->cparams.n_threads_batch;
  15199. }
  15200. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  15201. ctx->abort_callback = abort_callback;
  15202. ctx->abort_callback_data = abort_callback_data;
  15203. }
  15204. void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
  15205. ctx->cparams.embeddings = embeddings;
  15206. }
  15207. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  15208. ctx->cparams.causal_attn = causal_attn;
  15209. }
  15210. struct llama_batch llama_batch_get_one(
  15211. llama_token * tokens,
  15212. int32_t n_tokens,
  15213. llama_pos pos_0,
  15214. llama_seq_id seq_id) {
  15215. return {
  15216. /*n_tokens =*/ n_tokens,
  15217. /*tokens =*/ tokens,
  15218. /*embd =*/ nullptr,
  15219. /*pos =*/ nullptr,
  15220. /*n_seq_id =*/ nullptr,
  15221. /*seq_id =*/ nullptr,
  15222. /*logits =*/ nullptr,
  15223. /*all_pos_0 =*/ pos_0,
  15224. /*all_pos_1 =*/ 1,
  15225. /*all_seq_id =*/ seq_id,
  15226. };
  15227. }
  15228. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  15229. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  15230. if (embd) {
  15231. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  15232. } else {
  15233. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  15234. }
  15235. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  15236. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  15237. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  15238. for (int i = 0; i < n_tokens_alloc; ++i) {
  15239. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  15240. }
  15241. batch.seq_id[n_tokens_alloc] = nullptr;
  15242. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  15243. return batch;
  15244. }
  15245. void llama_batch_free(struct llama_batch batch) {
  15246. if (batch.token) free(batch.token);
  15247. if (batch.embd) free(batch.embd);
  15248. if (batch.pos) free(batch.pos);
  15249. if (batch.n_seq_id) free(batch.n_seq_id);
  15250. if (batch.seq_id) {
  15251. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  15252. free(batch.seq_id[i]);
  15253. }
  15254. free(batch.seq_id);
  15255. }
  15256. if (batch.logits) free(batch.logits);
  15257. }
  15258. int32_t llama_encode(
  15259. struct llama_context * ctx,
  15260. struct llama_batch batch) {
  15261. const int ret = llama_encode_internal(*ctx, batch);
  15262. if (ret < 0) {
  15263. LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
  15264. }
  15265. return ret;
  15266. }
  15267. int32_t llama_decode(
  15268. struct llama_context * ctx,
  15269. struct llama_batch batch) {
  15270. const int ret = llama_decode_internal(*ctx, batch);
  15271. if (ret < 0) {
  15272. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  15273. }
  15274. return ret;
  15275. }
  15276. void llama_synchronize(struct llama_context * ctx) {
  15277. ggml_backend_sched_synchronize(ctx->sched);
  15278. // FIXME: if multiple single tokens are evaluated without a synchronization,
  15279. // the stats will be added to the prompt evaluation stats
  15280. // this should only happen when using batch size 1 to evaluate a batch
  15281. // add the evaluation to the stats
  15282. if (ctx->n_queued_tokens == 1) {
  15283. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15284. ctx->n_eval++;
  15285. } else if (ctx->n_queued_tokens > 1) {
  15286. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15287. ctx->n_p_eval += ctx->n_queued_tokens;
  15288. }
  15289. // get a more accurate load time, upon first eval
  15290. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  15291. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  15292. ctx->has_evaluated_once = true;
  15293. }
  15294. ctx->n_queued_tokens = 0;
  15295. ctx->t_compute_start_us = 0;
  15296. }
  15297. float * llama_get_logits(struct llama_context * ctx) {
  15298. llama_synchronize(ctx);
  15299. return ctx->logits;
  15300. }
  15301. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  15302. int32_t j = -1;
  15303. llama_synchronize(ctx);
  15304. try {
  15305. if (ctx->logits == nullptr) {
  15306. throw std::runtime_error("no logits");
  15307. }
  15308. if (i < 0) {
  15309. j = ctx->n_outputs + i;
  15310. if (j < 0) {
  15311. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15312. }
  15313. } else if ((size_t) i >= ctx->output_ids.size()) {
  15314. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15315. } else {
  15316. j = ctx->output_ids[i];
  15317. }
  15318. if (j < 0) {
  15319. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15320. }
  15321. if (j >= ctx->n_outputs) {
  15322. // This should not happen
  15323. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15324. }
  15325. return ctx->logits + j*ctx->model.hparams.n_vocab;
  15326. } catch (const std::exception & err) {
  15327. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  15328. #ifndef NDEBUG
  15329. GGML_ABORT("fatal error");
  15330. #endif
  15331. return nullptr;
  15332. }
  15333. }
  15334. float * llama_get_embeddings(struct llama_context * ctx) {
  15335. llama_synchronize(ctx);
  15336. return ctx->embd;
  15337. }
  15338. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  15339. int32_t j = -1;
  15340. llama_synchronize(ctx);
  15341. try {
  15342. if (ctx->embd == nullptr) {
  15343. throw std::runtime_error("no embeddings");
  15344. }
  15345. if (i < 0) {
  15346. j = ctx->n_outputs + i;
  15347. if (j < 0) {
  15348. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15349. }
  15350. } else if ((size_t) i >= ctx->output_ids.size()) {
  15351. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15352. } else {
  15353. j = ctx->output_ids[i];
  15354. }
  15355. if (j < 0) {
  15356. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15357. }
  15358. if (j >= ctx->n_outputs) {
  15359. // This should not happen
  15360. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15361. }
  15362. return ctx->embd + j*ctx->model.hparams.n_embd;
  15363. } catch (const std::exception & err) {
  15364. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  15365. #ifndef NDEBUG
  15366. GGML_ABORT("fatal error");
  15367. #endif
  15368. return nullptr;
  15369. }
  15370. }
  15371. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  15372. llama_synchronize(ctx);
  15373. auto it = ctx->embd_seq.find(seq_id);
  15374. if (it == ctx->embd_seq.end()) {
  15375. return nullptr;
  15376. }
  15377. return it->second.data();
  15378. }
  15379. //
  15380. // vocab
  15381. //
  15382. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  15383. return llama_token_get_text_impl(model->vocab, token);
  15384. }
  15385. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  15386. return llama_token_get_score_impl(model->vocab, token);
  15387. }
  15388. enum llama_token_attr llama_token_get_attr(const struct llama_model * model, llama_token token) {
  15389. return llama_token_get_attr_impl(model->vocab, token);
  15390. }
  15391. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  15392. return llama_token_is_eog_impl(model->vocab, token);
  15393. }
  15394. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  15395. return llama_token_is_control_impl(model->vocab, token);
  15396. }
  15397. llama_token llama_token_bos(const struct llama_model * model) {
  15398. return llama_token_bos_impl(model->vocab);
  15399. }
  15400. llama_token llama_token_eos(const struct llama_model * model) {
  15401. return llama_token_eos_impl(model->vocab);
  15402. }
  15403. llama_token llama_token_cls(const struct llama_model * model) {
  15404. return llama_token_cls_impl(model->vocab);
  15405. }
  15406. llama_token llama_token_sep(const struct llama_model * model) {
  15407. return llama_token_sep_impl(model->vocab);
  15408. }
  15409. llama_token llama_token_nl (const struct llama_model * model) {
  15410. return llama_token_nl_impl(model->vocab);
  15411. }
  15412. llama_token llama_token_pad(const struct llama_model * model) {
  15413. return llama_token_pad_impl(model->vocab);
  15414. }
  15415. int32_t llama_add_bos_token(const struct llama_model * model) {
  15416. return llama_add_bos_token_impl(model->vocab);
  15417. }
  15418. int32_t llama_add_eos_token(const struct llama_model * model) {
  15419. return llama_add_eos_token_impl(model->vocab);
  15420. }
  15421. llama_token llama_token_prefix(const struct llama_model * model) {
  15422. return llama_token_prefix_impl(model->vocab);
  15423. }
  15424. llama_token llama_token_middle(const struct llama_model * model) {
  15425. return llama_token_middle_impl(model->vocab);
  15426. }
  15427. llama_token llama_token_suffix(const struct llama_model * model) {
  15428. return llama_token_suffix_impl(model->vocab);
  15429. }
  15430. llama_token llama_token_eot(const struct llama_model * model) {
  15431. return llama_token_eot_impl(model->vocab);
  15432. }
  15433. //
  15434. // tokenization
  15435. //
  15436. int32_t llama_tokenize(
  15437. const struct llama_model * model,
  15438. const char * text,
  15439. int32_t text_len,
  15440. llama_token * tokens,
  15441. int32_t n_tokens_max,
  15442. bool add_special,
  15443. bool parse_special) {
  15444. return llama_tokenize_impl(model->vocab, text, text_len, tokens, n_tokens_max, add_special, parse_special);
  15445. }
  15446. int32_t llama_token_to_piece(
  15447. const struct llama_model * model,
  15448. llama_token token,
  15449. char * buf,
  15450. int32_t length,
  15451. int32_t lstrip,
  15452. bool special) {
  15453. return llama_token_to_piece_impl(model->vocab, token, buf, length, lstrip, special);
  15454. }
  15455. int32_t llama_detokenize(
  15456. const struct llama_model * model,
  15457. const llama_token * tokens,
  15458. int32_t n_tokens,
  15459. char * text,
  15460. int32_t text_len_max,
  15461. bool remove_special,
  15462. bool unparse_special) {
  15463. return llama_detokenize_impl(model->vocab, tokens, n_tokens, text, text_len_max, remove_special, unparse_special);
  15464. }
  15465. //
  15466. // chat templates
  15467. //
  15468. // Simple version of "llama_apply_chat_template" that only works with strings
  15469. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  15470. static int32_t llama_chat_apply_template_internal(
  15471. const std::string & tmpl,
  15472. const std::vector<const llama_chat_message *> & chat,
  15473. std::string & dest, bool add_ass) {
  15474. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  15475. std::stringstream ss;
  15476. auto tmpl_contains = [&tmpl](std::string haystack) -> bool {
  15477. return tmpl.find(haystack) != std::string::npos;
  15478. };
  15479. if (tmpl == "chatml" || tmpl_contains("<|im_start|>")) {
  15480. // chatml template
  15481. for (auto message : chat) {
  15482. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  15483. }
  15484. if (add_ass) {
  15485. ss << "<|im_start|>assistant\n";
  15486. }
  15487. } else if (tmpl == "llama2" || tmpl == "mistral" || tmpl_contains("[INST]")) {
  15488. // llama2 template and its variants
  15489. // [variant] support system message
  15490. bool support_system_message = tmpl_contains("<<SYS>>") || tmpl == "mistral";
  15491. // [variant] space before + after response
  15492. bool space_around_response = tmpl_contains("' ' + eos_token");
  15493. // [variant] add BOS inside history
  15494. bool add_bos_inside_history = tmpl_contains("bos_token + '[INST]");
  15495. // [variant] trim spaces from the input message
  15496. bool strip_message = tmpl_contains("content.strip()");
  15497. // construct the prompt
  15498. bool is_inside_turn = true; // skip BOS at the beginning
  15499. ss << "[INST] ";
  15500. for (auto message : chat) {
  15501. std::string content = strip_message ? trim(message->content) : message->content;
  15502. std::string role(message->role);
  15503. if (!is_inside_turn) {
  15504. is_inside_turn = true;
  15505. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  15506. }
  15507. if (role == "system") {
  15508. if (support_system_message) {
  15509. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  15510. } else {
  15511. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  15512. ss << content << "\n";
  15513. }
  15514. } else if (role == "user") {
  15515. ss << content << " [/INST]";
  15516. } else {
  15517. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  15518. is_inside_turn = false;
  15519. }
  15520. }
  15521. // llama2 templates seem to not care about "add_generation_prompt"
  15522. } else if (tmpl == "phi3" || (tmpl_contains("<|assistant|>") && tmpl_contains("<|end|>"))) {
  15523. // Phi 3
  15524. for (auto message : chat) {
  15525. std::string role(message->role);
  15526. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  15527. }
  15528. if (add_ass) {
  15529. ss << "<|assistant|>\n";
  15530. }
  15531. } else if (tmpl == "zephyr" || tmpl_contains("<|user|>")) {
  15532. // zephyr template
  15533. for (auto message : chat) {
  15534. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  15535. }
  15536. if (add_ass) {
  15537. ss << "<|assistant|>\n";
  15538. }
  15539. } else if (tmpl == "monarch" || tmpl_contains("bos_token + message['role']")) {
  15540. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  15541. for (auto message : chat) {
  15542. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  15543. ss << bos << message->role << "\n" << message->content << "</s>\n";
  15544. }
  15545. if (add_ass) {
  15546. ss << "<s>assistant\n";
  15547. }
  15548. } else if (tmpl == "gemma" || tmpl == "gemma2" || tmpl_contains("<start_of_turn>")) {
  15549. // google/gemma-7b-it
  15550. std::string system_prompt = "";
  15551. for (auto message : chat) {
  15552. std::string role(message->role);
  15553. if (role == "system") {
  15554. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  15555. system_prompt = trim(message->content);
  15556. continue;
  15557. }
  15558. // in gemma, "assistant" is "model"
  15559. role = role == "assistant" ? "model" : message->role;
  15560. ss << "<start_of_turn>" << role << "\n";
  15561. if (!system_prompt.empty() && role != "model") {
  15562. ss << system_prompt << "\n\n";
  15563. system_prompt = "";
  15564. }
  15565. ss << trim(message->content) << "<end_of_turn>\n";
  15566. }
  15567. if (add_ass) {
  15568. ss << "<start_of_turn>model\n";
  15569. }
  15570. } else if (tmpl == "orion" || tmpl_contains("'\\n\\nAssistant: ' + eos_token")) {
  15571. // OrionStarAI/Orion-14B-Chat
  15572. std::string system_prompt = "";
  15573. for (auto message : chat) {
  15574. std::string role(message->role);
  15575. if (role == "system") {
  15576. // there is no system message support, we will merge it with user prompt
  15577. system_prompt = message->content;
  15578. continue;
  15579. } else if (role == "user") {
  15580. ss << "Human: ";
  15581. if (!system_prompt.empty()) {
  15582. ss << system_prompt << "\n\n";
  15583. system_prompt = "";
  15584. }
  15585. ss << message->content << "\n\nAssistant: </s>";
  15586. } else {
  15587. ss << message->content << "</s>";
  15588. }
  15589. }
  15590. } else if (tmpl == "openchat" || tmpl_contains("GPT4 Correct ")) {
  15591. // openchat/openchat-3.5-0106,
  15592. for (auto message : chat) {
  15593. std::string role(message->role);
  15594. if (role == "system") {
  15595. ss << message->content << "<|end_of_turn|>";
  15596. } else {
  15597. role[0] = toupper(role[0]);
  15598. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  15599. }
  15600. }
  15601. if (add_ass) {
  15602. ss << "GPT4 Correct Assistant:";
  15603. }
  15604. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl_contains("USER: ") && tmpl_contains("ASSISTANT: "))) {
  15605. // eachadea/vicuna-13b-1.1 (and Orca variant)
  15606. for (auto message : chat) {
  15607. std::string role(message->role);
  15608. if (role == "system") {
  15609. // Orca-Vicuna variant uses a system prefix
  15610. if (tmpl == "vicuna-orca" || tmpl_contains("SYSTEM: ")) {
  15611. ss << "SYSTEM: " << message->content << "\n";
  15612. } else {
  15613. ss << message->content << "\n\n";
  15614. }
  15615. } else if (role == "user") {
  15616. ss << "USER: " << message->content << "\n";
  15617. } else if (role == "assistant") {
  15618. ss << "ASSISTANT: " << message->content << "</s>\n";
  15619. }
  15620. }
  15621. if (add_ass) {
  15622. ss << "ASSISTANT:";
  15623. }
  15624. } else if (tmpl == "deepseek" || (tmpl_contains("### Instruction:") && tmpl_contains("<|EOT|>"))) {
  15625. // deepseek-ai/deepseek-coder-33b-instruct
  15626. for (auto message : chat) {
  15627. std::string role(message->role);
  15628. if (role == "system") {
  15629. ss << message->content;
  15630. } else if (role == "user") {
  15631. ss << "### Instruction:\n" << message->content << "\n";
  15632. } else if (role == "assistant") {
  15633. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  15634. }
  15635. }
  15636. if (add_ass) {
  15637. ss << "### Response:\n";
  15638. }
  15639. } else if (tmpl == "command-r" || (tmpl_contains("<|START_OF_TURN_TOKEN|>") && tmpl_contains("<|USER_TOKEN|>"))) {
  15640. // CohereForAI/c4ai-command-r-plus
  15641. for (auto message : chat) {
  15642. std::string role(message->role);
  15643. if (role == "system") {
  15644. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15645. } else if (role == "user") {
  15646. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15647. } else if (role == "assistant") {
  15648. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15649. }
  15650. }
  15651. if (add_ass) {
  15652. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  15653. }
  15654. } else if (tmpl == "llama3" || (tmpl_contains("<|start_header_id|>") && tmpl_contains("<|end_header_id|>"))) {
  15655. // Llama 3
  15656. for (auto message : chat) {
  15657. std::string role(message->role);
  15658. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  15659. }
  15660. if (add_ass) {
  15661. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  15662. }
  15663. } else if (tmpl == "chatglm3" || tmpl_contains("[gMASK]sop")) {
  15664. // chatglm3-6b
  15665. ss << "[gMASK]" << "sop";
  15666. for (auto message : chat) {
  15667. std::string role(message->role);
  15668. ss << "<|" << role << "|>" << "\n " << message->content;
  15669. }
  15670. if (add_ass) {
  15671. ss << "<|assistant|>";
  15672. }
  15673. } else if (tmpl == "chatglm4" || tmpl_contains("[gMASK]<sop>")) {
  15674. ss << "[gMASK]" << "<sop>";
  15675. for (auto message : chat) {
  15676. std::string role(message->role);
  15677. ss << "<|" << role << "|>" << "\n" << message->content;
  15678. }
  15679. if (add_ass) {
  15680. ss << "<|assistant|>";
  15681. }
  15682. } else if (tmpl == "minicpm" || tmpl_contains(LU8("<用户>"))) {
  15683. // MiniCPM-3B-OpenHermes-2.5-v2-GGUF
  15684. for (auto message : chat) {
  15685. std::string role(message->role);
  15686. if (role == "user") {
  15687. ss << LU8("<用户>");
  15688. ss << trim(message->content);
  15689. ss << "<AI>";
  15690. } else {
  15691. ss << trim(message->content);
  15692. }
  15693. }
  15694. } else if (tmpl == "deepseek2" || tmpl_contains("'Assistant: ' + message['content'] + eos_token")) {
  15695. // DeepSeek-V2
  15696. for (auto message : chat) {
  15697. std::string role(message->role);
  15698. if (role == "system") {
  15699. ss << message->content << "\n\n";
  15700. } else if (role == "user") {
  15701. ss << "User: " << message->content << "\n\n";
  15702. } else if (role == "assistant") {
  15703. ss << "Assistant: " << message->content << LU8("<|end▁of▁sentence|>");
  15704. }
  15705. }
  15706. if (add_ass) {
  15707. ss << "Assistant:";
  15708. }
  15709. } else {
  15710. // template not supported
  15711. return -1;
  15712. }
  15713. dest = ss.str();
  15714. return dest.size();
  15715. }
  15716. int32_t llama_chat_apply_template(
  15717. const struct llama_model * model,
  15718. const char * tmpl,
  15719. const struct llama_chat_message * chat,
  15720. size_t n_msg,
  15721. bool add_ass,
  15722. char * buf,
  15723. int32_t length) {
  15724. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  15725. if (tmpl == nullptr) {
  15726. GGML_ASSERT(model != nullptr);
  15727. // load template from model
  15728. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  15729. std::string template_key = "tokenizer.chat_template";
  15730. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  15731. if (res < 0) {
  15732. // worst case: there is no information about template, we will use chatml by default
  15733. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  15734. } else {
  15735. curr_tmpl = std::string(model_template.data(), model_template.size());
  15736. }
  15737. }
  15738. // format the chat to string
  15739. std::vector<const llama_chat_message *> chat_vec;
  15740. chat_vec.resize(n_msg);
  15741. for (size_t i = 0; i < n_msg; i++) {
  15742. chat_vec[i] = &chat[i];
  15743. }
  15744. std::string formatted_chat;
  15745. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  15746. if (res < 0) {
  15747. return res;
  15748. }
  15749. if (buf && length > 0) {
  15750. strncpy(buf, formatted_chat.c_str(), length);
  15751. }
  15752. return res;
  15753. }
  15754. //
  15755. // grammar
  15756. //
  15757. struct llama_grammar * llama_grammar_init(
  15758. const llama_grammar_element ** rules,
  15759. size_t n_rules,
  15760. size_t start_rule_index) {
  15761. return llama_grammar_init_impl(rules, n_rules, start_rule_index);
  15762. }
  15763. void llama_grammar_free(struct llama_grammar * grammar) {
  15764. llama_grammar_free_impl(grammar);
  15765. }
  15766. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  15767. return llama_grammar_copy_impl(grammar);
  15768. }
  15769. void llama_grammar_sample(
  15770. const struct llama_grammar * grammar,
  15771. const struct llama_context * ctx,
  15772. llama_token_data_array * candidates) {
  15773. llama_grammar_sample_impl(grammar, &ctx->model.vocab, &ctx->sampling, candidates);
  15774. }
  15775. void llama_sample_grammar(
  15776. struct llama_context * ctx,
  15777. llama_token_data_array * candidates,
  15778. const struct llama_grammar * grammar) {
  15779. llama_grammar_sample(grammar, ctx, candidates);
  15780. }
  15781. void llama_grammar_accept_token(
  15782. struct llama_grammar * grammar,
  15783. struct llama_context * ctx,
  15784. llama_token token) {
  15785. llama_grammar_accept_token_impl(grammar, &ctx->model.vocab, &ctx->sampling, token);
  15786. }
  15787. //
  15788. // sampling
  15789. //
  15790. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  15791. llama_set_rng_seed_impl(&ctx->sampling, seed);
  15792. }
  15793. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  15794. llama_sample_softmax_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15795. }
  15796. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  15797. llama_sample_top_k_impl(ctx ? &ctx->sampling : nullptr, candidates, k, min_keep);
  15798. }
  15799. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15800. llama_sample_top_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15801. }
  15802. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15803. llama_sample_min_p_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15804. }
  15805. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  15806. llama_sample_tail_free_impl(ctx ? &ctx->sampling : nullptr, candidates, z, min_keep);
  15807. }
  15808. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  15809. llama_sample_typical_impl(ctx ? &ctx->sampling : nullptr, candidates, p, min_keep);
  15810. }
  15811. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  15812. llama_sample_entropy_impl(ctx ? &ctx->sampling : nullptr, candidates_p, min_temp, max_temp, exponent_val);
  15813. }
  15814. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  15815. llama_sample_temp_impl(ctx ? &ctx->sampling : nullptr, candidates_p, temp);
  15816. }
  15817. void llama_sample_repetition_penalties(
  15818. struct llama_context * ctx,
  15819. llama_token_data_array * candidates,
  15820. const llama_token * last_tokens,
  15821. size_t penalty_last_n,
  15822. float penalty_repeat,
  15823. float penalty_freq,
  15824. float penalty_present) {
  15825. llama_sample_repetition_penalties_impl(ctx ? &ctx->sampling : nullptr, candidates, last_tokens, penalty_last_n, penalty_repeat, penalty_freq, penalty_present);
  15826. }
  15827. void llama_sample_apply_guidance(
  15828. struct llama_context * ctx,
  15829. float * logits,
  15830. float * logits_guidance,
  15831. float scale) {
  15832. llama_sample_apply_guidance_impl(&ctx->sampling, logits, logits_guidance, scale);
  15833. }
  15834. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  15835. return llama_sample_token_mirostat_impl(&ctx->sampling, candidates, tau, eta, m, mu);
  15836. }
  15837. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  15838. return llama_sample_token_mirostat_v2_impl(ctx ? &ctx->sampling : nullptr, candidates, tau, eta, mu);
  15839. }
  15840. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  15841. return llama_sample_token_greedy_impl(ctx ? &ctx->sampling : nullptr, candidates);
  15842. }
  15843. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  15844. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, rng);
  15845. }
  15846. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  15847. return llama_sample_token_with_rng_impl(&ctx->sampling, candidates, ctx->sampling.rng);
  15848. }
  15849. int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  15850. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  15851. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  15852. return strlen(split_path);
  15853. }
  15854. return 0;
  15855. }
  15856. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  15857. std::string str_split_path(split_path);
  15858. char postfix[32];
  15859. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  15860. std::string str_postfix(postfix);
  15861. // check if dest ends with postfix
  15862. int size_prefix = str_split_path.size() - str_postfix.size();
  15863. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  15864. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  15865. return size_prefix;
  15866. }
  15867. return 0;
  15868. }
  15869. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  15870. struct llama_timings result = {
  15871. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  15872. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  15873. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  15874. /*.t_sample_ms =*/ 1e-3 * ctx->sampling.t_sample_us,
  15875. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  15876. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  15877. /*.n_sample =*/ std::max(1, ctx->sampling.n_sample),
  15878. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  15879. /*.n_eval =*/ std::max(1, ctx->n_eval),
  15880. };
  15881. return result;
  15882. }
  15883. void llama_print_timings(struct llama_context * ctx) {
  15884. const llama_timings timings = llama_get_timings(ctx);
  15885. LLAMA_LOG_INFO("\n");
  15886. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  15887. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15888. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  15889. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  15890. __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);
  15891. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15892. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  15893. 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));
  15894. }
  15895. void llama_reset_timings(struct llama_context * ctx) {
  15896. ctx->t_start_us = ggml_time_us();
  15897. ctx->t_eval_us = ctx->n_eval = 0;
  15898. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  15899. ctx->sampling.reset_timings();
  15900. }
  15901. const char * llama_print_system_info(void) {
  15902. static std::string s;
  15903. s = "";
  15904. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  15905. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  15906. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  15907. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  15908. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  15909. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  15910. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  15911. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  15912. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  15913. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  15914. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  15915. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  15916. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  15917. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  15918. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  15919. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  15920. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  15921. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  15922. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  15923. s += "LLAMAFILE = " + std::to_string(ggml_cpu_has_llamafile()) + " | ";
  15924. return s.c_str();
  15925. }
  15926. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  15927. fprintf(stream, "\n");
  15928. fprintf(stream, "###########\n");
  15929. fprintf(stream, "# Timings #\n");
  15930. fprintf(stream, "###########\n");
  15931. fprintf(stream, "\n");
  15932. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  15933. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  15934. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  15935. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  15936. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  15937. 1.0e-3 * ctx->sampling.t_sample_us / ctx->sampling.n_sample);
  15938. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  15939. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  15940. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->sampling.n_sample);
  15941. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  15942. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  15943. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  15944. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->sampling.t_sample_us);
  15945. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  15946. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  15947. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  15948. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  15949. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  15950. 1.0e6 * ctx->sampling.n_sample / ctx->sampling.t_sample_us);
  15951. }
  15952. // For internal test use
  15953. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  15954. struct llama_context * ctx
  15955. ) {
  15956. return ctx->model.tensors_by_name;
  15957. }
  15958. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  15959. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  15960. g_state.log_callback_user_data = user_data;
  15961. #ifdef GGML_USE_METAL
  15962. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15963. #elif defined(GGML_USE_CUDA)
  15964. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15965. #elif defined(GGML_USE_CANN)
  15966. ggml_backend_cann_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15967. #endif
  15968. }
  15969. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  15970. va_list args_copy;
  15971. va_copy(args_copy, args);
  15972. char buffer[128];
  15973. int len = vsnprintf(buffer, 128, format, args);
  15974. if (len < 128) {
  15975. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  15976. } else {
  15977. char* buffer2 = new char[len+1];
  15978. vsnprintf(buffer2, len+1, format, args_copy);
  15979. buffer2[len] = 0;
  15980. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  15981. delete[] buffer2;
  15982. }
  15983. va_end(args_copy);
  15984. }
  15985. void llama_log_internal(ggml_log_level level, const char * format, ...) {
  15986. va_list args;
  15987. va_start(args, format);
  15988. llama_log_internal_v(level, format, args);
  15989. va_end(args);
  15990. }
  15991. void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  15992. (void) level;
  15993. (void) user_data;
  15994. fputs(text, stderr);
  15995. fflush(stderr);
  15996. }
  15997. static int llama_apply_lora_from_file_internal(
  15998. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  15999. ) {
  16000. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  16001. const int64_t t_start_lora_us = ggml_time_us();
  16002. llama_file fin(path_lora, "rb");
  16003. // verify magic and version
  16004. {
  16005. uint32_t magic = fin.read_u32();
  16006. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  16007. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  16008. return 1;
  16009. }
  16010. uint32_t format_version = fin.read_u32();
  16011. if (format_version != 1) {
  16012. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  16013. return 1;
  16014. }
  16015. }
  16016. int32_t lora_r = fin.read_u32();
  16017. int32_t lora_alpha = fin.read_u32();
  16018. float scaling = scale * (float)lora_alpha / (float)lora_r;
  16019. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  16020. // load base model
  16021. std::unique_ptr<llama_model_loader> ml;
  16022. if (path_base_model) {
  16023. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  16024. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*check_tensors*/ false, /*kv_overrides*/ nullptr));
  16025. ml->init_mappings(/*prefetch*/ false); // no prefetching
  16026. }
  16027. struct tensor_meta {
  16028. std::string name;
  16029. ggml_type type;
  16030. int32_t ne[2];
  16031. size_t offset;
  16032. };
  16033. std::map<std::string, tensor_meta> tensor_meta_map;
  16034. // load all tensor meta
  16035. while (true) {
  16036. if (fin.tell() == fin.size) {
  16037. // eof
  16038. break;
  16039. }
  16040. int32_t n_dims;
  16041. int32_t name_len;
  16042. int32_t ftype;
  16043. fin.read_raw(&n_dims, sizeof(n_dims));
  16044. fin.read_raw(&name_len, sizeof(name_len));
  16045. fin.read_raw(&ftype, sizeof(ftype));
  16046. if (n_dims != 1 && n_dims != 2) {
  16047. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  16048. return 1;
  16049. }
  16050. int32_t ne[2] = { 1, 1 };
  16051. for (int i = 0; i < n_dims; ++i) {
  16052. fin.read_raw(&ne[i], sizeof(ne[i]));
  16053. }
  16054. std::string name;
  16055. {
  16056. GGML_ASSERT(name_len < GGML_MAX_NAME);
  16057. char buf[GGML_MAX_NAME];
  16058. fin.read_raw(buf, name_len);
  16059. name = std::string(buf, name_len);
  16060. }
  16061. // check for lora suffix
  16062. std::string lora_suffix;
  16063. if (name.length() > 6) {
  16064. lora_suffix = name.substr(name.length() - 6);
  16065. }
  16066. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  16067. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  16068. return 1;
  16069. }
  16070. // tensor type
  16071. ggml_type wtype;
  16072. switch (ftype) {
  16073. case 0: wtype = GGML_TYPE_F32; break;
  16074. case 1: wtype = GGML_TYPE_F16; break;
  16075. default:
  16076. {
  16077. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  16078. __func__, ftype);
  16079. return 1;
  16080. }
  16081. }
  16082. // data offset
  16083. size_t offset = fin.tell();
  16084. offset = (offset + 31) & -32;
  16085. // skip tensor data
  16086. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  16087. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  16088. }
  16089. bool warned = false;
  16090. int n_tensors = 0;
  16091. // apply
  16092. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  16093. if (backend_cpu == nullptr) {
  16094. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  16095. return 1;
  16096. }
  16097. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  16098. std::vector<no_init<uint8_t>> read_buf;
  16099. for (const auto & it : model.tensors_by_name) {
  16100. const std::string & base_name = it.first;
  16101. ggml_tensor * model_t = it.second;
  16102. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  16103. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  16104. continue;
  16105. }
  16106. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  16107. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  16108. ggml_init_params lora_init_params = {
  16109. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  16110. /* .mem_buffer */ nullptr,
  16111. /* .no_alloc */ true,
  16112. };
  16113. ggml_context * lora_ctx = ggml_init(lora_init_params);
  16114. if (lora_ctx == nullptr) {
  16115. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  16116. ggml_backend_free(backend_cpu);
  16117. return 1;
  16118. }
  16119. // create tensors
  16120. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  16121. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  16122. ggml_set_name(loraA, metaA.name.c_str());
  16123. ggml_set_name(loraB, metaB.name.c_str());
  16124. ggml_tensor * base_t;
  16125. if (ml) {
  16126. if (!ml->get_tensor_meta(base_name.c_str())) {
  16127. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  16128. return 1;
  16129. }
  16130. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  16131. } else {
  16132. base_t = ggml_dup_tensor(lora_ctx, model_t);
  16133. }
  16134. ggml_set_name(base_t, base_name.c_str());
  16135. // allocate in backend buffer
  16136. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  16137. if (lora_buf == nullptr) {
  16138. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  16139. return 1;
  16140. }
  16141. // load tensor data
  16142. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  16143. read_buf.resize(ggml_nbytes(tensor));
  16144. fin.seek(tensor_meta.offset, SEEK_SET);
  16145. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  16146. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  16147. };
  16148. load_tensor(metaA, loraA);
  16149. load_tensor(metaB, loraB);
  16150. // load base model tensor data
  16151. if (ml) {
  16152. ml->load_data_for(base_t);
  16153. } else {
  16154. ggml_backend_tensor_copy(model_t, base_t);
  16155. }
  16156. if (ggml_is_quantized(base_t->type) && !warned) {
  16157. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  16158. "use a f16 or f32 base model with --lora-base\n", __func__);
  16159. warned = true;
  16160. }
  16161. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  16162. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  16163. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  16164. ggml_free(lora_ctx);
  16165. ggml_backend_buffer_free(lora_buf);
  16166. ggml_backend_free(backend_cpu);
  16167. return 1;
  16168. }
  16169. auto build_lora_graph = [&]() {
  16170. // w = w + BA*s
  16171. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  16172. ggml_set_name(BA, "BA");
  16173. if (scaling != 1.0f) {
  16174. BA = ggml_scale(lora_ctx, BA, scaling);
  16175. ggml_set_name(BA, "BA_scaled");
  16176. }
  16177. ggml_tensor * r;
  16178. r = ggml_add_inplace(lora_ctx, base_t, BA);
  16179. ggml_set_name(r, "r_add");
  16180. if (base_t->type != model_t->type) {
  16181. // convert the result to the model type
  16182. r = ggml_cast(lora_ctx, r, model_t->type);
  16183. ggml_set_name(r, "r_cast");
  16184. }
  16185. return r;
  16186. };
  16187. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  16188. ggml_tensor * r = build_lora_graph();
  16189. ggml_build_forward_expand(gf, r);
  16190. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  16191. if (graph_buf == nullptr) {
  16192. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  16193. ggml_free(lora_ctx);
  16194. ggml_backend_buffer_free(lora_buf);
  16195. ggml_backend_free(backend_cpu);
  16196. return 1;
  16197. }
  16198. ggml_backend_graph_compute(backend_cpu, gf);
  16199. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  16200. #if 0
  16201. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  16202. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  16203. // sched compute
  16204. ggml_build_forward_expand(gf, build_graph());
  16205. ggml_backend_sched_init_measure(sched, gf);
  16206. // create the graph again, since the previous one was destroyed by the measure
  16207. ggml_graph_clear(gf);
  16208. ggml_build_forward_expand(gf, build_graph());
  16209. ggml_backend_sched_graph_compute(sched, gf);
  16210. ggml_backend_sched_free(sched);
  16211. #endif
  16212. ggml_backend_buffer_free(lora_buf);
  16213. ggml_backend_buffer_free(graph_buf);
  16214. ggml_free(lora_ctx);
  16215. n_tensors++;
  16216. if (n_tensors % 4 == 0) {
  16217. LLAMA_LOG_INFO(".");
  16218. }
  16219. }
  16220. ggml_backend_free(backend_cpu);
  16221. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  16222. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  16223. return 0;
  16224. }
  16225. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  16226. try {
  16227. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  16228. } catch (const std::exception & err) {
  16229. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  16230. return 1;
  16231. }
  16232. }