llama.cpp 762 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_RPC
  8. # include "ggml-rpc.h"
  9. #endif
  10. #ifdef GGML_USE_CUDA
  11. # include "ggml-cuda.h"
  12. #elif defined(GGML_USE_CLBLAST)
  13. # include "ggml-opencl.h"
  14. #elif defined(GGML_USE_VULKAN)
  15. # include "ggml-vulkan.h"
  16. #elif defined(GGML_USE_SYCL)
  17. # include "ggml-sycl.h"
  18. #elif defined(GGML_USE_KOMPUTE)
  19. # include "ggml-kompute.h"
  20. #endif
  21. #ifdef GGML_USE_METAL
  22. # include "ggml-metal.h"
  23. #endif
  24. // TODO: replace with ggml API call
  25. #define QK_K 256
  26. #ifdef __has_include
  27. #if __has_include(<unistd.h>)
  28. #include <unistd.h>
  29. #if defined(_POSIX_MAPPED_FILES)
  30. #include <sys/mman.h>
  31. #include <fcntl.h>
  32. #endif
  33. #if defined(_POSIX_MEMLOCK_RANGE)
  34. #include <sys/resource.h>
  35. #endif
  36. #endif
  37. #endif
  38. #if defined(_WIN32)
  39. #define WIN32_LEAN_AND_MEAN
  40. #ifndef NOMINMAX
  41. #define NOMINMAX
  42. #endif
  43. #include <windows.h>
  44. #ifndef PATH_MAX
  45. #define PATH_MAX MAX_PATH
  46. #endif
  47. #include <io.h>
  48. #endif
  49. #include <algorithm>
  50. #include <array>
  51. #include <cassert>
  52. #include <cctype>
  53. #include <cfloat>
  54. #include <cinttypes>
  55. #include <climits>
  56. #include <cmath>
  57. #include <cstdarg>
  58. #include <cstddef>
  59. #include <cstdint>
  60. #include <cstdio>
  61. #include <cstring>
  62. #include <ctime>
  63. #include <forward_list>
  64. #include <fstream>
  65. #include <functional>
  66. #include <future>
  67. #include <initializer_list>
  68. #include <locale>
  69. #include <map>
  70. #include <memory>
  71. #include <mutex>
  72. #include <numeric>
  73. #include <queue>
  74. #include <random>
  75. #include <regex>
  76. #include <set>
  77. #include <sstream>
  78. #include <thread>
  79. #include <type_traits>
  80. #include <unordered_map>
  81. #if defined(_MSC_VER)
  82. #pragma warning(disable: 4244 4267) // possible loss of data
  83. #endif
  84. #ifdef __GNUC__
  85. #ifdef __MINGW32__
  86. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  87. #else
  88. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  89. #endif
  90. #else
  91. #define LLAMA_ATTRIBUTE_FORMAT(...)
  92. #endif
  93. #define LLAMA_MAX_NODES 8192
  94. #define LLAMA_MAX_EXPERTS 160
  95. //
  96. // logging
  97. //
  98. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  99. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  100. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  101. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  102. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  103. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  104. //
  105. // helpers
  106. //
  107. static size_t utf8_len(char src) {
  108. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  109. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  110. return lookup[highbits];
  111. }
  112. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  113. std::string result;
  114. for (size_t pos = 0; ; pos += search.length()) {
  115. auto new_pos = s.find(search, pos);
  116. if (new_pos == std::string::npos) {
  117. result += s.substr(pos, s.size() - pos);
  118. break;
  119. }
  120. result += s.substr(pos, new_pos - pos) + replace;
  121. pos = new_pos;
  122. }
  123. s = std::move(result);
  124. }
  125. static bool is_float_close(float a, float b, float abs_tol) {
  126. // Check for non-negative tolerance
  127. if (abs_tol < 0.0) {
  128. throw std::invalid_argument("Tolerance must be non-negative");
  129. }
  130. // Exact equality check
  131. if (a == b) {
  132. return true;
  133. }
  134. // Check for infinities
  135. if (std::isinf(a) || std::isinf(b)) {
  136. return false;
  137. }
  138. // Regular comparison using the provided absolute tolerance
  139. return std::fabs(b - a) <= abs_tol;
  140. }
  141. static void zeros(std::ofstream & file, size_t n) {
  142. char zero = 0;
  143. for (size_t i = 0; i < n; ++i) {
  144. file.write(&zero, 1);
  145. }
  146. }
  147. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  148. static std::string format(const char * fmt, ...) {
  149. va_list ap;
  150. va_list ap2;
  151. va_start(ap, fmt);
  152. va_copy(ap2, ap);
  153. int size = vsnprintf(NULL, 0, fmt, ap);
  154. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  155. std::vector<char> buf(size + 1);
  156. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  157. GGML_ASSERT(size2 == size);
  158. va_end(ap2);
  159. va_end(ap);
  160. return std::string(buf.data(), size);
  161. }
  162. //
  163. // gguf constants (sync with gguf.py)
  164. //
  165. enum llm_arch {
  166. LLM_ARCH_LLAMA,
  167. LLM_ARCH_FALCON,
  168. LLM_ARCH_BAICHUAN,
  169. LLM_ARCH_GROK,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_REFACT,
  176. LLM_ARCH_BERT,
  177. LLM_ARCH_NOMIC_BERT,
  178. LLM_ARCH_JINA_BERT_V2,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_QWEN2MOE,
  184. LLM_ARCH_PHI2,
  185. LLM_ARCH_PHI3,
  186. LLM_ARCH_PLAMO,
  187. LLM_ARCH_CODESHELL,
  188. LLM_ARCH_ORION,
  189. LLM_ARCH_INTERNLM2,
  190. LLM_ARCH_MINICPM,
  191. LLM_ARCH_GEMMA,
  192. LLM_ARCH_STARCODER2,
  193. LLM_ARCH_MAMBA,
  194. LLM_ARCH_XVERSE,
  195. LLM_ARCH_COMMAND_R,
  196. LLM_ARCH_DBRX,
  197. LLM_ARCH_OLMO,
  198. LLM_ARCH_ARCTIC,
  199. LLM_ARCH_DEEPSEEK2,
  200. LLM_ARCH_UNKNOWN,
  201. };
  202. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  203. { LLM_ARCH_LLAMA, "llama" },
  204. { LLM_ARCH_FALCON, "falcon" },
  205. { LLM_ARCH_GROK, "grok" },
  206. { LLM_ARCH_GPT2, "gpt2" },
  207. { LLM_ARCH_GPTJ, "gptj" },
  208. { LLM_ARCH_GPTNEOX, "gptneox" },
  209. { LLM_ARCH_MPT, "mpt" },
  210. { LLM_ARCH_BAICHUAN, "baichuan" },
  211. { LLM_ARCH_STARCODER, "starcoder" },
  212. { LLM_ARCH_REFACT, "refact" },
  213. { LLM_ARCH_BERT, "bert" },
  214. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  215. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  216. { LLM_ARCH_BLOOM, "bloom" },
  217. { LLM_ARCH_STABLELM, "stablelm" },
  218. { LLM_ARCH_QWEN, "qwen" },
  219. { LLM_ARCH_QWEN2, "qwen2" },
  220. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  221. { LLM_ARCH_PHI2, "phi2" },
  222. { LLM_ARCH_PHI3, "phi3" },
  223. { LLM_ARCH_PLAMO, "plamo" },
  224. { LLM_ARCH_CODESHELL, "codeshell" },
  225. { LLM_ARCH_ORION, "orion" },
  226. { LLM_ARCH_INTERNLM2, "internlm2" },
  227. { LLM_ARCH_MINICPM, "minicpm" },
  228. { LLM_ARCH_GEMMA, "gemma" },
  229. { LLM_ARCH_STARCODER2, "starcoder2" },
  230. { LLM_ARCH_MAMBA, "mamba" },
  231. { LLM_ARCH_XVERSE, "xverse" },
  232. { LLM_ARCH_COMMAND_R, "command-r" },
  233. { LLM_ARCH_DBRX, "dbrx" },
  234. { LLM_ARCH_OLMO, "olmo" },
  235. { LLM_ARCH_ARCTIC, "arctic" },
  236. { LLM_ARCH_DEEPSEEK2, "deepseek2" },
  237. { LLM_ARCH_UNKNOWN, "(unknown)" },
  238. };
  239. enum llm_kv {
  240. LLM_KV_GENERAL_ARCHITECTURE,
  241. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  242. LLM_KV_GENERAL_ALIGNMENT,
  243. LLM_KV_GENERAL_NAME,
  244. LLM_KV_GENERAL_AUTHOR,
  245. LLM_KV_GENERAL_VERSION,
  246. LLM_KV_GENERAL_URL,
  247. LLM_KV_GENERAL_DESCRIPTION,
  248. LLM_KV_GENERAL_LICENSE,
  249. LLM_KV_GENERAL_SOURCE_URL,
  250. LLM_KV_GENERAL_SOURCE_HF_REPO,
  251. LLM_KV_VOCAB_SIZE,
  252. LLM_KV_CONTEXT_LENGTH,
  253. LLM_KV_EMBEDDING_LENGTH,
  254. LLM_KV_BLOCK_COUNT,
  255. LLM_KV_LEADING_DENSE_BLOCK_COUNT,
  256. LLM_KV_FEED_FORWARD_LENGTH,
  257. LLM_KV_EXPERT_FEED_FORWARD_LENGTH,
  258. LLM_KV_USE_PARALLEL_RESIDUAL,
  259. LLM_KV_TENSOR_DATA_LAYOUT,
  260. LLM_KV_EXPERT_COUNT,
  261. LLM_KV_EXPERT_USED_COUNT,
  262. LLM_KV_EXPERT_SHARED_COUNT,
  263. LLM_KV_EXPERT_WEIGHTS_SCALE,
  264. LLM_KV_POOLING_TYPE,
  265. LLM_KV_LOGIT_SCALE,
  266. LLM_KV_ATTENTION_HEAD_COUNT,
  267. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  268. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  269. LLM_KV_ATTENTION_CLAMP_KQV,
  270. LLM_KV_ATTENTION_KEY_LENGTH,
  271. LLM_KV_ATTENTION_VALUE_LENGTH,
  272. LLM_KV_ATTENTION_LAYERNORM_EPS,
  273. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  274. LLM_KV_ATTENTION_CAUSAL,
  275. LLM_KV_ATTENTION_Q_LORA_RANK,
  276. LLM_KV_ATTENTION_KV_LORA_RANK,
  277. LLM_KV_ROPE_DIMENSION_COUNT,
  278. LLM_KV_ROPE_FREQ_BASE,
  279. LLM_KV_ROPE_SCALE_LINEAR,
  280. LLM_KV_ROPE_SCALING_TYPE,
  281. LLM_KV_ROPE_SCALING_FACTOR,
  282. LLM_KV_ROPE_SCALING_ATTN_FACTOR,
  283. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  284. LLM_KV_ROPE_SCALING_FINETUNED,
  285. LLM_KV_ROPE_SCALING_YARN_LOG_MUL,
  286. LLM_KV_SPLIT_NO,
  287. LLM_KV_SPLIT_COUNT,
  288. LLM_KV_SPLIT_TENSORS_COUNT,
  289. LLM_KV_SSM_INNER_SIZE,
  290. LLM_KV_SSM_CONV_KERNEL,
  291. LLM_KV_SSM_STATE_SIZE,
  292. LLM_KV_SSM_TIME_STEP_RANK,
  293. LLM_KV_TOKENIZER_MODEL,
  294. LLM_KV_TOKENIZER_PRE,
  295. LLM_KV_TOKENIZER_LIST,
  296. LLM_KV_TOKENIZER_TOKEN_TYPE,
  297. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  298. LLM_KV_TOKENIZER_SCORES,
  299. LLM_KV_TOKENIZER_MERGES,
  300. LLM_KV_TOKENIZER_BOS_ID,
  301. LLM_KV_TOKENIZER_EOS_ID,
  302. LLM_KV_TOKENIZER_UNK_ID,
  303. LLM_KV_TOKENIZER_SEP_ID,
  304. LLM_KV_TOKENIZER_PAD_ID,
  305. LLM_KV_TOKENIZER_CLS_ID,
  306. LLM_KV_TOKENIZER_MASK_ID,
  307. LLM_KV_TOKENIZER_ADD_BOS,
  308. LLM_KV_TOKENIZER_ADD_EOS,
  309. LLM_KV_TOKENIZER_ADD_PREFIX,
  310. LLM_KV_TOKENIZER_HF_JSON,
  311. LLM_KV_TOKENIZER_RWKV,
  312. LLM_KV_TOKENIZER_PREFIX_ID,
  313. LLM_KV_TOKENIZER_SUFFIX_ID,
  314. LLM_KV_TOKENIZER_MIDDLE_ID,
  315. LLM_KV_TOKENIZER_EOT_ID,
  316. };
  317. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  318. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  319. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  320. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  321. { LLM_KV_GENERAL_NAME, "general.name" },
  322. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  323. { LLM_KV_GENERAL_VERSION, "general.version" },
  324. { LLM_KV_GENERAL_URL, "general.url" },
  325. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  326. { LLM_KV_GENERAL_LICENSE, "general.license" },
  327. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  328. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  329. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  330. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  331. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  332. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  333. { LLM_KV_LEADING_DENSE_BLOCK_COUNT, "%s.leading_dense_block_count" },
  334. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  335. { LLM_KV_EXPERT_FEED_FORWARD_LENGTH, "%s.expert_feed_forward_length" },
  336. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  337. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  338. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  339. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  340. { LLM_KV_EXPERT_SHARED_COUNT, "%s.expert_shared_count" },
  341. { LLM_KV_EXPERT_WEIGHTS_SCALE, "%s.expert_weights_scale" },
  342. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  343. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  344. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  345. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  346. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  347. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  348. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  349. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  350. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  351. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  352. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  353. { LLM_KV_ATTENTION_Q_LORA_RANK, "%s.attention.q_lora_rank" },
  354. { LLM_KV_ATTENTION_KV_LORA_RANK, "%s.attention.kv_lora_rank" },
  355. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  356. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  357. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  358. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  359. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  360. { LLM_KV_ROPE_SCALING_ATTN_FACTOR, "%s.rope.scaling.attn_factor" },
  361. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  362. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  363. { LLM_KV_ROPE_SCALING_YARN_LOG_MUL, "%s.rope.scaling.yarn_log_multiplier" },
  364. { LLM_KV_SPLIT_NO, "split.no" },
  365. { LLM_KV_SPLIT_COUNT, "split.count" },
  366. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  367. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  368. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  369. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  370. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  371. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  372. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  373. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  374. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  375. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  376. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  377. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  378. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  379. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  380. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  381. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  382. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  383. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  384. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  385. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  386. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  387. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  388. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  389. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  390. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  391. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  392. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  393. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  394. };
  395. struct LLM_KV {
  396. LLM_KV(llm_arch arch) : arch(arch) {}
  397. llm_arch arch;
  398. std::string operator()(llm_kv kv) const {
  399. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  400. }
  401. };
  402. enum llm_tensor {
  403. LLM_TENSOR_TOKEN_EMBD,
  404. LLM_TENSOR_TOKEN_EMBD_NORM,
  405. LLM_TENSOR_TOKEN_TYPES,
  406. LLM_TENSOR_POS_EMBD,
  407. LLM_TENSOR_OUTPUT,
  408. LLM_TENSOR_OUTPUT_NORM,
  409. LLM_TENSOR_ROPE_FREQS,
  410. LLM_TENSOR_ROPE_FACTORS_LONG,
  411. LLM_TENSOR_ROPE_FACTORS_SHORT,
  412. LLM_TENSOR_ATTN_Q,
  413. LLM_TENSOR_ATTN_K,
  414. LLM_TENSOR_ATTN_V,
  415. LLM_TENSOR_ATTN_QKV,
  416. LLM_TENSOR_ATTN_OUT,
  417. LLM_TENSOR_ATTN_NORM,
  418. LLM_TENSOR_ATTN_NORM_2,
  419. LLM_TENSOR_ATTN_OUT_NORM,
  420. LLM_TENSOR_ATTN_ROT_EMBD,
  421. LLM_TENSOR_FFN_GATE_INP,
  422. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  423. LLM_TENSOR_FFN_NORM,
  424. LLM_TENSOR_FFN_GATE,
  425. LLM_TENSOR_FFN_DOWN,
  426. LLM_TENSOR_FFN_UP,
  427. LLM_TENSOR_FFN_ACT,
  428. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  429. LLM_TENSOR_FFN_GATE_EXP,
  430. LLM_TENSOR_FFN_UP_EXP,
  431. LLM_TENSOR_FFN_NORM_EXPS,
  432. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  433. LLM_TENSOR_FFN_GATE_EXPS,
  434. LLM_TENSOR_FFN_UP_EXPS,
  435. LLM_TENSOR_FFN_DOWN_SHEXP,
  436. LLM_TENSOR_FFN_GATE_SHEXP,
  437. LLM_TENSOR_FFN_UP_SHEXP,
  438. LLM_TENSOR_ATTN_Q_NORM,
  439. LLM_TENSOR_ATTN_K_NORM,
  440. LLM_TENSOR_LAYER_OUT_NORM,
  441. LLM_TENSOR_SSM_IN,
  442. LLM_TENSOR_SSM_CONV1D,
  443. LLM_TENSOR_SSM_X,
  444. LLM_TENSOR_SSM_DT,
  445. LLM_TENSOR_SSM_A,
  446. LLM_TENSOR_SSM_D,
  447. LLM_TENSOR_SSM_OUT,
  448. LLM_TENSOR_ATTN_Q_A,
  449. LLM_TENSOR_ATTN_Q_B,
  450. LLM_TENSOR_ATTN_KV_A_MQA,
  451. LLM_TENSOR_ATTN_KV_B,
  452. LLM_TENSOR_ATTN_Q_A_NORM,
  453. LLM_TENSOR_ATTN_KV_A_NORM,
  454. };
  455. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  456. {
  457. LLM_ARCH_LLAMA,
  458. {
  459. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  460. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  461. { LLM_TENSOR_OUTPUT, "output" },
  462. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  463. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  464. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  465. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  466. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  467. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  468. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  469. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  470. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  471. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  472. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  473. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  474. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  475. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  476. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  477. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  478. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  479. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  480. },
  481. },
  482. {
  483. LLM_ARCH_BAICHUAN,
  484. {
  485. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  486. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  487. { LLM_TENSOR_OUTPUT, "output" },
  488. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  489. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  490. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  491. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  492. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  493. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  494. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  495. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  496. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  497. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  498. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  499. },
  500. },
  501. {
  502. LLM_ARCH_FALCON,
  503. {
  504. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  505. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  506. { LLM_TENSOR_OUTPUT, "output" },
  507. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  508. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  509. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  510. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  511. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  512. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  513. },
  514. },
  515. {
  516. LLM_ARCH_GROK,
  517. {
  518. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  519. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  520. { LLM_TENSOR_OUTPUT, "output" },
  521. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  522. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  523. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  524. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  525. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  528. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  529. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  530. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  531. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  532. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  533. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  534. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  535. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  536. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  537. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  538. },
  539. },
  540. {
  541. LLM_ARCH_GPT2,
  542. {
  543. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  544. { LLM_TENSOR_POS_EMBD, "position_embd" },
  545. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  546. { LLM_TENSOR_OUTPUT, "output" },
  547. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  548. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  549. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  550. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  551. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  552. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  553. },
  554. },
  555. {
  556. LLM_ARCH_GPTJ,
  557. {
  558. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  559. },
  560. },
  561. {
  562. LLM_ARCH_GPTNEOX,
  563. {
  564. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  565. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  566. { LLM_TENSOR_OUTPUT, "output" },
  567. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  568. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  569. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  570. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  571. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  572. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  573. },
  574. },
  575. {
  576. LLM_ARCH_MPT,
  577. {
  578. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  579. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  580. { LLM_TENSOR_OUTPUT, "output"},
  581. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  582. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  583. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  584. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  585. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  586. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  587. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  588. { LLM_TENSOR_POS_EMBD, "position_embd" },
  589. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  590. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  591. },
  592. },
  593. {
  594. LLM_ARCH_STARCODER,
  595. {
  596. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  597. { LLM_TENSOR_POS_EMBD, "position_embd" },
  598. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  599. { LLM_TENSOR_OUTPUT, "output" },
  600. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  601. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  602. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  603. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  604. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  605. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  606. },
  607. },
  608. {
  609. LLM_ARCH_REFACT,
  610. {
  611. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  612. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  613. { LLM_TENSOR_OUTPUT, "output" },
  614. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  615. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  616. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  617. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  618. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  619. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  620. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  621. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  622. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  623. },
  624. },
  625. {
  626. LLM_ARCH_BERT,
  627. {
  628. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  629. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  630. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  631. { LLM_TENSOR_POS_EMBD, "position_embd" },
  632. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  633. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  634. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  635. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  636. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  637. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  638. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  639. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  640. },
  641. },
  642. {
  643. LLM_ARCH_NOMIC_BERT,
  644. {
  645. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  646. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  647. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  648. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  649. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  650. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  651. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  652. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  653. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  654. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  655. },
  656. },
  657. {
  658. LLM_ARCH_JINA_BERT_V2,
  659. {
  660. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  661. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  662. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  663. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  664. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  665. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  666. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  667. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  668. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  669. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  670. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  671. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  672. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  673. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  674. },
  675. },
  676. {
  677. LLM_ARCH_BLOOM,
  678. {
  679. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  680. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  681. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  682. { LLM_TENSOR_OUTPUT, "output" },
  683. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  684. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  685. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  686. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  687. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  688. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  689. },
  690. },
  691. {
  692. LLM_ARCH_STABLELM,
  693. {
  694. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  695. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  696. { LLM_TENSOR_OUTPUT, "output" },
  697. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  698. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  699. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  700. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  701. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  702. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  703. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  704. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  705. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  706. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  707. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  708. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  709. },
  710. },
  711. {
  712. LLM_ARCH_QWEN,
  713. {
  714. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  715. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  716. { LLM_TENSOR_OUTPUT, "output" },
  717. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  718. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  719. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  720. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  721. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  722. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  723. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  724. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  725. },
  726. },
  727. {
  728. LLM_ARCH_QWEN2,
  729. {
  730. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  731. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  732. { LLM_TENSOR_OUTPUT, "output" },
  733. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  734. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  735. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  736. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  737. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  738. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_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_QWEN2MOE,
  746. {
  747. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  748. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  749. { LLM_TENSOR_OUTPUT, "output" },
  750. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  751. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  752. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  753. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  754. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  755. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  756. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  757. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  758. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  759. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  760. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  761. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  762. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  763. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  764. },
  765. },
  766. {
  767. LLM_ARCH_PHI2,
  768. {
  769. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  770. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  771. { LLM_TENSOR_OUTPUT, "output" },
  772. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  773. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  774. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  775. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  776. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  777. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  778. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  779. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  780. },
  781. },
  782. {
  783. LLM_ARCH_PHI3,
  784. {
  785. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  786. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  787. { LLM_TENSOR_OUTPUT, "output" },
  788. { LLM_TENSOR_ROPE_FACTORS_LONG, "rope_factors_long" },
  789. { LLM_TENSOR_ROPE_FACTORS_SHORT, "rope_factors_short" },
  790. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  791. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  792. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  793. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  794. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  795. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  796. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  797. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  798. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  799. },
  800. },
  801. {
  802. LLM_ARCH_PLAMO,
  803. {
  804. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  805. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  806. { LLM_TENSOR_OUTPUT, "output" },
  807. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  808. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  809. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  810. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  811. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  812. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  813. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  814. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  815. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  816. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  817. },
  818. },
  819. {
  820. LLM_ARCH_CODESHELL,
  821. {
  822. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  823. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  824. { LLM_TENSOR_OUTPUT, "output" },
  825. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  826. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  827. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  828. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  829. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  830. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  831. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  832. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  833. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  834. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  835. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  836. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  837. },
  838. },
  839. {
  840. LLM_ARCH_ORION,
  841. {
  842. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  843. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  844. { LLM_TENSOR_OUTPUT, "output" },
  845. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  846. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  847. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  848. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  849. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  850. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  851. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  852. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  853. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  854. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  855. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  856. },
  857. },
  858. {
  859. LLM_ARCH_INTERNLM2,
  860. {
  861. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  862. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  863. { LLM_TENSOR_OUTPUT, "output" },
  864. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  865. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  866. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  867. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  868. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  869. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  870. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  871. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  872. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  873. },
  874. },
  875. {
  876. LLM_ARCH_MINICPM,
  877. {
  878. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  879. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  880. { LLM_TENSOR_OUTPUT, "output" },
  881. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  882. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  883. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  884. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  885. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  886. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  887. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  888. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  889. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  890. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  891. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  892. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  893. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  894. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  895. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  896. },
  897. },
  898. {
  899. LLM_ARCH_GEMMA,
  900. {
  901. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  902. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  903. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  904. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  905. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  906. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  907. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  908. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  909. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  910. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  911. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  912. },
  913. },
  914. {
  915. LLM_ARCH_STARCODER2,
  916. {
  917. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  918. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  919. { LLM_TENSOR_OUTPUT, "output" },
  920. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  921. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  922. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  923. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  924. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  925. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  926. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  927. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  928. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  929. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  930. },
  931. },
  932. {
  933. LLM_ARCH_MAMBA,
  934. {
  935. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  936. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  937. { LLM_TENSOR_OUTPUT, "output" },
  938. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  939. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  940. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  941. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  942. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  943. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  944. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  945. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  946. },
  947. },
  948. {
  949. LLM_ARCH_XVERSE,
  950. {
  951. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  952. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  953. { LLM_TENSOR_OUTPUT, "output" },
  954. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  955. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  956. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  957. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  958. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  959. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  960. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  961. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  962. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  963. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  964. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  965. },
  966. },
  967. {
  968. LLM_ARCH_COMMAND_R,
  969. {
  970. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  971. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  972. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  973. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  974. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  975. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  976. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  977. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  978. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  979. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  980. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  981. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  982. },
  983. },
  984. {
  985. LLM_ARCH_DBRX,
  986. {
  987. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  988. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  989. { LLM_TENSOR_OUTPUT, "output" },
  990. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  991. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  992. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  993. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  994. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  995. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  996. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  997. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  998. },
  999. },
  1000. {
  1001. LLM_ARCH_OLMO,
  1002. {
  1003. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1004. { LLM_TENSOR_OUTPUT, "output" },
  1005. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1006. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1007. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1008. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1009. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1010. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1011. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1012. },
  1013. },
  1014. {
  1015. LLM_ARCH_ARCTIC,
  1016. {
  1017. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1018. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1019. { LLM_TENSOR_OUTPUT, "output" },
  1020. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1021. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1022. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1023. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1024. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1025. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1026. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1027. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1028. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1029. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1030. { LLM_TENSOR_FFN_NORM_EXPS, "blk.%d.ffn_norm_exps" },
  1031. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1032. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1033. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1034. },
  1035. },
  1036. {
  1037. LLM_ARCH_DEEPSEEK2,
  1038. {
  1039. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1040. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  1041. { LLM_TENSOR_OUTPUT, "output" },
  1042. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  1043. { LLM_TENSOR_ATTN_Q_A_NORM, "blk.%d.attn_q_a_norm" },
  1044. { LLM_TENSOR_ATTN_KV_A_NORM, "blk.%d.attn_kv_a_norm" },
  1045. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  1046. { LLM_TENSOR_ATTN_Q_A, "blk.%d.attn_q_a" },
  1047. { LLM_TENSOR_ATTN_Q_B, "blk.%d.attn_q_b" },
  1048. { LLM_TENSOR_ATTN_KV_A_MQA, "blk.%d.attn_kv_a_mqa" },
  1049. { LLM_TENSOR_ATTN_KV_B, "blk.%d.attn_kv_b" },
  1050. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1051. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  1052. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1053. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1054. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1055. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  1056. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  1057. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  1058. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  1059. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  1060. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  1061. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  1062. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  1063. },
  1064. },
  1065. {
  1066. LLM_ARCH_UNKNOWN,
  1067. {
  1068. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1069. },
  1070. },
  1071. };
  1072. static llm_arch llm_arch_from_string(const std::string & name) {
  1073. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1074. if (kv.second == name) {
  1075. return kv.first;
  1076. }
  1077. }
  1078. return LLM_ARCH_UNKNOWN;
  1079. }
  1080. // helper to handle gguf constants
  1081. // usage:
  1082. //
  1083. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1084. //
  1085. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1086. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1087. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1088. //
  1089. struct LLM_TN {
  1090. LLM_TN(llm_arch arch) : arch(arch) {}
  1091. llm_arch arch;
  1092. std::string operator()(llm_tensor tensor) const {
  1093. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1094. return "__missing__";
  1095. }
  1096. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1097. }
  1098. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1099. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1100. return "__missing__";
  1101. }
  1102. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1103. }
  1104. std::string operator()(llm_tensor tensor, int bid) const {
  1105. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1106. return "__missing__";
  1107. }
  1108. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1109. }
  1110. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1111. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1112. return "__missing__";
  1113. }
  1114. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1115. }
  1116. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1117. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1118. return "__missing__";
  1119. }
  1120. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1121. }
  1122. };
  1123. //
  1124. // gguf helpers
  1125. //
  1126. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1127. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1128. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1129. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1130. };
  1131. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1132. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1133. if (kv.second == name) {
  1134. return (llama_rope_scaling_type) kv.first;
  1135. }
  1136. }
  1137. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1138. }
  1139. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1140. switch (type) {
  1141. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1142. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1143. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1144. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1145. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1146. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1147. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1148. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1149. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1150. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1151. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1152. default: return format("unknown type %d", type);
  1153. }
  1154. }
  1155. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1156. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1157. switch (type) {
  1158. case GGUF_TYPE_STRING:
  1159. return gguf_get_val_str(ctx_gguf, i);
  1160. case GGUF_TYPE_ARRAY:
  1161. {
  1162. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1163. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1164. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1165. std::stringstream ss;
  1166. ss << "[";
  1167. for (int j = 0; j < arr_n; j++) {
  1168. if (arr_type == GGUF_TYPE_STRING) {
  1169. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1170. // escape quotes
  1171. replace_all(val, "\\", "\\\\");
  1172. replace_all(val, "\"", "\\\"");
  1173. ss << '"' << val << '"';
  1174. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1175. ss << "???";
  1176. } else {
  1177. ss << gguf_data_to_str(arr_type, data, j);
  1178. }
  1179. if (j < arr_n - 1) {
  1180. ss << ", ";
  1181. }
  1182. }
  1183. ss << "]";
  1184. return ss.str();
  1185. }
  1186. default:
  1187. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1188. }
  1189. }
  1190. //
  1191. // llama helpers
  1192. //
  1193. #if defined(_WIN32)
  1194. static std::string llama_format_win_err(DWORD err) {
  1195. LPSTR buf;
  1196. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1197. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1198. if (!size) {
  1199. return "FormatMessageA failed";
  1200. }
  1201. std::string ret(buf, size);
  1202. LocalFree(buf);
  1203. return ret;
  1204. }
  1205. #endif
  1206. template <typename T>
  1207. struct no_init {
  1208. T value;
  1209. no_init() { /* do nothing */ }
  1210. };
  1211. struct llama_file {
  1212. // use FILE * so we don't have to re-open the file to mmap
  1213. FILE * fp;
  1214. size_t size;
  1215. llama_file(const char * fname, const char * mode) {
  1216. fp = ggml_fopen(fname, mode);
  1217. if (fp == NULL) {
  1218. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1219. }
  1220. seek(0, SEEK_END);
  1221. size = tell();
  1222. seek(0, SEEK_SET);
  1223. }
  1224. size_t tell() const {
  1225. #ifdef _WIN32
  1226. __int64 ret = _ftelli64(fp);
  1227. #else
  1228. long ret = std::ftell(fp);
  1229. #endif
  1230. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1231. return (size_t) ret;
  1232. }
  1233. void seek(size_t offset, int whence) const {
  1234. #ifdef _WIN32
  1235. int ret = _fseeki64(fp, (__int64) offset, whence);
  1236. #else
  1237. int ret = std::fseek(fp, (long) offset, whence);
  1238. #endif
  1239. GGML_ASSERT(ret == 0); // same
  1240. }
  1241. void read_raw(void * ptr, size_t len) const {
  1242. if (len == 0) {
  1243. return;
  1244. }
  1245. errno = 0;
  1246. std::size_t ret = std::fread(ptr, len, 1, fp);
  1247. if (ferror(fp)) {
  1248. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1249. }
  1250. if (ret != 1) {
  1251. throw std::runtime_error("unexpectedly reached end of file");
  1252. }
  1253. }
  1254. uint32_t read_u32() const {
  1255. uint32_t ret;
  1256. read_raw(&ret, sizeof(ret));
  1257. return ret;
  1258. }
  1259. void write_raw(const void * ptr, size_t len) const {
  1260. if (len == 0) {
  1261. return;
  1262. }
  1263. errno = 0;
  1264. size_t ret = std::fwrite(ptr, len, 1, fp);
  1265. if (ret != 1) {
  1266. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1267. }
  1268. }
  1269. void write_u32(std::uint32_t val) const {
  1270. write_raw(&val, sizeof(val));
  1271. }
  1272. ~llama_file() {
  1273. if (fp) {
  1274. std::fclose(fp);
  1275. }
  1276. }
  1277. };
  1278. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1279. struct llama_mmap {
  1280. void * addr;
  1281. size_t size;
  1282. llama_mmap(const llama_mmap &) = delete;
  1283. #ifdef _POSIX_MAPPED_FILES
  1284. static constexpr bool SUPPORTED = true;
  1285. // list of mapped fragments (first_offset, last_offset)
  1286. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1287. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1288. size = file->size;
  1289. int fd = fileno(file->fp);
  1290. int flags = MAP_SHARED;
  1291. // prefetch/readahead impairs performance on NUMA systems
  1292. if (numa) { prefetch = 0; }
  1293. #ifdef __linux__
  1294. // advise the kernel to read the file sequentially (increases readahead)
  1295. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1296. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1297. strerror(errno));
  1298. }
  1299. if (prefetch) { flags |= MAP_POPULATE; }
  1300. #endif
  1301. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1302. if (addr == MAP_FAILED) { // NOLINT
  1303. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1304. }
  1305. if (prefetch > 0) {
  1306. // advise the kernel to preload the mapped memory
  1307. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1308. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1309. strerror(errno));
  1310. }
  1311. }
  1312. if (numa) {
  1313. // advise the kernel not to use readahead
  1314. // (because the next page might not belong on the same node)
  1315. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1316. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1317. strerror(errno));
  1318. }
  1319. }
  1320. // initialize list of mapped_fragments
  1321. mapped_fragments.emplace_back(0, file->size);
  1322. }
  1323. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1324. // align first to the next page
  1325. size_t offset_in_page = *first & (page_size - 1);
  1326. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1327. *first += offset_to_page;
  1328. // align last to the previous page
  1329. *last = *last & ~(page_size - 1);
  1330. if (*last <= *first) {
  1331. *last = *first;
  1332. }
  1333. }
  1334. // partially unmap the file in the range [first, last)
  1335. void unmap_fragment(size_t first, size_t last) {
  1336. // note: this function must not be called multiple times with overlapping ranges
  1337. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1338. int page_size = sysconf(_SC_PAGESIZE);
  1339. align_range(&first, &last, page_size);
  1340. size_t len = last - first;
  1341. if (len == 0) {
  1342. return;
  1343. }
  1344. GGML_ASSERT(first % page_size == 0);
  1345. GGML_ASSERT(last % page_size == 0);
  1346. GGML_ASSERT(last > first);
  1347. void * next_page_start = (uint8_t *) addr + first;
  1348. // unmap the range
  1349. if (munmap(next_page_start, len)) {
  1350. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1351. }
  1352. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1353. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1354. for (const auto & frag : mapped_fragments) {
  1355. if (frag.first < first && frag.second > last) {
  1356. // the range is in the middle of the fragment, split it
  1357. new_mapped_fragments.emplace_back(frag.first, first);
  1358. new_mapped_fragments.emplace_back(last, frag.second);
  1359. } else if (frag.first < first && frag.second > first) {
  1360. // the range starts in the middle of the fragment
  1361. new_mapped_fragments.emplace_back(frag.first, first);
  1362. } else if (frag.first < last && frag.second > last) {
  1363. // the range ends in the middle of the fragment
  1364. new_mapped_fragments.emplace_back(last, frag.second);
  1365. } else if (frag.first >= first && frag.second <= last) {
  1366. // the range covers the entire fragment
  1367. } else {
  1368. // the range is outside the fragment
  1369. new_mapped_fragments.push_back(frag);
  1370. }
  1371. }
  1372. mapped_fragments = std::move(new_mapped_fragments);
  1373. }
  1374. ~llama_mmap() {
  1375. for (const auto & frag : mapped_fragments) {
  1376. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1377. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1378. }
  1379. }
  1380. }
  1381. #elif defined(_WIN32)
  1382. static constexpr bool SUPPORTED = true;
  1383. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1384. GGML_UNUSED(numa);
  1385. size = file->size;
  1386. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1387. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1388. if (hMapping == NULL) {
  1389. DWORD error = GetLastError();
  1390. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1391. }
  1392. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1393. DWORD error = GetLastError();
  1394. CloseHandle(hMapping);
  1395. if (addr == NULL) {
  1396. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1397. }
  1398. if (prefetch > 0) {
  1399. #if _WIN32_WINNT >= 0x602
  1400. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1401. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1402. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1403. // may fail on pre-Windows 8 systems
  1404. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1405. if (pPrefetchVirtualMemory) {
  1406. // advise the kernel to preload the mapped memory
  1407. WIN32_MEMORY_RANGE_ENTRY range;
  1408. range.VirtualAddress = addr;
  1409. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1410. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1411. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1412. llama_format_win_err(GetLastError()).c_str());
  1413. }
  1414. }
  1415. #else
  1416. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1417. #endif
  1418. }
  1419. }
  1420. void unmap_fragment(size_t first, size_t last) {
  1421. // not supported
  1422. GGML_UNUSED(first);
  1423. GGML_UNUSED(last);
  1424. }
  1425. ~llama_mmap() {
  1426. if (!UnmapViewOfFile(addr)) {
  1427. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1428. llama_format_win_err(GetLastError()).c_str());
  1429. }
  1430. }
  1431. #else
  1432. static constexpr bool SUPPORTED = false;
  1433. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1434. GGML_UNUSED(file);
  1435. GGML_UNUSED(prefetch);
  1436. GGML_UNUSED(numa);
  1437. throw std::runtime_error("mmap not supported");
  1438. }
  1439. void unmap_fragment(size_t first, size_t last) {
  1440. GGML_UNUSED(first);
  1441. GGML_UNUSED(last);
  1442. throw std::runtime_error("mmap not supported");
  1443. }
  1444. #endif
  1445. };
  1446. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1447. // Represents some region of memory being locked using mlock or VirtualLock;
  1448. // will automatically unlock on destruction.
  1449. struct llama_mlock {
  1450. void * addr = NULL;
  1451. size_t size = 0;
  1452. bool failed_already = false;
  1453. llama_mlock() {}
  1454. llama_mlock(const llama_mlock &) = delete;
  1455. ~llama_mlock() {
  1456. if (size) {
  1457. raw_unlock(addr, size);
  1458. }
  1459. }
  1460. void init(void * ptr) {
  1461. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1462. addr = ptr;
  1463. }
  1464. void grow_to(size_t target_size) {
  1465. GGML_ASSERT(addr);
  1466. if (failed_already) {
  1467. return;
  1468. }
  1469. size_t granularity = lock_granularity();
  1470. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1471. if (target_size > size) {
  1472. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1473. size = target_size;
  1474. } else {
  1475. failed_already = true;
  1476. }
  1477. }
  1478. }
  1479. #ifdef _POSIX_MEMLOCK_RANGE
  1480. static constexpr bool SUPPORTED = true;
  1481. static size_t lock_granularity() {
  1482. return (size_t) sysconf(_SC_PAGESIZE);
  1483. }
  1484. #ifdef __APPLE__
  1485. #define MLOCK_SUGGESTION \
  1486. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1487. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1488. #else
  1489. #define MLOCK_SUGGESTION \
  1490. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1491. #endif
  1492. bool raw_lock(const void * addr, size_t size) const {
  1493. if (!mlock(addr, size)) {
  1494. return true;
  1495. }
  1496. char* errmsg = std::strerror(errno);
  1497. bool suggest = (errno == ENOMEM);
  1498. // Check if the resource limit is fine after all
  1499. struct rlimit lock_limit;
  1500. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1501. suggest = false;
  1502. }
  1503. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1504. suggest = false;
  1505. }
  1506. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1507. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1508. return false;
  1509. }
  1510. #undef MLOCK_SUGGESTION
  1511. static void raw_unlock(void * addr, size_t size) {
  1512. if (munlock(addr, size)) {
  1513. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1514. }
  1515. }
  1516. #elif defined(_WIN32)
  1517. static constexpr bool SUPPORTED = true;
  1518. static size_t lock_granularity() {
  1519. SYSTEM_INFO si;
  1520. GetSystemInfo(&si);
  1521. return (size_t) si.dwPageSize;
  1522. }
  1523. bool raw_lock(void * ptr, size_t len) const {
  1524. for (int tries = 1; ; tries++) {
  1525. if (VirtualLock(ptr, len)) {
  1526. return true;
  1527. }
  1528. if (tries == 2) {
  1529. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1530. len, size, llama_format_win_err(GetLastError()).c_str());
  1531. return false;
  1532. }
  1533. // It failed but this was only the first try; increase the working
  1534. // set size and try again.
  1535. SIZE_T min_ws_size, max_ws_size;
  1536. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1537. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1538. llama_format_win_err(GetLastError()).c_str());
  1539. return false;
  1540. }
  1541. // Per MSDN: "The maximum number of pages that a process can lock
  1542. // is equal to the number of pages in its minimum working set minus
  1543. // a small overhead."
  1544. // Hopefully a megabyte is enough overhead:
  1545. size_t increment = len + 1048576;
  1546. // The minimum must be <= the maximum, so we need to increase both:
  1547. min_ws_size += increment;
  1548. max_ws_size += increment;
  1549. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1550. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1551. llama_format_win_err(GetLastError()).c_str());
  1552. return false;
  1553. }
  1554. }
  1555. }
  1556. static void raw_unlock(void * ptr, size_t len) {
  1557. if (!VirtualUnlock(ptr, len)) {
  1558. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1559. llama_format_win_err(GetLastError()).c_str());
  1560. }
  1561. }
  1562. #else
  1563. static constexpr bool SUPPORTED = false;
  1564. static size_t lock_granularity() {
  1565. return (size_t) 65536;
  1566. }
  1567. bool raw_lock(const void * addr, size_t len) const {
  1568. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1569. return false;
  1570. }
  1571. static void raw_unlock(const void * addr, size_t len) {}
  1572. #endif
  1573. };
  1574. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1575. // NOTE: avoid ever using this except for building the token_to_piece caches
  1576. static std::string llama_token_to_piece(const struct llama_model * model, llama_token token, bool special) {
  1577. std::vector<char> result(8, 0);
  1578. const int n_tokens = llama_token_to_piece(model, token, result.data(), result.size(), special);
  1579. if (n_tokens < 0) {
  1580. result.resize(-n_tokens);
  1581. int check = llama_token_to_piece(model, token, result.data(), result.size(), special);
  1582. GGML_ASSERT(check == -n_tokens);
  1583. }
  1584. else {
  1585. result.resize(n_tokens);
  1586. }
  1587. return std::string(result.data(), result.size());
  1588. }
  1589. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1590. ggml_backend_buffer_type_t buft = nullptr;
  1591. #if defined(GGML_USE_CUDA)
  1592. // host buffers should only be used when data is expected to be copied to/from the GPU
  1593. if (host_buffer) {
  1594. buft = ggml_backend_cuda_host_buffer_type();
  1595. }
  1596. #elif defined(GGML_USE_SYCL)
  1597. if (host_buffer) {
  1598. buft = ggml_backend_sycl_host_buffer_type();
  1599. }
  1600. #elif defined(GGML_USE_CPU_HBM)
  1601. buft = ggml_backend_cpu_hbm_buffer_type();
  1602. #elif defined(GGML_USE_VULKAN)
  1603. if (host_buffer) {
  1604. buft = ggml_backend_vk_host_buffer_type();
  1605. }
  1606. #endif
  1607. if (buft == nullptr) {
  1608. buft = ggml_backend_cpu_buffer_type();
  1609. }
  1610. return buft;
  1611. GGML_UNUSED(host_buffer);
  1612. }
  1613. //
  1614. // globals
  1615. //
  1616. struct llama_state {
  1617. llama_state() {
  1618. #ifdef GGML_USE_METAL
  1619. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1620. #elif defined(GGML_USE_CUDA)
  1621. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1622. #endif
  1623. }
  1624. // We save the log callback globally
  1625. ggml_log_callback log_callback = llama_log_callback_default;
  1626. void * log_callback_user_data = nullptr;
  1627. };
  1628. static llama_state g_state;
  1629. // available llama models
  1630. enum e_model {
  1631. MODEL_UNKNOWN,
  1632. MODEL_14M,
  1633. MODEL_17M,
  1634. MODEL_22M,
  1635. MODEL_33M,
  1636. MODEL_70M,
  1637. MODEL_109M,
  1638. MODEL_137M,
  1639. MODEL_160M,
  1640. MODEL_335M,
  1641. MODEL_410M,
  1642. MODEL_0_5B,
  1643. MODEL_1B,
  1644. MODEL_1_4B,
  1645. MODEL_2B,
  1646. MODEL_2_8B,
  1647. MODEL_3B,
  1648. MODEL_4B,
  1649. MODEL_6_9B,
  1650. MODEL_7B,
  1651. MODEL_8B,
  1652. MODEL_12B,
  1653. MODEL_13B,
  1654. MODEL_14B,
  1655. MODEL_15B,
  1656. MODEL_16B,
  1657. MODEL_20B,
  1658. MODEL_30B,
  1659. MODEL_34B,
  1660. MODEL_35B,
  1661. MODEL_40B,
  1662. MODEL_65B,
  1663. MODEL_70B,
  1664. MODEL_236B,
  1665. MODEL_314B,
  1666. MODEL_SMALL,
  1667. MODEL_MEDIUM,
  1668. MODEL_LARGE,
  1669. MODEL_XL,
  1670. MODEL_A2_7B,
  1671. MODEL_8x7B,
  1672. MODEL_8x22B,
  1673. MODEL_16x12B,
  1674. MODEL_10B_128x3_66B,
  1675. };
  1676. static const size_t kiB = 1024;
  1677. static const size_t MiB = 1024*kiB;
  1678. static const size_t GiB = 1024*MiB;
  1679. struct llama_hparams {
  1680. bool vocab_only;
  1681. bool rope_finetuned;
  1682. bool use_par_res;
  1683. uint32_t n_vocab;
  1684. uint32_t n_ctx_train; // context size the model was trained on
  1685. uint32_t n_embd;
  1686. uint32_t n_head;
  1687. uint32_t n_head_kv;
  1688. uint32_t n_layer;
  1689. uint32_t n_rot;
  1690. 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
  1691. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1692. uint32_t n_ff;
  1693. uint32_t n_expert = 0;
  1694. uint32_t n_expert_used = 0;
  1695. uint32_t n_vocab_type = 0; // for BERT-style token types
  1696. uint32_t n_layer_dense_lead = 0;
  1697. uint32_t n_lora_q = 0;
  1698. uint32_t n_lora_kv = 0;
  1699. uint32_t n_ff_exp = 0;
  1700. uint32_t n_expert_shared = 0;
  1701. float expert_weights_scale = 0.0;
  1702. float f_norm_eps;
  1703. float f_norm_rms_eps;
  1704. float rope_attn_factor = 1.0f;
  1705. float rope_freq_base_train;
  1706. float rope_freq_scale_train;
  1707. uint32_t n_yarn_orig_ctx;
  1708. float rope_yarn_log_mul;
  1709. // for State Space Models
  1710. uint32_t ssm_d_conv = 0;
  1711. uint32_t ssm_d_inner = 0;
  1712. uint32_t ssm_d_state = 0;
  1713. uint32_t ssm_dt_rank = 0;
  1714. float f_clamp_kqv = 0.0f;
  1715. float f_max_alibi_bias = 0.0f;
  1716. float f_logit_scale = 0.0f;
  1717. bool causal_attn = true;
  1718. bool use_alibi = false;
  1719. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1720. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1721. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1722. bool operator!=(const llama_hparams & other) const {
  1723. if (this->vocab_only != other.vocab_only) return true;
  1724. if (this->n_vocab != other.n_vocab) return true;
  1725. if (this->n_ctx_train != other.n_ctx_train) return true;
  1726. if (this->n_embd != other.n_embd) return true;
  1727. if (this->n_head != other.n_head) return true;
  1728. if (this->n_head_kv != other.n_head_kv) return true;
  1729. if (this->n_layer != other.n_layer) return true;
  1730. if (this->n_rot != other.n_rot) return true;
  1731. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1732. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1733. if (this->n_ff != other.n_ff) return true;
  1734. if (this->n_expert != other.n_expert) return true;
  1735. if (this->n_expert_used != other.n_expert_used) return true;
  1736. if (this->n_layer_dense_lead != other.n_layer_dense_lead) return true;
  1737. if (this->n_lora_q != other.n_lora_q) return true;
  1738. if (this->n_lora_kv != other.n_lora_kv) return true;
  1739. if (this->n_ff_exp != other.n_ff_exp) return true;
  1740. if (this->n_expert_shared != other.n_expert_shared) return true;
  1741. if (this->rope_finetuned != other.rope_finetuned) return true;
  1742. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1743. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1744. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1745. if (this->ssm_d_state != other.ssm_d_state) return true;
  1746. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1747. const float EPSILON = 1e-9f;
  1748. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1749. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1750. if (!is_float_close(this->rope_attn_factor, other.rope_attn_factor, EPSILON)) return true;
  1751. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1752. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1753. if (!is_float_close(this->expert_weights_scale, other.expert_weights_scale, EPSILON)) return true;
  1754. if (!is_float_close(this->rope_yarn_log_mul, other.rope_yarn_log_mul, EPSILON)) return true;
  1755. return false;
  1756. }
  1757. uint32_t n_gqa() const {
  1758. if (n_head_kv == 0) {
  1759. return 0;
  1760. }
  1761. return n_head/n_head_kv;
  1762. }
  1763. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1764. return n_embd_head_k * n_head_kv;
  1765. }
  1766. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1767. return n_embd_head_v * n_head_kv;
  1768. }
  1769. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1770. // corresponds to Mamba's conv_states size
  1771. // TODO: maybe support other convolution strides than 1
  1772. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1773. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1774. }
  1775. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1776. // corresponds to Mamba's ssm_states size
  1777. return ssm_d_state * ssm_d_inner;
  1778. }
  1779. };
  1780. struct llama_cparams {
  1781. uint32_t n_ctx; // context size used during inference
  1782. uint32_t n_batch;
  1783. uint32_t n_ubatch;
  1784. uint32_t n_seq_max;
  1785. uint32_t n_threads; // number of threads to use for generation
  1786. uint32_t n_threads_batch; // number of threads to use for batch processing
  1787. float rope_freq_base;
  1788. float rope_freq_scale;
  1789. uint32_t n_yarn_orig_ctx;
  1790. // These hyperparameters are not exposed in GGUF, because all
  1791. // existing YaRN models use the same values for them.
  1792. float yarn_ext_factor;
  1793. float yarn_attn_factor;
  1794. float yarn_beta_fast;
  1795. float yarn_beta_slow;
  1796. float defrag_thold;
  1797. bool embeddings;
  1798. bool causal_attn;
  1799. bool offload_kqv;
  1800. bool flash_attn;
  1801. enum llama_pooling_type pooling_type;
  1802. ggml_backend_sched_eval_callback cb_eval;
  1803. void * cb_eval_user_data;
  1804. };
  1805. struct llama_layer {
  1806. // normalization
  1807. struct ggml_tensor * attn_norm;
  1808. struct ggml_tensor * attn_norm_b;
  1809. struct ggml_tensor * attn_norm_2;
  1810. struct ggml_tensor * attn_norm_2_b;
  1811. struct ggml_tensor * attn_q_norm;
  1812. struct ggml_tensor * attn_q_norm_b;
  1813. struct ggml_tensor * attn_k_norm;
  1814. struct ggml_tensor * attn_k_norm_b;
  1815. struct ggml_tensor * attn_out_norm;
  1816. struct ggml_tensor * attn_out_norm_b;
  1817. struct ggml_tensor * attn_q_a_norm;
  1818. struct ggml_tensor * attn_kv_a_norm;
  1819. // attention
  1820. struct ggml_tensor * wq;
  1821. struct ggml_tensor * wk;
  1822. struct ggml_tensor * wv;
  1823. struct ggml_tensor * wo;
  1824. struct ggml_tensor * wqkv;
  1825. struct ggml_tensor * wq_a;
  1826. struct ggml_tensor * wq_b;
  1827. struct ggml_tensor * wkv_a_mqa;
  1828. struct ggml_tensor * wkv_b;
  1829. // attention bias
  1830. struct ggml_tensor * bq;
  1831. struct ggml_tensor * bk;
  1832. struct ggml_tensor * bv;
  1833. struct ggml_tensor * bo;
  1834. struct ggml_tensor * bqkv;
  1835. // normalization
  1836. struct ggml_tensor * ffn_norm;
  1837. struct ggml_tensor * ffn_norm_b;
  1838. struct ggml_tensor * layer_out_norm;
  1839. struct ggml_tensor * layer_out_norm_b;
  1840. struct ggml_tensor * ffn_norm_exps;
  1841. // ff
  1842. struct ggml_tensor * ffn_gate; // w1
  1843. struct ggml_tensor * ffn_down; // w2
  1844. struct ggml_tensor * ffn_up; // w3
  1845. // ff MoE
  1846. struct ggml_tensor * ffn_gate_inp;
  1847. struct ggml_tensor * ffn_gate_exps;
  1848. struct ggml_tensor * ffn_down_exps;
  1849. struct ggml_tensor * ffn_up_exps ;
  1850. // ff shared expert (shexp)
  1851. struct ggml_tensor * ffn_gate_inp_shexp;
  1852. struct ggml_tensor * ffn_gate_shexp;
  1853. struct ggml_tensor * ffn_down_shexp;
  1854. struct ggml_tensor * ffn_up_shexp;
  1855. // ff bias
  1856. struct ggml_tensor * ffn_gate_b = nullptr;
  1857. struct ggml_tensor * ffn_down_b = nullptr; // b2
  1858. struct ggml_tensor * ffn_up_b = nullptr; // b3
  1859. struct ggml_tensor * ffn_act;
  1860. // mamba proj
  1861. struct ggml_tensor * ssm_in;
  1862. struct ggml_tensor * ssm_x;
  1863. struct ggml_tensor * ssm_dt;
  1864. struct ggml_tensor * ssm_out;
  1865. // mamba
  1866. struct ggml_tensor * ssm_conv1d;
  1867. struct ggml_tensor * ssm_a;
  1868. struct ggml_tensor * ssm_d;
  1869. // mamba bias
  1870. struct ggml_tensor * ssm_conv1d_b;
  1871. struct ggml_tensor * ssm_dt_b;
  1872. // long rope factors
  1873. struct ggml_tensor * rope_long = nullptr;
  1874. struct ggml_tensor * rope_short = nullptr;
  1875. };
  1876. struct llama_kv_cell {
  1877. llama_pos pos = -1;
  1878. llama_pos delta = 0;
  1879. int32_t src = 0; // used by recurrent state models to copy states
  1880. std::set<llama_seq_id> seq_id;
  1881. bool has_seq_id(const llama_seq_id & id) const {
  1882. return seq_id.find(id) != seq_id.end();
  1883. }
  1884. bool is_empty() const {
  1885. return seq_id.empty();
  1886. }
  1887. bool is_same_seq(const llama_kv_cell & other) const {
  1888. return seq_id == other.seq_id;
  1889. }
  1890. };
  1891. // ring-buffer of cached KV data
  1892. struct llama_kv_cache {
  1893. bool has_shift = false;
  1894. bool do_defrag = false;
  1895. bool do_copy = false;
  1896. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  1897. bool v_trans = true; // the value tensor is transposed
  1898. // Note: The value of head isn't only used to optimize searching
  1899. // for a free KV slot. llama_decode_internal also uses it, so it
  1900. // cannot be freely changed after a slot has been allocated.
  1901. uint32_t head = 0;
  1902. uint32_t size = 0;
  1903. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1904. // computed before each graph build
  1905. uint32_t n = 0;
  1906. ggml_type type_k = GGML_TYPE_F16;
  1907. ggml_type type_v = GGML_TYPE_F16;
  1908. std::vector<llama_kv_cell> cells;
  1909. std::vector<struct ggml_tensor *> k_l; // per layer
  1910. std::vector<struct ggml_tensor *> v_l;
  1911. std::vector<struct ggml_context *> ctxs;
  1912. std::vector<ggml_backend_buffer_t> bufs;
  1913. size_t total_size() const {
  1914. size_t size = 0;
  1915. for (ggml_backend_buffer_t buf : bufs) {
  1916. size += ggml_backend_buffer_get_size(buf);
  1917. }
  1918. return size;
  1919. }
  1920. ~llama_kv_cache() {
  1921. for (struct ggml_context * ctx : ctxs) {
  1922. ggml_free(ctx);
  1923. }
  1924. for (ggml_backend_buffer_t buf : bufs) {
  1925. ggml_backend_buffer_free(buf);
  1926. }
  1927. }
  1928. };
  1929. struct llama_control_vector {
  1930. std::vector<struct ggml_tensor *> tensors; // per layer
  1931. std::vector<struct ggml_context *> ctxs;
  1932. std::vector<ggml_backend_buffer_t> bufs;
  1933. int32_t layer_start = -1;
  1934. int32_t layer_end = -1;
  1935. ggml_tensor * tensor_for(int il) const {
  1936. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1937. return nullptr;
  1938. }
  1939. return tensors[il];
  1940. }
  1941. ~llama_control_vector() {
  1942. for (struct ggml_context * ctx : ctxs) {
  1943. ggml_free(ctx);
  1944. }
  1945. for (ggml_backend_buffer_t buf : bufs) {
  1946. ggml_backend_buffer_free(buf);
  1947. }
  1948. }
  1949. };
  1950. struct llama_vocab {
  1951. using id = int32_t;
  1952. using token = std::string;
  1953. using ttype = llama_token_type;
  1954. struct token_data {
  1955. token text;
  1956. float score;
  1957. ttype type;
  1958. };
  1959. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1960. enum llama_vocab_pre_type type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1961. std::unordered_map<token, id> token_to_id;
  1962. std::vector<token_data> id_to_token;
  1963. std::vector<id> cache_special_tokens;
  1964. std::vector<token> cache_token_to_piece; // llama_token_to_piece(special = false);
  1965. std::vector<token> cache_token_to_piece_special; // llama_token_to_piece(special = true);
  1966. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1967. // default LLaMA special tokens
  1968. id special_bos_id = 1;
  1969. id special_eos_id = 2;
  1970. id special_unk_id = 0;
  1971. id special_sep_id = -1;
  1972. id special_pad_id = -1;
  1973. id special_cls_id = -1;
  1974. id special_mask_id = -1;
  1975. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1976. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1977. id linefeed_id = 13;
  1978. id special_prefix_id = -1;
  1979. id special_suffix_id = -1;
  1980. id special_middle_id = -1;
  1981. id special_eot_id = -1; // TODO: move above after "eos_id", and here add "file separator" token
  1982. bool add_space_prefix = true;
  1983. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1984. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1985. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1986. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1987. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1988. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1989. if (it == bpe_ranks.end()) {
  1990. return -1;
  1991. }
  1992. return it->second;
  1993. }
  1994. };
  1995. struct llama_model {
  1996. e_model type = MODEL_UNKNOWN;
  1997. llm_arch arch = LLM_ARCH_UNKNOWN;
  1998. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1999. std::string name = "n/a";
  2000. llama_hparams hparams = {};
  2001. llama_vocab vocab;
  2002. struct ggml_tensor * tok_embd;
  2003. struct ggml_tensor * type_embd;
  2004. struct ggml_tensor * pos_embd;
  2005. struct ggml_tensor * tok_norm;
  2006. struct ggml_tensor * tok_norm_b;
  2007. struct ggml_tensor * output_norm;
  2008. struct ggml_tensor * output_norm_b;
  2009. struct ggml_tensor * output;
  2010. struct ggml_tensor * output_b;
  2011. std::vector<llama_layer> layers;
  2012. llama_split_mode split_mode;
  2013. int main_gpu;
  2014. int n_gpu_layers;
  2015. std::vector<std::string> rpc_servers;
  2016. // gguf metadata
  2017. std::unordered_map<std::string, std::string> gguf_kv;
  2018. // layer -> buffer type mapping
  2019. struct layer_buft {
  2020. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  2021. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  2022. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  2023. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  2024. ggml_backend_buffer_type_t buft; // everything else
  2025. };
  2026. layer_buft buft_input;
  2027. layer_buft buft_output;
  2028. std::vector<layer_buft> buft_layer;
  2029. // contexts where the model tensors metadata is stored
  2030. std::vector<struct ggml_context *> ctxs;
  2031. // the model memory buffers for the tensor data
  2032. std::vector<ggml_backend_buffer_t> bufs;
  2033. // model memory mapped files
  2034. llama_mmaps mappings;
  2035. // objects representing data potentially being locked in memory
  2036. llama_mlocks mlock_bufs;
  2037. llama_mlocks mlock_mmaps;
  2038. // for quantize-stats only
  2039. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  2040. int64_t t_load_us = 0;
  2041. int64_t t_start_us = 0;
  2042. ~llama_model() {
  2043. for (struct ggml_context * ctx : ctxs) {
  2044. ggml_free(ctx);
  2045. }
  2046. for (ggml_backend_buffer_t buf : bufs) {
  2047. #ifdef GGML_USE_CUDA
  2048. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  2049. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  2050. }
  2051. #endif
  2052. ggml_backend_buffer_free(buf);
  2053. }
  2054. }
  2055. };
  2056. struct llama_context {
  2057. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  2058. ~llama_context() {
  2059. ggml_backend_sched_free(sched);
  2060. for (ggml_backend_t backend : backends) {
  2061. ggml_backend_free(backend);
  2062. }
  2063. ggml_backend_buffer_free(buf_output);
  2064. }
  2065. llama_cparams cparams;
  2066. std::vector<ggml_backend_t> backends;
  2067. #ifdef GGML_USE_METAL
  2068. ggml_backend_t backend_metal = nullptr;
  2069. #endif
  2070. ggml_backend_t backend_cpu = nullptr;
  2071. const llama_model & model;
  2072. // key + value cache for the self attention
  2073. struct llama_kv_cache kv_self;
  2074. std::mt19937 rng;
  2075. bool has_evaluated_once = false;
  2076. int64_t t_start_us;
  2077. int64_t t_load_us;
  2078. int64_t t_sample_us = 0;
  2079. int64_t t_p_eval_us = 0;
  2080. int64_t t_eval_us = 0;
  2081. int64_t t_compute_start_us = 0;
  2082. int64_t n_queued_tokens = 0;
  2083. int32_t n_sample = 0; // number of tokens sampled
  2084. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  2085. int32_t n_eval = 0; // number of eval calls
  2086. // host buffer for the model output (logits and embeddings)
  2087. ggml_backend_buffer_t buf_output = nullptr;
  2088. // decode output (2-dimensional array: [n_outputs][n_vocab])
  2089. size_t logits_size = 0; // capacity (of floats) for logits
  2090. float * logits = nullptr;
  2091. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  2092. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  2093. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  2094. bool logits_all = false;
  2095. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  2096. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  2097. size_t embd_size = 0; // capacity (of floats) for embeddings
  2098. float * embd = nullptr;
  2099. // sequence embeddings output (map of [n_embd] vectors)
  2100. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2101. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2102. // memory buffers used to evaluate the model
  2103. std::vector<uint8_t> buf_compute_meta;
  2104. ggml_backend_sched_t sched = nullptr;
  2105. ggml_abort_callback abort_callback = nullptr;
  2106. void * abort_callback_data = nullptr;
  2107. // input tensors
  2108. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2109. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2110. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2111. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2112. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2113. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2114. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2115. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2116. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2117. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2118. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2119. // control vectors
  2120. struct llama_control_vector cvec;
  2121. };
  2122. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2123. ggml_backend_buffer_type_t buft = nullptr;
  2124. #ifdef GGML_USE_RPC
  2125. std::string endpoint = model.rpc_servers[gpu];
  2126. buft = ggml_backend_rpc_buffer_type(endpoint.c_str());
  2127. #elif defined(GGML_USE_METAL)
  2128. buft = ggml_backend_metal_buffer_type();
  2129. #elif defined(GGML_USE_CUDA)
  2130. buft = ggml_backend_cuda_buffer_type(gpu);
  2131. #elif defined(GGML_USE_VULKAN)
  2132. buft = ggml_backend_vk_buffer_type(gpu);
  2133. #elif defined(GGML_USE_SYCL)
  2134. buft = ggml_backend_sycl_buffer_type(gpu);
  2135. #elif defined(GGML_USE_CLBLAST)
  2136. buft = ggml_backend_opencl_buffer_type();
  2137. #elif defined(GGML_USE_KOMPUTE)
  2138. buft = ggml_backend_kompute_buffer_type(gpu);
  2139. if (buft == nullptr) {
  2140. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2141. }
  2142. #endif
  2143. if (buft == nullptr) {
  2144. buft = llama_default_buffer_type_cpu(true);
  2145. }
  2146. return buft;
  2147. GGML_UNUSED(model);
  2148. GGML_UNUSED(gpu);
  2149. }
  2150. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2151. ggml_backend_buffer_type_t buft = nullptr;
  2152. #ifdef GGML_USE_CUDA
  2153. if (ggml_backend_cuda_get_device_count() > 1) {
  2154. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2155. }
  2156. #endif
  2157. #ifdef GGML_USE_SYCL
  2158. if (ggml_backend_sycl_get_device_count() > 1) {
  2159. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2160. }
  2161. #endif
  2162. if (buft == nullptr) {
  2163. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2164. }
  2165. return buft;
  2166. GGML_UNUSED(tensor_split);
  2167. }
  2168. static size_t llama_get_device_count(const llama_model & model) {
  2169. #if defined(GGML_USE_RPC)
  2170. return model.rpc_servers.size();
  2171. #elif defined(GGML_USE_CUDA)
  2172. return ggml_backend_cuda_get_device_count();
  2173. #elif defined(GGML_USE_SYCL)
  2174. return ggml_backend_sycl_get_device_count();
  2175. #elif defined(GGML_USE_VULKAN)
  2176. return ggml_backend_vk_get_device_count();
  2177. #else
  2178. return 1;
  2179. #endif
  2180. GGML_UNUSED(model);
  2181. }
  2182. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2183. #if defined(GGML_USE_RPC)
  2184. size_t total;
  2185. size_t free;
  2186. std::string endpoint = model.rpc_servers[device];
  2187. ggml_backend_rpc_get_device_memory(endpoint.c_str(), &free, &total);
  2188. return free;
  2189. #elif defined(GGML_USE_CUDA)
  2190. size_t total;
  2191. size_t free;
  2192. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2193. return free;
  2194. #elif defined(GGML_USE_SYCL)
  2195. size_t total;
  2196. size_t free;
  2197. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2198. return free;
  2199. #elif defined(GGML_USE_VULKAN)
  2200. size_t total;
  2201. size_t free;
  2202. ggml_backend_vk_get_device_memory(device, &free, &total);
  2203. return free;
  2204. #else
  2205. return 1;
  2206. #endif
  2207. GGML_UNUSED(model);
  2208. GGML_UNUSED(device);
  2209. }
  2210. //
  2211. // kv cache helpers
  2212. //
  2213. static bool llama_kv_cache_init(
  2214. struct llama_kv_cache & cache,
  2215. const llama_context * ctx,
  2216. ggml_type type_k,
  2217. ggml_type type_v,
  2218. uint32_t kv_size,
  2219. bool offload) {
  2220. const llama_model & model = ctx->model;
  2221. const llama_cparams & cparams = ctx->cparams;
  2222. const struct llama_hparams & hparams = model.hparams;
  2223. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  2224. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  2225. const int64_t n_layer = hparams.n_layer;
  2226. cache.has_shift = false;
  2227. // TODO: find a nicer way to add other recurrent model architectures
  2228. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2229. cache.v_trans = !cparams.flash_attn;
  2230. // TODO: support mixed recurrent Transformer architectures
  2231. // NOTE: (!a || b) is a logical implication (a -> b)
  2232. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  2233. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  2234. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  2235. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  2236. cache.head = 0;
  2237. cache.size = kv_size;
  2238. cache.used = 0;
  2239. cache.type_k = type_k;
  2240. cache.type_v = type_v;
  2241. cache.cells.clear();
  2242. cache.cells.resize(kv_size);
  2243. if (cache.recurrent) {
  2244. // init state copy sources
  2245. for (uint32_t i = 0; i < cache.size; ++i) {
  2246. cache.cells[i].src = i;
  2247. }
  2248. }
  2249. #ifdef GGML_USE_CLBLAST
  2250. offload = false;
  2251. #endif
  2252. // count used buffer types
  2253. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2254. if (offload) {
  2255. for (int64_t i = 0; i < n_layer; ++i) {
  2256. buft_layer_count[model.buft_layer[i].buft]++;
  2257. }
  2258. } else {
  2259. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2260. }
  2261. // create a context for each buffer type
  2262. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2263. for (auto & it : buft_layer_count) {
  2264. int n_layers = it.second;
  2265. struct ggml_init_params params = {
  2266. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2267. /*.mem_buffer =*/ NULL,
  2268. /*.no_alloc =*/ true,
  2269. };
  2270. ggml_context * ctx = ggml_init(params);
  2271. if (!ctx) {
  2272. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2273. return false;
  2274. }
  2275. ctx_map[it.first] = ctx;
  2276. cache.ctxs.push_back(ctx);
  2277. }
  2278. cache.k_l.reserve(n_layer);
  2279. cache.v_l.reserve(n_layer);
  2280. for (int i = 0; i < (int) n_layer; i++) {
  2281. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2282. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2283. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2284. ggml_format_name(k, "cache_k_l%d", i);
  2285. ggml_format_name(v, "cache_v_l%d", i);
  2286. cache.k_l.push_back(k);
  2287. cache.v_l.push_back(v);
  2288. }
  2289. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2290. for (auto it : ctx_map) {
  2291. ggml_backend_buffer_type_t buft = it.first;
  2292. ggml_context * ctx = it.second;
  2293. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2294. if (!buf) {
  2295. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2296. return false;
  2297. }
  2298. ggml_backend_buffer_clear(buf, 0);
  2299. 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);
  2300. cache.bufs.push_back(buf);
  2301. }
  2302. return true;
  2303. }
  2304. // find an empty slot of size "n_tokens" in the cache
  2305. // updates the cache head
  2306. // Note: On success, it's important that cache.head points
  2307. // to the first cell of the slot.
  2308. static bool llama_kv_cache_find_slot(
  2309. struct llama_kv_cache & cache,
  2310. const struct llama_batch & batch) {
  2311. const uint32_t n_tokens = batch.n_tokens;
  2312. if (cache.recurrent) {
  2313. // For recurrent state architectures (like Mamba),
  2314. // each KV cache cell can store the state for a whole sequence.
  2315. llama_seq_id min = cache.size - 1;
  2316. llama_seq_id max = 0;
  2317. for (uint32_t i = 0; i < n_tokens; ++i) {
  2318. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2319. llama_seq_id seq_id = batch.seq_id[i][j];
  2320. // make sure it's a valid seq_id
  2321. if ((uint32_t) seq_id < cache.size) {
  2322. if (seq_id > max) {
  2323. max = seq_id;
  2324. }
  2325. if (seq_id < min) {
  2326. min = seq_id;
  2327. }
  2328. // Assuming the tokens are in-order
  2329. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2330. // What should happen when the pos backtracks or skips a value?
  2331. // Clearing the state mid-batch would require special-casing which isn't done.
  2332. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2333. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2334. }
  2335. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2336. cache.used += 1;
  2337. }
  2338. cache.cells[seq_id].pos = batch.pos[i];
  2339. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2340. } else {
  2341. // too big seq_id
  2342. // TODO: would it be possible to resize the KV cache size instead?
  2343. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2344. return false;
  2345. }
  2346. }
  2347. }
  2348. // allow getting the range of used cells, from head to head + n
  2349. cache.head = min;
  2350. cache.n = max - min + 1;
  2351. // sanity check
  2352. return max >= min;
  2353. }
  2354. // otherwise, one cell per token.
  2355. if (n_tokens > cache.size) {
  2356. LLAMA_LOG_ERROR("%s: n_tokens=%d > cache.size=%d\n", __func__, n_tokens, cache.size);
  2357. return false;
  2358. }
  2359. uint32_t n_tested = 0;
  2360. while (true) {
  2361. if (cache.head + n_tokens > cache.size) {
  2362. n_tested += cache.size - cache.head;
  2363. cache.head = 0;
  2364. continue;
  2365. }
  2366. bool found = true;
  2367. for (uint32_t i = 0; i < n_tokens; i++) {
  2368. if (cache.cells[cache.head + i].pos >= 0) {
  2369. found = false;
  2370. cache.head += i + 1;
  2371. n_tested += i + 1;
  2372. break;
  2373. }
  2374. }
  2375. if (found) {
  2376. break;
  2377. }
  2378. if (n_tested >= cache.size) {
  2379. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2380. return false;
  2381. }
  2382. }
  2383. for (uint32_t i = 0; i < n_tokens; i++) {
  2384. cache.cells[cache.head + i].pos = batch.pos[i];
  2385. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2386. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2387. }
  2388. }
  2389. cache.used += n_tokens;
  2390. return true;
  2391. }
  2392. // find how many cells are currently in use
  2393. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2394. for (uint32_t i = cache.size; i > 0; --i) {
  2395. const llama_kv_cell & cell = cache.cells[i - 1];
  2396. if (cell.pos >= 0 && !cell.is_empty()) {
  2397. return i;
  2398. }
  2399. }
  2400. return 0;
  2401. }
  2402. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2403. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2404. cache.cells[i].pos = -1;
  2405. cache.cells[i].seq_id.clear();
  2406. }
  2407. cache.head = 0;
  2408. cache.used = 0;
  2409. for (auto & buf : cache.bufs) {
  2410. ggml_backend_buffer_clear(buf, 0);
  2411. }
  2412. }
  2413. static bool llama_kv_cache_seq_rm(
  2414. struct llama_kv_cache & cache,
  2415. llama_seq_id seq_id,
  2416. llama_pos p0,
  2417. llama_pos p1) {
  2418. uint32_t new_head = cache.size;
  2419. if (p0 < 0) p0 = 0;
  2420. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2421. // models like Mamba can't have a state partially erased
  2422. if (cache.recurrent) {
  2423. if (seq_id >= (int64_t) cache.size) {
  2424. // could be fatal
  2425. return false;
  2426. }
  2427. if (0 <= seq_id) {
  2428. // partial intersection is invalid
  2429. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2430. return false;
  2431. }
  2432. } else {
  2433. // seq_id is negative, then the range should include everything or nothing
  2434. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2435. return false;
  2436. }
  2437. }
  2438. }
  2439. for (uint32_t i = 0; i < cache.size; ++i) {
  2440. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2441. if (seq_id < 0) {
  2442. cache.cells[i].seq_id.clear();
  2443. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2444. cache.cells[i].seq_id.erase(seq_id);
  2445. } else {
  2446. continue;
  2447. }
  2448. if (cache.cells[i].is_empty()) {
  2449. // keep count of the number of used cells
  2450. if (cache.cells[i].pos >= 0) cache.used--;
  2451. cache.cells[i].pos = -1;
  2452. if (new_head == cache.size) new_head = i;
  2453. }
  2454. }
  2455. }
  2456. // If we freed up a slot, set head to it so searching can start there.
  2457. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2458. return true;
  2459. }
  2460. static void llama_kv_cache_seq_cp(
  2461. struct llama_kv_cache & cache,
  2462. llama_seq_id seq_id_src,
  2463. llama_seq_id seq_id_dst,
  2464. llama_pos p0,
  2465. llama_pos p1) {
  2466. if (p0 < 0) p0 = 0;
  2467. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2468. if (cache.recurrent) {
  2469. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2470. seq_id_src = cache.cells[seq_id_src].src;
  2471. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2472. // intent to "copy from"
  2473. // supports copy chains thanks to taking the source of the source
  2474. cache.cells[seq_id_dst].src = seq_id_src;
  2475. // preserve the "keep or clear" status of the copied sequence
  2476. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2477. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2478. } else {
  2479. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2480. }
  2481. cache.do_copy = true;
  2482. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2483. }
  2484. return;
  2485. }
  2486. // otherwise, this is the KV cache of a Transformer-like model
  2487. cache.head = 0;
  2488. for (uint32_t i = 0; i < cache.size; ++i) {
  2489. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2490. cache.cells[i].seq_id.insert(seq_id_dst);
  2491. }
  2492. }
  2493. }
  2494. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2495. uint32_t new_head = cache.size;
  2496. for (uint32_t i = 0; i < cache.size; ++i) {
  2497. if (!cache.cells[i].has_seq_id(seq_id)) {
  2498. if (cache.cells[i].pos >= 0) cache.used--;
  2499. cache.cells[i].pos = -1;
  2500. cache.cells[i].seq_id.clear();
  2501. if (new_head == cache.size) new_head = i;
  2502. } else {
  2503. cache.cells[i].seq_id.clear();
  2504. cache.cells[i].seq_id.insert(seq_id);
  2505. }
  2506. }
  2507. // If we freed up a slot, set head to it so searching can start there.
  2508. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2509. }
  2510. static void llama_kv_cache_seq_add(
  2511. struct llama_kv_cache & cache,
  2512. llama_seq_id seq_id,
  2513. llama_pos p0,
  2514. llama_pos p1,
  2515. llama_pos delta) {
  2516. uint32_t new_head = cache.size;
  2517. if (p0 < 0) p0 = 0;
  2518. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2519. if (cache.recurrent) {
  2520. // for Mamba-like models, only the pos needs to be shifted
  2521. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2522. llama_kv_cell & cell = cache.cells[seq_id];
  2523. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2524. cell.pos += delta;
  2525. }
  2526. }
  2527. return;
  2528. }
  2529. for (uint32_t i = 0; i < cache.size; ++i) {
  2530. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2531. cache.has_shift = true;
  2532. cache.cells[i].pos += delta;
  2533. cache.cells[i].delta += delta;
  2534. if (cache.cells[i].pos < 0) {
  2535. if (!cache.cells[i].is_empty()) {
  2536. cache.used--;
  2537. }
  2538. cache.cells[i].pos = -1;
  2539. cache.cells[i].seq_id.clear();
  2540. if (new_head == cache.size) {
  2541. new_head = i;
  2542. }
  2543. }
  2544. }
  2545. }
  2546. // If we freed up a slot, set head to it so searching can start there.
  2547. // Otherwise we just start the next search from the beginning.
  2548. cache.head = new_head != cache.size ? new_head : 0;
  2549. }
  2550. static void llama_kv_cache_seq_div(
  2551. struct llama_kv_cache & cache,
  2552. llama_seq_id seq_id,
  2553. llama_pos p0,
  2554. llama_pos p1,
  2555. int d) {
  2556. if (p0 < 0) p0 = 0;
  2557. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2558. if (cache.recurrent) {
  2559. // for Mamba-like models, only the pos needs to be changed
  2560. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2561. llama_kv_cell & cell = cache.cells[seq_id];
  2562. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2563. cell.pos /= d;
  2564. }
  2565. }
  2566. return;
  2567. }
  2568. for (uint32_t i = 0; i < cache.size; ++i) {
  2569. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2570. cache.has_shift = true;
  2571. {
  2572. llama_pos p_old = cache.cells[i].pos;
  2573. cache.cells[i].pos /= d;
  2574. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2575. }
  2576. }
  2577. }
  2578. }
  2579. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2580. llama_pos result = 0;
  2581. for (uint32_t i = 0; i < cache.size; ++i) {
  2582. if (cache.cells[i].has_seq_id(seq_id)) {
  2583. result = std::max(result, cache.cells[i].pos);
  2584. }
  2585. }
  2586. return result;
  2587. }
  2588. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2589. cache.do_defrag = true;
  2590. }
  2591. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  2592. // the FA kernels require padding to avoid extra runtime boundary checks
  2593. return cparams.flash_attn ? 256u : 32u;
  2594. }
  2595. //
  2596. // model loading and saving
  2597. //
  2598. enum llama_fver {
  2599. GGUF_FILE_VERSION_V1 = 1,
  2600. GGUF_FILE_VERSION_V2 = 2,
  2601. GGUF_FILE_VERSION_V3 = 3,
  2602. };
  2603. static const char * llama_file_version_name(llama_fver version) {
  2604. switch (version) {
  2605. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2606. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2607. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2608. }
  2609. return "unknown";
  2610. }
  2611. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2612. char buf[256];
  2613. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2614. for (size_t i = 1; i < ne.size(); i++) {
  2615. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2616. }
  2617. return buf;
  2618. }
  2619. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2620. char buf[256];
  2621. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2622. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2623. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2624. }
  2625. return buf;
  2626. }
  2627. namespace GGUFMeta {
  2628. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2629. struct GKV_Base_Type {
  2630. static constexpr gguf_type gt = gt_;
  2631. static T getter(const gguf_context * ctx, const int kid) {
  2632. return gfun(ctx, kid);
  2633. }
  2634. };
  2635. template<typename T> struct GKV_Base;
  2636. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2637. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2638. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2639. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2640. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2641. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2642. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2643. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2644. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2645. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2646. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2647. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2648. template<> struct GKV_Base<std::string> {
  2649. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2650. static std::string getter(const gguf_context * ctx, const int kid) {
  2651. return gguf_get_val_str(ctx, kid);
  2652. }
  2653. };
  2654. struct ArrayInfo {
  2655. const gguf_type gt;
  2656. const size_t length;
  2657. const void * data;
  2658. };
  2659. template<> struct GKV_Base<ArrayInfo> {
  2660. public:
  2661. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2662. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2663. return ArrayInfo {
  2664. gguf_get_arr_type(ctx, k),
  2665. size_t(gguf_get_arr_n(ctx, k)),
  2666. gguf_get_arr_data(ctx, k),
  2667. };
  2668. }
  2669. };
  2670. template<typename T>
  2671. class GKV : public GKV_Base<T> {
  2672. GKV() = delete;
  2673. public:
  2674. static T get_kv(const gguf_context * ctx, const int k) {
  2675. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2676. if (kt != GKV::gt) {
  2677. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2678. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2679. }
  2680. return GKV::getter(ctx, k);
  2681. }
  2682. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2683. switch (ty) {
  2684. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2685. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2686. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2687. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  2688. }
  2689. return "unknown";
  2690. }
  2691. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2692. if (!ovrd) { return false; }
  2693. if (ovrd->tag == expected_type) {
  2694. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2695. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2696. switch (ovrd->tag) {
  2697. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2698. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  2699. } break;
  2700. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2701. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  2702. } break;
  2703. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2704. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  2705. } break;
  2706. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  2707. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  2708. } break;
  2709. default:
  2710. // Shouldn't be possible to end up here, but just in case...
  2711. throw std::runtime_error(
  2712. format("Unsupported attempt to override %s type for metadata key %s\n",
  2713. override_type_to_str(ovrd->tag), ovrd->key));
  2714. }
  2715. return true;
  2716. }
  2717. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2718. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2719. return false;
  2720. }
  2721. template<typename OT>
  2722. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2723. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2724. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2725. target = ovrd->val_bool;
  2726. return true;
  2727. }
  2728. return false;
  2729. }
  2730. template<typename OT>
  2731. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2732. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2733. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2734. target = ovrd->val_i64;
  2735. return true;
  2736. }
  2737. return false;
  2738. }
  2739. template<typename OT>
  2740. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2741. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2742. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2743. target = ovrd->val_f64;
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. template<typename OT>
  2749. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2750. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2751. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  2752. target = ovrd->val_str;
  2753. return true;
  2754. }
  2755. return false;
  2756. }
  2757. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2758. if (try_override<T>(target, ovrd)) {
  2759. return true;
  2760. }
  2761. if (k < 0) { return false; }
  2762. target = get_kv(ctx, k);
  2763. return true;
  2764. }
  2765. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2766. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2767. }
  2768. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2769. return set(ctx, key.c_str(), target, ovrd);
  2770. }
  2771. };
  2772. }
  2773. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2774. struct llama_model_loader {
  2775. int n_kv = 0;
  2776. int n_tensors = 0;
  2777. int n_created = 0;
  2778. int64_t n_elements = 0;
  2779. size_t n_bytes = 0;
  2780. bool use_mmap = false;
  2781. bool check_tensors;
  2782. llama_files files;
  2783. llama_ftype ftype;
  2784. llama_fver fver;
  2785. llama_mmaps mappings;
  2786. // Holds information on a model weight
  2787. struct llama_tensor_weight {
  2788. uint16_t idx; // source file index
  2789. size_t offs; // tensor data offset in the original file
  2790. ggml_tensor * tensor;
  2791. 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) {
  2792. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2793. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2794. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  2795. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  2796. }
  2797. }
  2798. };
  2799. std::vector<llama_tensor_weight> weights;
  2800. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2801. struct gguf_context * meta = NULL;
  2802. std::vector<ggml_context *> contexts;
  2803. std::string arch_name;
  2804. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2805. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  2806. int trace = 0;
  2807. if (getenv("LLAMA_TRACE")) {
  2808. trace = atoi(getenv("LLAMA_TRACE"));
  2809. }
  2810. if (param_overrides_p != nullptr) {
  2811. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2812. kv_overrides.insert({std::string(p->key), *p});
  2813. }
  2814. }
  2815. struct ggml_context * ctx = NULL;
  2816. struct gguf_init_params params = {
  2817. /*.no_alloc = */ true,
  2818. /*.ctx = */ &ctx,
  2819. };
  2820. meta = gguf_init_from_file(fname.c_str(), params);
  2821. if (!meta) {
  2822. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2823. }
  2824. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2825. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2826. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2827. contexts.emplace_back(ctx);
  2828. // Save tensors data offset of the main file.
  2829. // For subsidiary files, `meta` tensor data offset must not be used,
  2830. // so we build a unified tensors index for weights.
  2831. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2832. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  2833. }
  2834. uint16_t n_split = 0;
  2835. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2836. // Load additional GGML contexts
  2837. if (n_split > 1) {
  2838. uint16_t idx = 0;
  2839. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2840. if (idx != 0) {
  2841. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2842. }
  2843. char split_prefix[PATH_MAX] = {0};
  2844. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2845. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2846. }
  2847. if (trace > 0) {
  2848. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2849. }
  2850. char split_path[PATH_MAX] = {0};
  2851. for (idx = 1; idx < n_split; idx++) {
  2852. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2853. struct gguf_init_params split_params = {
  2854. /*.no_alloc = */ true,
  2855. /*.ctx = */ &ctx,
  2856. };
  2857. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2858. if (!ctx_gguf) {
  2859. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2860. }
  2861. files.emplace_back(new llama_file(split_path, "rb"));
  2862. contexts.emplace_back(ctx);
  2863. // Save tensors data offset info of the shard.
  2864. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2865. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  2866. }
  2867. gguf_free(ctx_gguf);
  2868. }
  2869. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2870. // sanity check
  2871. {
  2872. const int n_tensors_loaded = (int) weights.size();
  2873. if (n_tensors != n_tensors_loaded) {
  2874. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2875. }
  2876. }
  2877. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2878. }
  2879. n_kv = gguf_get_n_kv(meta);
  2880. n_tensors = weights.size();
  2881. fver = (enum llama_fver) gguf_get_version(meta);
  2882. std::set<std::string> tensor_names;
  2883. for (auto & w : weights) {
  2884. n_elements += ggml_nelements(w.tensor);
  2885. n_bytes += ggml_nbytes(w.tensor);
  2886. // make sure there is no duplicated tensor names
  2887. const std::string name(w.tensor->name);
  2888. auto found = tensor_names.find(name);
  2889. if (found != tensor_names.end()) {
  2890. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  2891. }
  2892. tensor_names.insert(name);
  2893. }
  2894. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2895. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2896. // determine file type based on the number of tensors for each quantization and print meta data
  2897. // TODO: make optional
  2898. {
  2899. std::map<enum ggml_type, uint32_t> n_type;
  2900. uint32_t n_type_max = 0;
  2901. enum ggml_type type_max = GGML_TYPE_F32;
  2902. for (int i = 0; i < n_tensors; i++) {
  2903. const ggml_tensor * tensor = weights.at(i).tensor;
  2904. enum ggml_type type = tensor->type;
  2905. n_type[type]++;
  2906. if (n_type_max < n_type[type]) {
  2907. n_type_max = n_type[type];
  2908. type_max = type;
  2909. }
  2910. if (trace > 0) {
  2911. const uint16_t sid = weights.at(i).idx;
  2912. 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());
  2913. }
  2914. }
  2915. switch (type_max) {
  2916. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2917. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2918. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  2919. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2920. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2921. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2922. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2923. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2924. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2925. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2926. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2927. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2928. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2929. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2930. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2931. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2932. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2933. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2934. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2935. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2936. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2937. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2938. default:
  2939. {
  2940. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2941. ftype = LLAMA_FTYPE_ALL_F32;
  2942. } break;
  2943. }
  2944. // this is a way to mark that we have "guessed" the file type
  2945. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2946. {
  2947. const int kid = gguf_find_key(meta, "general.file_type");
  2948. if (kid >= 0) {
  2949. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2950. }
  2951. }
  2952. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2953. for (int i = 0; i < n_kv; i++) {
  2954. const char * name = gguf_get_key(meta, i);
  2955. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2956. const std::string type_name =
  2957. type == GGUF_TYPE_ARRAY
  2958. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2959. : gguf_type_name(type);
  2960. std::string value = gguf_kv_to_str(meta, i);
  2961. const size_t MAX_VALUE_LEN = 40;
  2962. if (value.size() > MAX_VALUE_LEN) {
  2963. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2964. }
  2965. replace_all(value, "\n", "\\n");
  2966. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2967. }
  2968. // print type counts
  2969. for (auto & kv : n_type) {
  2970. if (kv.second == 0) {
  2971. continue;
  2972. }
  2973. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2974. }
  2975. }
  2976. if (!llama_mmap::SUPPORTED) {
  2977. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2978. use_mmap = false;
  2979. }
  2980. this->use_mmap = use_mmap;
  2981. this->check_tensors = check_tensors;
  2982. }
  2983. ~llama_model_loader() {
  2984. if (meta) {
  2985. gguf_free(meta);
  2986. }
  2987. for (auto * ctx : contexts) {
  2988. ggml_free(ctx);
  2989. }
  2990. }
  2991. template<typename T>
  2992. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2993. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2994. const int kid = gguf_find_key(meta, key.c_str());
  2995. if (kid < 0) {
  2996. if (required) {
  2997. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2998. }
  2999. return false;
  3000. }
  3001. struct GGUFMeta::ArrayInfo arr_info =
  3002. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3003. result = arr_info.length;
  3004. return true;
  3005. }
  3006. template<typename T>
  3007. typename std::enable_if<std::is_integral<T>::value, bool>::type
  3008. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  3009. return get_arr_n(llm_kv(kid), result, required);
  3010. }
  3011. template<typename T>
  3012. bool get_arr(const std::string & key, std::vector<T> & result, const bool required = true) {
  3013. const int kid = gguf_find_key(meta, key.c_str());
  3014. if (kid < 0) {
  3015. if (required) {
  3016. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3017. }
  3018. return false;
  3019. }
  3020. struct GGUFMeta::ArrayInfo arr_info =
  3021. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  3022. if (arr_info.gt != GGUF_TYPE_FLOAT32 && arr_info.gt != GGUF_TYPE_INT32) {
  3023. throw std::runtime_error(format("%s is not a float32 or int32 array", key.c_str()));
  3024. }
  3025. // GGML_ASSERT(gguf_type_size(arr_info.gt) == sizeof(T));
  3026. GGML_ASSERT((arr_info.gt != GGUF_TYPE_FLOAT32 || std::is_same<T, float>::value));
  3027. GGML_ASSERT((arr_info.gt != GGUF_TYPE_INT32 || std::is_same<T, int>::value));
  3028. result.resize(arr_info.length);
  3029. result.assign((const T*)arr_info.data, (const T *)arr_info.data + arr_info.length);
  3030. return true;
  3031. }
  3032. template<typename T>
  3033. bool get_arr(const enum llm_kv kid, T& result, const bool required = true) {
  3034. return get_arr(llm_kv(kid), result, required);
  3035. }
  3036. template<typename T>
  3037. bool get_key(const std::string & key, T & result, const bool required = true) {
  3038. auto it = kv_overrides.find(key);
  3039. const struct llama_model_kv_override * override =
  3040. it != kv_overrides.end() ? &it->second : nullptr;
  3041. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  3042. if (required && !found) {
  3043. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  3044. }
  3045. return found;
  3046. }
  3047. template<typename T>
  3048. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  3049. return get_key(llm_kv(kid), result, required);
  3050. }
  3051. std::string get_arch_name() const {
  3052. return arch_name;
  3053. }
  3054. enum llm_arch get_arch() const {
  3055. return llm_kv.arch;
  3056. }
  3057. const char * get_tensor_name(int i) const {
  3058. return weights.at(i).tensor->name;
  3059. }
  3060. const llama_tensor_weight * get_weight(const char * name) const {
  3061. for (const auto & weight : weights) {
  3062. if (strcmp(name, weight.tensor->name) == 0) {
  3063. return &weight;
  3064. }
  3065. }
  3066. return nullptr;
  3067. }
  3068. const llama_tensor_weight * get_weight(int i) const {
  3069. return get_weight(get_tensor_name(i));
  3070. }
  3071. const llama_tensor_weight & require_weight(const char * name) const {
  3072. const llama_tensor_weight * weight = get_weight(name);
  3073. if (!weight) {
  3074. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3075. }
  3076. return *weight;
  3077. }
  3078. struct ggml_tensor * get_tensor_meta(const char * name) const {
  3079. const auto * weight = get_weight(name);
  3080. if (!weight) {
  3081. return nullptr;
  3082. }
  3083. return weight->tensor;
  3084. }
  3085. struct ggml_tensor * require_tensor_meta(const char * name) const {
  3086. struct ggml_tensor * tensor = get_tensor_meta(name);
  3087. if (!tensor) {
  3088. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  3089. }
  3090. return tensor;
  3091. }
  3092. struct ggml_tensor * get_tensor_meta(int i) const {
  3093. return get_tensor_meta(get_tensor_name(i));
  3094. }
  3095. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur, bool duplicated) {
  3096. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  3097. ggml_set_name(tensor, ggml_get_name(cur));
  3098. if (duplicated) {
  3099. size_data += ggml_nbytes(cur);
  3100. } else {
  3101. n_created++;
  3102. }
  3103. return tensor;
  3104. }
  3105. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  3106. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  3107. if (cur == NULL) {
  3108. if (!required) {
  3109. return NULL;
  3110. }
  3111. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  3112. }
  3113. {
  3114. bool is_ok = true;
  3115. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3116. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  3117. is_ok = false;
  3118. break;
  3119. }
  3120. }
  3121. if (!is_ok) {
  3122. throw std::runtime_error(
  3123. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  3124. __func__, name.c_str(),
  3125. llama_format_tensor_shape(ne).c_str(),
  3126. llama_format_tensor_shape(cur).c_str()));
  3127. }
  3128. }
  3129. return cur;
  3130. }
  3131. static const int TENSOR_NOT_REQUIRED = 1;
  3132. static const int TENSOR_DUPLICATED = 2;
  3133. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, int flags = 0) {
  3134. const struct ggml_tensor * cur = check_tensor_dims(name, ne, !(flags & TENSOR_NOT_REQUIRED));
  3135. if (cur == NULL) {
  3136. return NULL;
  3137. }
  3138. return create_tensor_for(ctx, cur, flags & TENSOR_DUPLICATED);
  3139. }
  3140. 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) {
  3141. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3142. if (cur == NULL) {
  3143. return NULL;
  3144. }
  3145. if (cur->type != base->type) {
  3146. 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)));
  3147. }
  3148. std::array<int64_t, GGML_MAX_DIMS> dims;
  3149. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3150. dims[i] = i < ne.size() ? ne[i] : 1;
  3151. }
  3152. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  3153. dims[0], dims[1], dims[2], dims[3],
  3154. cur->nb[1], cur->nb[2], cur->nb[3],
  3155. offset);
  3156. ggml_set_name(tensor, name.c_str());
  3157. n_created++;
  3158. return tensor;
  3159. }
  3160. void done_getting_tensors() const {
  3161. if (n_created != n_tensors) {
  3162. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  3163. }
  3164. }
  3165. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  3166. if (use_mmap) {
  3167. mappings.reserve(files.size());
  3168. mmaps_used.reserve(files.size());
  3169. for (const auto & file : files) {
  3170. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  3171. mmaps_used.emplace_back(mapping->size, 0);
  3172. if (mlock_mmaps) {
  3173. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  3174. mlock_mmap->init(mapping->addr);
  3175. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  3176. }
  3177. mappings.emplace_back(std::move(mapping));
  3178. }
  3179. }
  3180. // compute the total size of all tensors for progress reporting
  3181. for (auto & w : weights) {
  3182. size_data += ggml_nbytes(w.tensor);
  3183. }
  3184. }
  3185. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  3186. GGML_ASSERT(!mappings.empty());
  3187. const auto & mapping = mappings.at(idx);
  3188. *first = mapping->size;
  3189. *last = 0;
  3190. *addr = mapping->addr;
  3191. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3192. try {
  3193. const auto * weight = get_weight(ggml_get_name(tensor));
  3194. if (!weight) {
  3195. continue;
  3196. }
  3197. if (weight->idx != idx) {
  3198. continue;
  3199. }
  3200. *first = std::min(*first, weight->offs);
  3201. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  3202. } catch(...) {
  3203. // the tensor is not in the model
  3204. }
  3205. }
  3206. }
  3207. // for backwards compatibility, does not support ggml-backend
  3208. void load_data_for(struct ggml_tensor * cur) const {
  3209. const auto & w = require_weight(ggml_get_name(cur));
  3210. if (use_mmap) {
  3211. const auto & mapping = mappings.at(w.idx);
  3212. if (cur->data == nullptr) {
  3213. cur->data = (uint8_t *)mapping->addr + w.offs;
  3214. } else {
  3215. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  3216. }
  3217. } else {
  3218. GGML_ASSERT(cur->data != nullptr);
  3219. GGML_ASSERT(w.idx < files.size());
  3220. const auto & file = files.at(w.idx);
  3221. file->seek(w.offs, SEEK_SET);
  3222. file->read_raw(cur->data, ggml_nbytes(cur));
  3223. }
  3224. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  3225. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3226. }
  3227. }
  3228. size_t size_done = 0;
  3229. size_t size_data = 0;
  3230. std::vector<std::pair<size_t, size_t>> mmaps_used;
  3231. // Returns false if cancelled by progress_callback
  3232. bool load_all_data(
  3233. struct ggml_context * ctx,
  3234. llama_buf_map & bufs_mmap,
  3235. llama_mlocks * lmlocks,
  3236. llama_progress_callback progress_callback,
  3237. void * progress_callback_user_data) {
  3238. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  3239. std::vector<no_init<uint8_t>> read_buf;
  3240. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  3241. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3242. const auto * weight = get_weight(ggml_get_name(cur));
  3243. if (weight == nullptr) {
  3244. // this can happen with split experts models
  3245. continue;
  3246. }
  3247. if (progress_callback) {
  3248. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  3249. return false;
  3250. }
  3251. }
  3252. size_t n_size = ggml_nbytes(cur);
  3253. if (use_mmap) {
  3254. const auto & mapping = mappings.at(weight->idx);
  3255. ggml_backend_buffer_t buf_mmap = nullptr;
  3256. if (bufs_mmap.count(weight->idx)) {
  3257. buf_mmap = bufs_mmap.at(weight->idx);
  3258. }
  3259. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  3260. if (check_tensors) {
  3261. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  3262. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  3263. }));
  3264. }
  3265. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  3266. if (buf_mmap && cur->data == nullptr) {
  3267. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  3268. if (lmlocks) {
  3269. const auto & lmlock = lmlocks->at(weight->idx);
  3270. lmlock->grow_to(weight->offs + n_size);
  3271. }
  3272. auto & mmap_used = mmaps_used[weight->idx];
  3273. mmap_used.first = std::min(mmap_used.first, weight->offs);
  3274. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  3275. } else {
  3276. ggml_backend_tensor_set(cur, data, 0, n_size);
  3277. }
  3278. } else {
  3279. GGML_ASSERT(weight->idx < files.size());
  3280. const auto & file = files.at(weight->idx);
  3281. if (ggml_backend_buffer_is_host(cur->buffer)) {
  3282. file->seek(weight->offs, SEEK_SET);
  3283. file->read_raw(cur->data, n_size);
  3284. if (check_tensors) {
  3285. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  3286. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  3287. }));
  3288. }
  3289. } else {
  3290. read_buf.resize(n_size);
  3291. file->seek(weight->offs, SEEK_SET);
  3292. file->read_raw(read_buf.data(), n_size);
  3293. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3294. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  3295. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3296. }
  3297. }
  3298. }
  3299. size_done += n_size;
  3300. }
  3301. // check validation results
  3302. bool validation_failed = false;
  3303. for (auto & future : validation_result) {
  3304. auto result = future.get();
  3305. if (!result.second) {
  3306. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  3307. validation_failed = true;
  3308. }
  3309. }
  3310. if (validation_failed) {
  3311. throw std::runtime_error("found tensors with invalid data");
  3312. }
  3313. // check if this is the last call and do final cleanup
  3314. if (size_done >= size_data) {
  3315. // unmap offloaded tensors and metadata
  3316. if (use_mmap) {
  3317. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3318. const auto & mmap_used = mmaps_used.at(idx);
  3319. auto & mapping = mappings.at(idx);
  3320. mapping->unmap_fragment(0, mmap_used.first);
  3321. if (mmap_used.second != 0) {
  3322. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3323. }
  3324. }
  3325. }
  3326. if (progress_callback) {
  3327. // Even though the model is done loading, we still honor
  3328. // cancellation since we need to free allocations.
  3329. return progress_callback(1.0f, progress_callback_user_data);
  3330. }
  3331. }
  3332. return true;
  3333. }
  3334. };
  3335. template<>
  3336. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3337. uint32_t tmp;
  3338. const bool found = get_key(kid, tmp, required);
  3339. if (found) {
  3340. result = (enum llama_pooling_type) tmp;
  3341. } else {
  3342. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3343. }
  3344. return found;
  3345. }
  3346. //
  3347. // load LLaMA models
  3348. //
  3349. static const char * llama_model_arch_name(llm_arch arch) {
  3350. auto it = LLM_ARCH_NAMES.find(arch);
  3351. if (it == LLM_ARCH_NAMES.end()) {
  3352. return "unknown";
  3353. }
  3354. return it->second;
  3355. }
  3356. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3357. if (ftype & LLAMA_FTYPE_GUESSED) {
  3358. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3359. }
  3360. switch (ftype) {
  3361. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3362. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3363. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  3364. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3365. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3366. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  3367. return "Q4_1, some F16";
  3368. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3369. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3370. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3371. // K-quants
  3372. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3373. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3374. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3375. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3376. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3377. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3378. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3379. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3380. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3381. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3382. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  3383. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3384. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3385. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3386. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3387. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  3388. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  3389. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  3390. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3391. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3392. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3393. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3394. default: return "unknown, may not work";
  3395. }
  3396. }
  3397. static const char * llama_model_type_name(e_model type) {
  3398. switch (type) {
  3399. case MODEL_14M: return "14M";
  3400. case MODEL_17M: return "17M";
  3401. case MODEL_22M: return "22M";
  3402. case MODEL_33M: return "33M";
  3403. case MODEL_70M: return "70M";
  3404. case MODEL_109M: return "109M";
  3405. case MODEL_137M: return "137M";
  3406. case MODEL_160M: return "160M";
  3407. case MODEL_335M: return "335M";
  3408. case MODEL_410M: return "410M";
  3409. case MODEL_0_5B: return "0.5B";
  3410. case MODEL_1B: return "1B";
  3411. case MODEL_1_4B: return "1.4B";
  3412. case MODEL_2B: return "2B";
  3413. case MODEL_2_8B: return "2.8B";
  3414. case MODEL_3B: return "3B";
  3415. case MODEL_4B: return "4B";
  3416. case MODEL_6_9B: return "6.9B";
  3417. case MODEL_7B: return "7B";
  3418. case MODEL_8B: return "8B";
  3419. case MODEL_12B: return "12B";
  3420. case MODEL_13B: return "13B";
  3421. case MODEL_14B: return "14B";
  3422. case MODEL_15B: return "15B";
  3423. case MODEL_16B: return "16B";
  3424. case MODEL_20B: return "20B";
  3425. case MODEL_30B: return "30B";
  3426. case MODEL_34B: return "34B";
  3427. case MODEL_35B: return "35B";
  3428. case MODEL_40B: return "40B";
  3429. case MODEL_65B: return "65B";
  3430. case MODEL_70B: return "70B";
  3431. case MODEL_236B: return "236B";
  3432. case MODEL_314B: return "314B";
  3433. case MODEL_SMALL: return "0.1B";
  3434. case MODEL_MEDIUM: return "0.4B";
  3435. case MODEL_LARGE: return "0.8B";
  3436. case MODEL_XL: return "1.5B";
  3437. case MODEL_A2_7B: return "A2.7B";
  3438. case MODEL_8x7B: return "8x7B";
  3439. case MODEL_8x22B: return "8x22B";
  3440. case MODEL_16x12B: return "16x12B";
  3441. case MODEL_10B_128x3_66B: return "10B+128x3.66B";
  3442. default: return "?B";
  3443. }
  3444. }
  3445. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3446. switch (type) {
  3447. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3448. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3449. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3450. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3451. default: return "unknown";
  3452. }
  3453. }
  3454. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3455. model.arch = ml.get_arch();
  3456. if (model.arch == LLM_ARCH_UNKNOWN) {
  3457. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3458. }
  3459. }
  3460. static void llm_load_hparams(
  3461. llama_model_loader & ml,
  3462. llama_model & model) {
  3463. auto & hparams = model.hparams;
  3464. const gguf_context * ctx = ml.meta;
  3465. // get metadata as string
  3466. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3467. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3468. if (type == GGUF_TYPE_ARRAY) {
  3469. continue;
  3470. }
  3471. const char * name = gguf_get_key(ctx, i);
  3472. const std::string value = gguf_kv_to_str(ctx, i);
  3473. model.gguf_kv.emplace(name, value);
  3474. }
  3475. // get general kv
  3476. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3477. // get hparams kv
  3478. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3479. // everything past this point is not vocab-related
  3480. if (hparams.vocab_only) {
  3481. return;
  3482. }
  3483. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3484. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3485. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3486. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3487. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3488. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3489. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3490. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3491. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3492. if (hparams.n_expert > 0) {
  3493. GGML_ASSERT(hparams.n_expert_used > 0);
  3494. } else {
  3495. GGML_ASSERT(hparams.n_expert_used == 0);
  3496. }
  3497. // n_head_kv is optional, default to n_head
  3498. hparams.n_head_kv = hparams.n_head;
  3499. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3500. bool rope_finetuned = false;
  3501. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3502. hparams.rope_finetuned = rope_finetuned;
  3503. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3504. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3505. // rope_freq_base (optional)
  3506. hparams.rope_freq_base_train = 10000.0f;
  3507. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3508. std::string rope_scaling("linear");
  3509. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3510. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3511. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3512. // rope_freq_scale (inverse of the kv) is optional
  3513. float ropescale = 0.0f;
  3514. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3515. // try the old key name
  3516. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3517. }
  3518. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3519. ml.get_key(LLM_KV_ROPE_SCALING_ATTN_FACTOR, hparams.rope_attn_factor, false);
  3520. // sanity check for n_rot (optional)
  3521. {
  3522. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3523. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3524. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3525. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3526. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3527. }
  3528. }
  3529. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3530. // gpt-j n_rot = rotary_dim
  3531. }
  3532. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3533. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3534. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3535. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3536. // arch-specific KVs
  3537. switch (model.arch) {
  3538. case LLM_ARCH_LLAMA:
  3539. {
  3540. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3541. if (hparams.n_expert == 8) {
  3542. switch (hparams.n_layer) {
  3543. case 32: model.type = e_model::MODEL_8x7B; break;
  3544. case 56: model.type = e_model::MODEL_8x22B; break;
  3545. default: model.type = e_model::MODEL_UNKNOWN;
  3546. }
  3547. } else {
  3548. switch (hparams.n_layer) {
  3549. case 22: model.type = e_model::MODEL_1B; break;
  3550. case 26: model.type = e_model::MODEL_3B; break;
  3551. // granite uses a vocab with len 49152
  3552. 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;
  3553. case 36: model.type = e_model::MODEL_8B; break; // granite
  3554. case 40: model.type = e_model::MODEL_13B; break;
  3555. case 48: model.type = e_model::MODEL_34B; break;
  3556. case 60: model.type = e_model::MODEL_30B; break;
  3557. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3558. default: model.type = e_model::MODEL_UNKNOWN;
  3559. }
  3560. }
  3561. } break;
  3562. case LLM_ARCH_MINICPM:
  3563. {
  3564. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3565. switch (hparams.n_layer) {
  3566. case 40: model.type = e_model::MODEL_2B; break;
  3567. default: model.type = e_model::MODEL_UNKNOWN;
  3568. }
  3569. } break;
  3570. case LLM_ARCH_GROK:
  3571. {
  3572. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3573. switch (hparams.n_layer) {
  3574. case 64: model.type = e_model::MODEL_314B; break;
  3575. default: model.type = e_model::MODEL_UNKNOWN;
  3576. }
  3577. } break;
  3578. case LLM_ARCH_FALCON:
  3579. {
  3580. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3581. switch (hparams.n_layer) {
  3582. case 32: model.type = e_model::MODEL_7B; break;
  3583. case 60: model.type = e_model::MODEL_40B; break;
  3584. default: model.type = e_model::MODEL_UNKNOWN;
  3585. }
  3586. } break;
  3587. case LLM_ARCH_BAICHUAN:
  3588. {
  3589. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3590. switch (hparams.n_layer) {
  3591. case 32: model.type = e_model::MODEL_7B; break;
  3592. case 40: model.type = e_model::MODEL_13B; break;
  3593. default: model.type = e_model::MODEL_UNKNOWN;
  3594. }
  3595. if (model.type == e_model::MODEL_13B) {
  3596. // TODO: become GGUF KV parameter
  3597. hparams.f_max_alibi_bias = 8.0f;
  3598. }
  3599. } break;
  3600. case LLM_ARCH_STARCODER:
  3601. {
  3602. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3603. switch (hparams.n_layer) {
  3604. case 24: model.type = e_model::MODEL_1B; break;
  3605. case 36: model.type = e_model::MODEL_3B; break;
  3606. case 42: model.type = e_model::MODEL_7B; break;
  3607. case 40: model.type = e_model::MODEL_15B; break;
  3608. default: model.type = e_model::MODEL_UNKNOWN;
  3609. }
  3610. } break;
  3611. case LLM_ARCH_REFACT:
  3612. {
  3613. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3614. switch (hparams.n_layer) {
  3615. case 32: model.type = e_model::MODEL_1B; break;
  3616. default: model.type = e_model::MODEL_UNKNOWN;
  3617. }
  3618. // TODO: become GGUF KV parameter
  3619. hparams.f_max_alibi_bias = 8.0f;
  3620. } break;
  3621. case LLM_ARCH_BERT:
  3622. {
  3623. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3624. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3625. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3626. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3627. switch (hparams.n_layer) {
  3628. case 3:
  3629. model.type = e_model::MODEL_17M; break; // bge-micro
  3630. case 6:
  3631. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3632. case 12:
  3633. switch (hparams.n_embd) {
  3634. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3635. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3636. } break;
  3637. case 24:
  3638. model.type = e_model::MODEL_335M; break; // bge-large
  3639. }
  3640. } break;
  3641. case LLM_ARCH_JINA_BERT_V2:
  3642. {
  3643. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3644. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3645. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3646. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3647. hparams.f_max_alibi_bias = 8.0f;
  3648. switch (hparams.n_layer) {
  3649. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  3650. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  3651. }
  3652. } break;
  3653. case LLM_ARCH_NOMIC_BERT:
  3654. {
  3655. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3656. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3657. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3658. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3659. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3660. model.type = e_model::MODEL_137M;
  3661. }
  3662. } break;
  3663. case LLM_ARCH_BLOOM:
  3664. {
  3665. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3666. switch (hparams.n_layer) {
  3667. case 24: model.type = e_model::MODEL_1B; break;
  3668. case 30:
  3669. switch (hparams.n_embd) {
  3670. case 2560: model.type = e_model::MODEL_3B; break;
  3671. case 4096: model.type = e_model::MODEL_7B; break;
  3672. } break;
  3673. }
  3674. // TODO: become GGUF KV parameter
  3675. hparams.f_max_alibi_bias = 8.0f;
  3676. } break;
  3677. case LLM_ARCH_MPT:
  3678. {
  3679. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3680. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3681. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3682. switch (hparams.n_layer) {
  3683. case 32: model.type = e_model::MODEL_7B; break;
  3684. case 48: model.type = e_model::MODEL_30B; break;
  3685. default: model.type = e_model::MODEL_UNKNOWN;
  3686. }
  3687. } break;
  3688. case LLM_ARCH_STABLELM:
  3689. {
  3690. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3691. switch (hparams.n_layer) {
  3692. case 24: model.type = e_model::MODEL_1B; break;
  3693. case 32: model.type = e_model::MODEL_3B; break;
  3694. case 40: model.type = e_model::MODEL_12B; break;
  3695. default: model.type = e_model::MODEL_UNKNOWN;
  3696. }
  3697. } break;
  3698. case LLM_ARCH_QWEN:
  3699. {
  3700. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3701. switch (hparams.n_layer) {
  3702. case 32: model.type = e_model::MODEL_7B; break;
  3703. case 40: model.type = e_model::MODEL_13B; break;
  3704. default: model.type = e_model::MODEL_UNKNOWN;
  3705. }
  3706. } break;
  3707. case LLM_ARCH_QWEN2:
  3708. {
  3709. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3710. switch (hparams.n_layer) {
  3711. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3712. case 32: model.type = e_model::MODEL_7B; break;
  3713. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3714. case 80: model.type = e_model::MODEL_70B; break;
  3715. default: model.type = e_model::MODEL_UNKNOWN;
  3716. }
  3717. } break;
  3718. case LLM_ARCH_QWEN2MOE:
  3719. {
  3720. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3721. switch (hparams.n_layer) {
  3722. case 24: model.type = e_model::MODEL_A2_7B; break;
  3723. default: model.type = e_model::MODEL_UNKNOWN;
  3724. }
  3725. } break;
  3726. case LLM_ARCH_PHI2:
  3727. {
  3728. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3729. switch (hparams.n_layer) {
  3730. case 24: model.type = e_model::MODEL_1B; break;
  3731. case 32: model.type = e_model::MODEL_3B; break;
  3732. default: model.type = e_model::MODEL_UNKNOWN;
  3733. }
  3734. } break;
  3735. case LLM_ARCH_PHI3:
  3736. {
  3737. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3738. switch (hparams.n_layer) {
  3739. case 24: model.type = e_model::MODEL_1B; break;
  3740. case 32: model.type = e_model::MODEL_3B; break;
  3741. case 40: model.type = e_model::MODEL_14B; break;
  3742. default: model.type = e_model::MODEL_UNKNOWN;
  3743. }
  3744. } break;
  3745. case LLM_ARCH_PLAMO:
  3746. {
  3747. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3748. switch (hparams.n_layer) {
  3749. case 40: model.type = e_model::MODEL_13B; break;
  3750. default: model.type = e_model::MODEL_UNKNOWN;
  3751. }
  3752. } break;
  3753. case LLM_ARCH_GPT2:
  3754. {
  3755. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3756. switch (hparams.n_layer) {
  3757. case 12: model.type = e_model::MODEL_SMALL; break;
  3758. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3759. case 36: model.type = e_model::MODEL_LARGE; break;
  3760. case 48: model.type = e_model::MODEL_XL; break;
  3761. default: model.type = e_model::MODEL_UNKNOWN;
  3762. }
  3763. } break;
  3764. case LLM_ARCH_CODESHELL:
  3765. {
  3766. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3767. switch (hparams.n_layer) {
  3768. case 42: model.type = e_model::MODEL_SMALL; break;
  3769. default: model.type = e_model::MODEL_UNKNOWN;
  3770. }
  3771. } break;
  3772. case LLM_ARCH_ORION:
  3773. {
  3774. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3775. switch (hparams.n_layer) {
  3776. case 40: model.type = e_model::MODEL_14B; break;
  3777. default: model.type = e_model::MODEL_UNKNOWN;
  3778. }
  3779. } break;
  3780. case LLM_ARCH_INTERNLM2:
  3781. {
  3782. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3783. switch (hparams.n_layer) {
  3784. case 32: model.type = e_model::MODEL_7B; break;
  3785. case 48: model.type = e_model::MODEL_20B; break;
  3786. default: model.type = e_model::MODEL_UNKNOWN;
  3787. }
  3788. } break;
  3789. case LLM_ARCH_GEMMA:
  3790. {
  3791. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3792. switch (hparams.n_layer) {
  3793. case 18: model.type = e_model::MODEL_2B; break;
  3794. case 28: model.type = e_model::MODEL_7B; break;
  3795. default: model.type = e_model::MODEL_UNKNOWN;
  3796. }
  3797. } break;
  3798. case LLM_ARCH_STARCODER2:
  3799. {
  3800. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3801. switch (hparams.n_layer) {
  3802. case 30: model.type = e_model::MODEL_3B; break;
  3803. case 32: model.type = e_model::MODEL_7B; break;
  3804. case 40: model.type = e_model::MODEL_15B; break;
  3805. case 52: model.type = e_model::MODEL_20B; break; // granite
  3806. case 88: model.type = e_model::MODEL_34B; break; // granite
  3807. default: model.type = e_model::MODEL_UNKNOWN;
  3808. }
  3809. } break;
  3810. case LLM_ARCH_MAMBA:
  3811. {
  3812. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3813. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3814. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3815. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3816. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3817. switch (hparams.n_layer) {
  3818. case 24:
  3819. switch (hparams.n_embd) {
  3820. case 768: model.type = e_model::MODEL_SMALL; break;
  3821. default: model.type = e_model::MODEL_UNKNOWN;
  3822. } break;
  3823. case 48:
  3824. switch (hparams.n_embd) {
  3825. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3826. case 1536: model.type = e_model::MODEL_LARGE; break;
  3827. case 2048: model.type = e_model::MODEL_XL; break;
  3828. default: model.type = e_model::MODEL_UNKNOWN;
  3829. } break;
  3830. case 64:
  3831. switch (hparams.n_embd) {
  3832. case 2560: model.type = e_model::MODEL_3B; break;
  3833. default: model.type = e_model::MODEL_UNKNOWN;
  3834. } break;
  3835. default: model.type = e_model::MODEL_UNKNOWN;
  3836. }
  3837. } break;
  3838. case LLM_ARCH_XVERSE:
  3839. {
  3840. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3841. switch (hparams.n_layer) {
  3842. case 32: model.type = e_model::MODEL_7B; break;
  3843. case 40: model.type = e_model::MODEL_13B; break;
  3844. case 80: model.type = e_model::MODEL_65B; break;
  3845. default: model.type = e_model::MODEL_UNKNOWN;
  3846. }
  3847. } break;
  3848. case LLM_ARCH_COMMAND_R:
  3849. {
  3850. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3851. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3852. switch (hparams.n_layer) {
  3853. case 40: model.type = e_model::MODEL_35B; break;
  3854. default: model.type = e_model::MODEL_UNKNOWN;
  3855. }
  3856. } break;
  3857. case LLM_ARCH_DBRX:
  3858. {
  3859. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3860. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  3861. switch (hparams.n_layer) {
  3862. case 40: model.type = e_model::MODEL_16x12B; break;
  3863. default: model.type = e_model::MODEL_UNKNOWN;
  3864. }
  3865. } break;
  3866. case LLM_ARCH_OLMO:
  3867. {
  3868. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3869. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3870. switch (hparams.n_layer) {
  3871. case 22: model.type = e_model::MODEL_1B; break;
  3872. case 32: model.type = e_model::MODEL_7B; break;
  3873. case 80: model.type = e_model::MODEL_70B; break;
  3874. default: model.type = e_model::MODEL_UNKNOWN;
  3875. }
  3876. } break;
  3877. case LLM_ARCH_GPTNEOX:
  3878. {
  3879. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3880. ml.get_key(LLM_KV_USE_PARALLEL_RESIDUAL, hparams.use_par_res);
  3881. switch (hparams.n_layer) {
  3882. case 6:
  3883. switch (hparams.n_ff) {
  3884. case 512: model.type = e_model::MODEL_14M; break;
  3885. case 2048: model.type = e_model::MODEL_70M; break;
  3886. default: model.type = e_model::MODEL_UNKNOWN;
  3887. } break;
  3888. case 12:
  3889. switch (hparams.n_ff) {
  3890. case 3072: model.type = e_model::MODEL_160M; break;
  3891. default: model.type = e_model::MODEL_UNKNOWN;
  3892. } break;
  3893. case 16:
  3894. switch (hparams.n_ff) {
  3895. case 8192: model.type = e_model::MODEL_1B; break;
  3896. default: model.type = e_model::MODEL_UNKNOWN;
  3897. } break;
  3898. case 24:
  3899. switch (hparams.n_ff) {
  3900. case 4096: model.type = e_model::MODEL_410M; break;
  3901. case 8192: model.type = e_model::MODEL_1_4B; break;
  3902. default: model.type = e_model::MODEL_UNKNOWN;
  3903. } break;
  3904. case 32:
  3905. switch (hparams.n_ff) {
  3906. case 10240: model.type = e_model::MODEL_2_8B; break;
  3907. case 16384: model.type = e_model::MODEL_6_9B; break;
  3908. default: model.type = e_model::MODEL_UNKNOWN;
  3909. } break;
  3910. case 36:
  3911. switch (hparams.n_ff) {
  3912. case 20480: model.type = e_model::MODEL_12B; break;
  3913. default: model.type = e_model::MODEL_UNKNOWN;
  3914. } break;
  3915. case 44:
  3916. switch (hparams.n_ff) {
  3917. case 24576: model.type = e_model::MODEL_20B; break;
  3918. default: model.type = e_model::MODEL_UNKNOWN;
  3919. } break;
  3920. default: model.type = e_model::MODEL_UNKNOWN;
  3921. }
  3922. } break;
  3923. case LLM_ARCH_ARCTIC:
  3924. {
  3925. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3926. if (hparams.n_expert == 128) {
  3927. switch (hparams.n_layer) {
  3928. case 35: model.type = e_model::MODEL_10B_128x3_66B; break;
  3929. default: model.type = e_model::MODEL_UNKNOWN;
  3930. }
  3931. } else {
  3932. model.type = e_model::MODEL_UNKNOWN;
  3933. }
  3934. } break;
  3935. case LLM_ARCH_DEEPSEEK2:
  3936. {
  3937. bool is_lite = (hparams.n_layer == 27);
  3938. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3939. ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
  3940. if (!is_lite) {
  3941. ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q);
  3942. }
  3943. ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv);
  3944. ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp);
  3945. ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
  3946. ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
  3947. ml.get_key(LLM_KV_ROPE_SCALING_YARN_LOG_MUL, hparams.rope_yarn_log_mul);
  3948. switch (hparams.n_layer) {
  3949. case 27: model.type = e_model::MODEL_16B; break;
  3950. case 60: model.type = e_model::MODEL_236B; break;
  3951. default: model.type = e_model::MODEL_UNKNOWN;
  3952. }
  3953. } break;
  3954. default: (void)0;
  3955. }
  3956. model.ftype = ml.ftype;
  3957. if (hparams.f_max_alibi_bias > 0.0f) {
  3958. hparams.use_alibi = true;
  3959. }
  3960. hparams.rope_type = llama_rope_type(&model);
  3961. }
  3962. // TODO: This should probably be in llama.h
  3963. static std::vector<llama_vocab::id> llama_tokenize_internal(
  3964. const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special = false
  3965. );
  3966. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3967. static void llm_load_vocab(
  3968. llama_model_loader & ml,
  3969. llama_model & model) {
  3970. auto & vocab = model.vocab;
  3971. struct gguf_context * ctx = ml.meta;
  3972. const auto kv = LLM_KV(model.arch);
  3973. // determine vocab type
  3974. {
  3975. std::string tokenizer_model;
  3976. std::string tokenizer_pre;
  3977. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  3978. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  3979. if (tokenizer_model == "no_vocab") {
  3980. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3981. // default special tokens
  3982. vocab.special_bos_id = -1;
  3983. vocab.special_eos_id = -1;
  3984. vocab.special_unk_id = -1;
  3985. vocab.special_sep_id = -1;
  3986. vocab.special_pad_id = -1;
  3987. vocab.special_cls_id = -1;
  3988. vocab.special_mask_id = -1;
  3989. vocab.linefeed_id = -1;
  3990. return;
  3991. } else if (tokenizer_model == "llama") {
  3992. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3993. // default special tokens
  3994. vocab.special_bos_id = 1;
  3995. vocab.special_eos_id = 2;
  3996. vocab.special_unk_id = 0;
  3997. vocab.special_sep_id = -1;
  3998. vocab.special_pad_id = -1;
  3999. vocab.special_cls_id = -1;
  4000. vocab.special_mask_id = -1;
  4001. // For Fill-In-the-Middle (FIM)/infill models which where converted
  4002. // prior to support of FIM special tokens in GGUF, the following
  4003. // will allow those models to continue to work. The general names
  4004. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  4005. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  4006. // new versions of these models have been published.
  4007. std::string gen_name;
  4008. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  4009. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  4010. [](unsigned char c){ return std::tolower(c); });
  4011. if (gen_name.find("code") != std::string::npos) {
  4012. if (model.arch == LLM_ARCH_LLAMA) {
  4013. vocab.special_prefix_id = 32007;
  4014. vocab.special_suffix_id = 32008;
  4015. vocab.special_middle_id = 32009;
  4016. vocab.special_eot_id = 32010;
  4017. } else if (model.arch == LLM_ARCH_GEMMA) {
  4018. vocab.special_prefix_id = 67;
  4019. vocab.special_suffix_id = 69;
  4020. vocab.special_middle_id = 68;
  4021. // TODO: this is not EOT, it is "file separator" token, needs fix
  4022. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  4023. //vocab.special_eot_id = 70;
  4024. vocab.special_eot_id = 107;
  4025. }
  4026. }
  4027. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  4028. if (add_space_prefix_keyidx != -1) {
  4029. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  4030. } // The default value of add_space_prefix is true.
  4031. } else if (tokenizer_model == "bert") {
  4032. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  4033. // default special tokens
  4034. vocab.special_bos_id = -1;
  4035. vocab.special_eos_id = -1;
  4036. vocab.special_unk_id = 100;
  4037. vocab.special_sep_id = 102;
  4038. vocab.special_pad_id = 0;
  4039. vocab.special_cls_id = 101;
  4040. vocab.special_mask_id = 103;
  4041. vocab.add_space_prefix = false;
  4042. } else if (tokenizer_model == "gpt2") {
  4043. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  4044. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  4045. if (add_space_prefix_keyidx != -1) {
  4046. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  4047. }
  4048. // read bpe merges and populate bpe ranks
  4049. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  4050. if (merges_keyidx == -1) {
  4051. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  4052. }
  4053. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  4054. for (int i = 0; i < n_merges; i++) {
  4055. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  4056. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4057. std::string first;
  4058. std::string second;
  4059. const size_t pos = word.find(' ', 1);
  4060. if (pos != std::string::npos) {
  4061. first = word.substr(0, pos);
  4062. second = word.substr(pos + 1);
  4063. }
  4064. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  4065. }
  4066. // default special tokens
  4067. vocab.special_bos_id = 11;
  4068. vocab.special_eos_id = 11;
  4069. vocab.special_unk_id = -1;
  4070. vocab.special_sep_id = -1;
  4071. vocab.special_pad_id = -1;
  4072. vocab.special_cls_id = -1;
  4073. vocab.special_mask_id = -1;
  4074. } else {
  4075. throw std::runtime_error(format("unknown tokenizer: '%s'", tokenizer_model.c_str()));
  4076. }
  4077. // for now, only BPE models have pre-tokenizers
  4078. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  4079. if (tokenizer_pre.empty()) {
  4080. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  4081. LLAMA_LOG_WARN("%s: \n", __func__);
  4082. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  4083. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  4084. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  4085. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  4086. LLAMA_LOG_WARN("%s: \n", __func__);
  4087. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4088. } else if (
  4089. tokenizer_pre == "default") {
  4090. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4091. } else if (
  4092. tokenizer_pre == "llama3" ||
  4093. tokenizer_pre == "llama-v3" ||
  4094. tokenizer_pre == "llama-bpe") {
  4095. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  4096. } else if (
  4097. tokenizer_pre == "deepseek-llm") {
  4098. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  4099. } else if (
  4100. tokenizer_pre == "deepseek-coder") {
  4101. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  4102. } else if (
  4103. tokenizer_pre == "falcon") {
  4104. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  4105. } else if (
  4106. tokenizer_pre == "mpt") {
  4107. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  4108. } else if (
  4109. tokenizer_pre == "starcoder") {
  4110. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  4111. } else if (
  4112. tokenizer_pre == "gpt-2" ||
  4113. tokenizer_pre == "jina-es" ||
  4114. tokenizer_pre == "jina-de" ||
  4115. tokenizer_pre == "jina-v2-es" ||
  4116. tokenizer_pre == "jina-v2-de") {
  4117. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  4118. } else if (
  4119. tokenizer_pre == "refact") {
  4120. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  4121. } else if (
  4122. tokenizer_pre == "command-r") {
  4123. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  4124. } else if (
  4125. tokenizer_pre == "qwen2") {
  4126. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  4127. } else if (
  4128. tokenizer_pre == "stablelm2") {
  4129. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  4130. } else if (
  4131. tokenizer_pre == "olmo") {
  4132. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  4133. } else if (
  4134. tokenizer_pre == "dbrx") {
  4135. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  4136. } else if (
  4137. tokenizer_pre == "smaug-bpe") {
  4138. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_SMAUG;
  4139. } else {
  4140. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  4141. }
  4142. } else {
  4143. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  4144. }
  4145. }
  4146. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  4147. if (token_idx == -1) {
  4148. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  4149. }
  4150. const float * scores = nullptr;
  4151. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  4152. if (score_idx != -1) {
  4153. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  4154. }
  4155. const int * toktypes = nullptr;
  4156. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  4157. if (toktype_idx != -1) {
  4158. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  4159. }
  4160. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  4161. vocab.id_to_token.resize(n_vocab);
  4162. for (uint32_t i = 0; i < n_vocab; i++) {
  4163. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  4164. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  4165. vocab.token_to_id[word] = i;
  4166. auto & token_data = vocab.id_to_token[i];
  4167. token_data.text = std::move(word);
  4168. token_data.score = scores ? scores[i] : 0.0f;
  4169. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  4170. }
  4171. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  4172. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  4173. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  4174. try {
  4175. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  4176. } catch (const std::exception & e) {
  4177. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  4178. vocab.linefeed_id = vocab.special_pad_id;
  4179. }
  4180. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  4181. vocab.linefeed_id = vocab.special_pad_id;
  4182. } else {
  4183. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  4184. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  4185. vocab.linefeed_id = ids[0];
  4186. }
  4187. // special tokens
  4188. {
  4189. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  4190. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  4191. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  4192. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  4193. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  4194. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  4195. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  4196. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  4197. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  4198. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  4199. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  4200. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  4201. };
  4202. for (const auto & it : special_token_types) {
  4203. const std::string & key = kv(std::get<0>(it));
  4204. int32_t & id = std::get<1>(it);
  4205. uint32_t new_id;
  4206. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  4207. continue;
  4208. }
  4209. if (new_id >= vocab.id_to_token.size()) {
  4210. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  4211. __func__, key.c_str(), new_id, id);
  4212. } else {
  4213. id = new_id;
  4214. }
  4215. }
  4216. // Handle add_bos_token and add_eos_token
  4217. {
  4218. bool temp = true;
  4219. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  4220. vocab.special_add_bos = int(temp);
  4221. }
  4222. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  4223. vocab.special_add_eos = int(temp);
  4224. }
  4225. }
  4226. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  4227. //
  4228. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  4229. // for now, we apply this workaround to find the EOT token based on its text
  4230. if (vocab.special_eot_id == -1) {
  4231. for (const auto & t : vocab.token_to_id) {
  4232. if (
  4233. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  4234. // need to fix convert script
  4235. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  4236. (t.first == "<|eot_id|>" ||
  4237. t.first == "<|im_end|>" ||
  4238. t.first == "<|end|>" ||
  4239. t.first == "<end_of_turn>" ||
  4240. t.first == "<|endoftext|>"
  4241. )
  4242. ) {
  4243. vocab.special_eot_id = t.second;
  4244. break;
  4245. }
  4246. }
  4247. }
  4248. }
  4249. // build special tokens cache
  4250. {
  4251. for (llama_vocab::id id = 0; id < (llama_vocab::id)n_vocab; ++id) {
  4252. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  4253. vocab.cache_special_tokens.push_back(id);
  4254. }
  4255. }
  4256. std::sort( vocab.cache_special_tokens.begin(), vocab.cache_special_tokens.end(),
  4257. [&] (const llama_vocab::id a, const llama_vocab::id b) {
  4258. return vocab.id_to_token[a].text.size() > vocab.id_to_token[b].text.size();
  4259. }
  4260. );
  4261. LLAMA_LOG_INFO("%s: special tokens cache size = %u\n", __func__, (uint32_t)vocab.cache_special_tokens.size());
  4262. }
  4263. // build token to piece caches
  4264. {
  4265. size_t size_cache = 0;
  4266. std::vector<llama_vocab::token> cache_token_to_piece (n_vocab);
  4267. std::vector<llama_vocab::token> cache_token_to_piece_special(n_vocab);
  4268. for (uint32_t id = 0; id < n_vocab; ++id) {
  4269. cache_token_to_piece[id] = llama_token_to_piece(&model, id, false);
  4270. cache_token_to_piece_special[id] = llama_token_to_piece(&model, id, true);
  4271. size_cache += cache_token_to_piece[id].size();
  4272. size_cache += cache_token_to_piece_special[id].size();
  4273. }
  4274. std::swap(vocab.cache_token_to_piece, cache_token_to_piece);
  4275. std::swap(vocab.cache_token_to_piece_special, cache_token_to_piece_special);
  4276. LLAMA_LOG_INFO("%s: token to piece cache size = %.4f MB\n", __func__, size_cache / 1024.0 / 1024.0);
  4277. }
  4278. }
  4279. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  4280. const auto & hparams = model.hparams;
  4281. const auto & vocab = model.vocab;
  4282. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  4283. // hparams
  4284. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  4285. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  4286. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  4287. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  4288. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  4289. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  4290. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  4291. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  4292. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  4293. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  4294. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  4295. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  4296. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  4297. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  4298. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  4299. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  4300. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  4301. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  4302. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  4303. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  4304. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  4305. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  4306. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  4307. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  4308. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  4309. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  4310. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  4311. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  4312. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  4313. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  4314. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  4315. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  4316. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  4317. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  4318. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  4319. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  4320. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  4321. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  4322. if (ml.n_elements >= 1e12) {
  4323. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  4324. } else if (ml.n_elements >= 1e9) {
  4325. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  4326. } else if (ml.n_elements >= 1e6) {
  4327. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  4328. } else {
  4329. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  4330. }
  4331. if (ml.n_bytes < GiB) {
  4332. 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);
  4333. } else {
  4334. 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);
  4335. }
  4336. // general kv
  4337. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  4338. // special tokens
  4339. 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() ); }
  4340. 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() ); }
  4341. 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() ); }
  4342. 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() ); }
  4343. 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() ); }
  4344. 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() ); }
  4345. 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() ); }
  4346. 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() ); }
  4347. 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() ); }
  4348. 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() ); }
  4349. 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() ); }
  4350. 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() ); }
  4351. if (model.arch == LLM_ARCH_DEEPSEEK2) {
  4352. LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead);
  4353. LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q);
  4354. LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv);
  4355. LLAMA_LOG_INFO("%s: n_ff_exp = %d\n", __func__, hparams.n_ff_exp);
  4356. LLAMA_LOG_INFO("%s: n_expert_shared = %d\n", __func__, hparams.n_expert_shared);
  4357. LLAMA_LOG_INFO("%s: expert_weights_scale = %.1f\n", __func__, hparams.expert_weights_scale);
  4358. LLAMA_LOG_INFO("%s: rope_yarn_log_mul = %.4f\n", __func__, hparams.rope_yarn_log_mul);
  4359. }
  4360. }
  4361. // Returns false if cancelled by progress_callback
  4362. static bool llm_load_tensors(
  4363. llama_model_loader & ml,
  4364. llama_model & model,
  4365. int n_gpu_layers,
  4366. enum llama_split_mode split_mode,
  4367. int main_gpu,
  4368. const float * tensor_split,
  4369. bool use_mlock,
  4370. llama_progress_callback progress_callback,
  4371. void * progress_callback_user_data) {
  4372. model.t_start_us = ggml_time_us();
  4373. auto & hparams = model.hparams;
  4374. #ifdef GGML_USE_SYCL
  4375. // disable MoE with SYCL until mul_mat_id is updated
  4376. if (hparams.n_expert > 0) {
  4377. n_gpu_layers = 0;
  4378. }
  4379. #endif
  4380. model.split_mode = split_mode;
  4381. model.main_gpu = main_gpu;
  4382. model.n_gpu_layers = n_gpu_layers;
  4383. const int64_t n_layer = hparams.n_layer;
  4384. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  4385. bool use_mmap_buffer = true;
  4386. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  4387. model.buft_input = llama_default_buffer_type_cpu(true);
  4388. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  4389. model.buft_layer.resize(n_layer);
  4390. // assign cpu layers
  4391. for (int64_t i = 0; i < i_gpu_start; ++i) {
  4392. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  4393. }
  4394. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  4395. // calculate the split points
  4396. int device_count = llama_get_device_count(model);
  4397. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  4398. std::vector<float> splits(device_count);
  4399. if (all_zero) {
  4400. // default split, by free memory
  4401. for (int i = 0; i < device_count; ++i) {
  4402. splits[i] = llama_get_device_memory(model, i);
  4403. }
  4404. } else {
  4405. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  4406. }
  4407. // sum and normalize the splits to get the split points
  4408. float split_sum = 0.0f;
  4409. for (int i = 0; i < device_count; ++i) {
  4410. split_sum += splits[i];
  4411. splits[i] = split_sum;
  4412. }
  4413. for (int i = 0; i < device_count; ++i) {
  4414. splits[i] /= split_sum;
  4415. }
  4416. // assign the repeating layers to the devices according to the splits
  4417. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  4418. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  4419. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  4420. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  4421. }
  4422. // assign the output layer
  4423. if (n_gpu_layers > n_layer) {
  4424. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  4425. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  4426. } else {
  4427. model.buft_output = llama_default_buffer_type_cpu(true);
  4428. }
  4429. } else {
  4430. ggml_backend_buffer_type_t split_buft;
  4431. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  4432. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  4433. } else {
  4434. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  4435. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  4436. }
  4437. // assign the repeating layers
  4438. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  4439. model.buft_layer[i] = {
  4440. split_buft,
  4441. llama_default_buffer_type_offload(model, main_gpu)
  4442. };
  4443. }
  4444. // assign the output layer
  4445. if (n_gpu_layers > n_layer) {
  4446. model.buft_output = {
  4447. split_buft,
  4448. llama_default_buffer_type_offload(model, main_gpu)
  4449. };
  4450. } else {
  4451. model.buft_output = llama_default_buffer_type_cpu(true);
  4452. }
  4453. }
  4454. // count used buffer types
  4455. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  4456. buft_layer_count[model.buft_input.buft]++;
  4457. buft_layer_count[model.buft_input.buft_matrix]++;
  4458. buft_layer_count[model.buft_output.buft]++;
  4459. buft_layer_count[model.buft_output.buft_matrix]++;
  4460. for (int64_t i = 0; i < n_layer; ++i) {
  4461. buft_layer_count[model.buft_layer[i].buft]++;
  4462. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  4463. }
  4464. // create one context per buffer type
  4465. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  4466. // for moe merged tensors
  4467. ctx_size += ggml_tensor_overhead()*n_layer*3;
  4468. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  4469. for (auto & it : buft_layer_count) {
  4470. struct ggml_init_params params = {
  4471. /*.mem_size =*/ ctx_size,
  4472. /*.mem_buffer =*/ NULL,
  4473. /*.no_alloc =*/ true,
  4474. };
  4475. ggml_context * ctx = ggml_init(params);
  4476. if (!ctx) {
  4477. throw std::runtime_error(format("failed to create context"));
  4478. }
  4479. ctx_map[it.first] = ctx;
  4480. model.ctxs.push_back(ctx);
  4481. }
  4482. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  4483. // create tensors for the weights
  4484. {
  4485. const int64_t n_embd = hparams.n_embd;
  4486. const int64_t n_embd_head = n_embd / hparams.n_head;
  4487. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4488. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4489. const int64_t n_embd_gqa = n_embd_v_gqa;
  4490. const int64_t n_vocab = hparams.n_vocab;
  4491. const int64_t n_vocab_type = hparams.n_vocab_type;
  4492. const int64_t n_ff = hparams.n_ff;
  4493. const int64_t n_expert = hparams.n_expert;
  4494. if (n_expert > 0 && hparams.n_expert_used == 0) {
  4495. throw std::runtime_error("model has expert layers but no expert layers are used");
  4496. }
  4497. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  4498. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  4499. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  4500. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  4501. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  4502. model.layers.resize(n_layer);
  4503. const auto tn = LLM_TN(model.arch);
  4504. switch (model.arch) {
  4505. case LLM_ARCH_LLAMA:
  4506. case LLM_ARCH_REFACT:
  4507. case LLM_ARCH_MINICPM:
  4508. {
  4509. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4510. // output
  4511. {
  4512. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4513. if (model.arch != LLM_ARCH_MINICPM){
  4514. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4515. // if output is NULL, init from the input tok embed
  4516. if (model.output == NULL) {
  4517. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  4518. }
  4519. }
  4520. }
  4521. for (int i = 0; i < n_layer; ++i) {
  4522. ggml_context * ctx_layer = ctx_for_layer(i);
  4523. ggml_context * ctx_split = ctx_for_layer_split(i);
  4524. auto & layer = model.layers[i];
  4525. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4526. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4527. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4528. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4529. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4530. // optional bias tensors
  4531. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4532. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4533. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4534. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4535. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4536. if (n_expert == 0) {
  4537. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4538. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4539. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4540. // optional MLP bias
  4541. layer.ffn_gate_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4542. layer.ffn_down_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4543. layer.ffn_up_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4544. } else {
  4545. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4546. 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);
  4547. if (layer.ffn_gate_exps) {
  4548. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4549. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4550. } else {
  4551. // merge split expert into a single tensor for compatibility with older models
  4552. // requires disabling mmap
  4553. use_mmap_buffer = false;
  4554. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4555. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4556. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4557. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4558. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4559. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4560. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4561. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4562. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4563. for (uint32_t x = 0; x < n_expert; ++x) {
  4564. // the individual experts are loaded into a view of the merged tensor
  4565. 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);
  4566. 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);
  4567. 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);
  4568. }
  4569. }
  4570. }
  4571. }
  4572. } break;
  4573. case LLM_ARCH_GROK:
  4574. {
  4575. if (n_expert == 0) {
  4576. throw std::runtime_error("Grok model cannot have zero experts");
  4577. }
  4578. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4579. // output
  4580. {
  4581. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4582. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4583. // if output is NULL, init from the input tok embed
  4584. if (model.output == NULL) {
  4585. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  4586. }
  4587. }
  4588. for (int i = 0; i < n_layer; ++i) {
  4589. ggml_context * ctx_layer = ctx_for_layer(i);
  4590. ggml_context * ctx_split = ctx_for_layer_split(i);
  4591. auto & layer = model.layers[i];
  4592. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4593. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4594. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4595. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4596. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4597. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4598. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4599. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4600. 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);
  4601. if (layer.ffn_gate_exps) {
  4602. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4603. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4604. } else {
  4605. // merge split expert into a single tensor for compatibility with older models
  4606. // requires disabling mmap
  4607. use_mmap_buffer = false;
  4608. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4609. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4610. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4611. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4612. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4613. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4614. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4615. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4616. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4617. for (uint32_t x = 0; x < n_expert; ++x) {
  4618. // the individual experts are loaded into a view of the merged tensor
  4619. 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);
  4620. 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);
  4621. 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);
  4622. }
  4623. }
  4624. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4625. }
  4626. } break;
  4627. case LLM_ARCH_DBRX:
  4628. {
  4629. if (n_expert == 0) {
  4630. throw std::runtime_error("DBRX model cannot have zero experts");
  4631. }
  4632. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4633. // output
  4634. {
  4635. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4636. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4637. }
  4638. for (int i = 0; i < n_layer; ++i) {
  4639. ggml_context * ctx_layer = ctx_for_layer(i);
  4640. ggml_context * ctx_split = ctx_for_layer_split(i);
  4641. auto & layer = model.layers[i];
  4642. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4643. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4644. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4645. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4646. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4647. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4648. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  4649. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4650. }
  4651. } break;
  4652. case LLM_ARCH_BAICHUAN:
  4653. {
  4654. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4655. {
  4656. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4657. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4658. }
  4659. for (int i = 0; i < n_layer; ++i) {
  4660. ggml_context * ctx_layer = ctx_for_layer(i);
  4661. ggml_context * ctx_split = ctx_for_layer_split(i);
  4662. auto & layer = model.layers[i];
  4663. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4664. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4665. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4666. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4667. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4668. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4669. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4670. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4671. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4672. }
  4673. } break;
  4674. case LLM_ARCH_FALCON:
  4675. {
  4676. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4677. // output
  4678. {
  4679. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4680. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4681. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4682. if (!model.output) {
  4683. 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
  4684. }
  4685. }
  4686. for (int i = 0; i < n_layer; ++i) {
  4687. ggml_context * ctx_layer = ctx_for_layer(i);
  4688. ggml_context * ctx_split = ctx_for_layer_split(i);
  4689. auto & layer = model.layers[i];
  4690. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4691. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4692. 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);
  4693. 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);
  4694. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4695. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4696. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4697. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4698. }
  4699. } break;
  4700. case LLM_ARCH_STARCODER:
  4701. {
  4702. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4703. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4704. // output
  4705. {
  4706. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4707. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4708. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4709. if (!model.output) {
  4710. // needs to be on GPU
  4711. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  4712. }
  4713. }
  4714. for (int i = 0; i < n_layer; ++i) {
  4715. ggml_context * ctx_layer = ctx_for_layer(i);
  4716. ggml_context * ctx_split = ctx_for_layer_split(i);
  4717. auto & layer = model.layers[i];
  4718. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4719. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4720. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4721. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4722. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4723. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4724. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4725. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4726. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4727. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4728. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4729. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4730. }
  4731. } break;
  4732. case LLM_ARCH_BERT:
  4733. case LLM_ARCH_NOMIC_BERT:
  4734. {
  4735. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4736. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4737. if (model.arch == LLM_ARCH_BERT) {
  4738. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4739. }
  4740. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4741. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4742. for (int i = 0; i < n_layer; ++i) {
  4743. ggml_context * ctx_layer = ctx_for_layer(i);
  4744. ggml_context * ctx_split = ctx_for_layer_split(i);
  4745. auto & layer = model.layers[i];
  4746. if (model.arch == LLM_ARCH_BERT) {
  4747. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4748. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4749. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4750. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4751. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4752. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4753. } else {
  4754. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4755. }
  4756. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4757. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4758. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4759. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4760. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4761. if (model.arch == LLM_ARCH_BERT) {
  4762. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4763. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4764. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4765. } else {
  4766. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4767. }
  4768. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4769. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4770. }
  4771. } break;
  4772. case LLM_ARCH_JINA_BERT_V2:
  4773. {
  4774. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  4775. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); //token_type_embeddings
  4776. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  4777. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  4778. for (int i = 0; i < n_layer; ++i) {
  4779. ggml_context * ctx_layer = ctx_for_layer(i);
  4780. ggml_context * ctx_split = ctx_for_layer_split(i);
  4781. auto & layer = model.layers[i]; // JinaBertLayer
  4782. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4783. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4784. 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);
  4785. 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);
  4786. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4787. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4788. 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);
  4789. 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);
  4790. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4791. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4792. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  4793. layer.bo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  4794. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  4795. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4796. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4797. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4798. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4799. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4800. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4801. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4802. }
  4803. } break;
  4804. case LLM_ARCH_BLOOM:
  4805. {
  4806. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4807. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4808. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4809. // output
  4810. {
  4811. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4812. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4813. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4814. }
  4815. for (int i = 0; i < n_layer; ++i) {
  4816. ggml_context * ctx_layer = ctx_for_layer(i);
  4817. ggml_context * ctx_split = ctx_for_layer_split(i);
  4818. auto & layer = model.layers[i];
  4819. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4820. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4821. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4822. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4823. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4824. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4825. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4826. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4827. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4828. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4829. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4830. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4831. }
  4832. } break;
  4833. case LLM_ARCH_MPT:
  4834. {
  4835. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4836. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4837. // output
  4838. {
  4839. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4840. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4841. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4842. if (!model.output) {
  4843. 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
  4844. }
  4845. }
  4846. for (int i = 0; i < n_layer; ++i) {
  4847. ggml_context * ctx_layer = ctx_for_layer(i);
  4848. ggml_context * ctx_split = ctx_for_layer_split(i);
  4849. auto & layer = model.layers[i];
  4850. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4851. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4852. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4853. 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);
  4854. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4855. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4856. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4857. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4858. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4859. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4860. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4861. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4862. 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);
  4863. 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);
  4864. 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);
  4865. 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);
  4866. // AWQ ScaleActivation layer
  4867. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4868. }
  4869. } break;
  4870. case LLM_ARCH_STABLELM:
  4871. {
  4872. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4873. // output
  4874. {
  4875. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4876. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4877. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4878. }
  4879. for (int i = 0; i < n_layer; ++i) {
  4880. ggml_context * ctx_layer = ctx_for_layer(i);
  4881. ggml_context * ctx_split = ctx_for_layer_split(i);
  4882. auto & layer = model.layers[i];
  4883. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4884. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4885. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4886. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4887. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4888. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4889. // optional bias tensors, present in Stable LM 2 1.6B
  4890. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4891. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4892. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4893. // optional q and k layernorms, present in StableLM 2 12B
  4894. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {hparams.n_embd_head_k, hparams.n_head}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4895. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {hparams.n_embd_head_k, hparams.n_head_kv}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4896. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  4897. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4898. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4899. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4900. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4901. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4902. }
  4903. } break;
  4904. case LLM_ARCH_QWEN:
  4905. {
  4906. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4907. // output
  4908. {
  4909. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4910. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4911. }
  4912. for (int i = 0; i < n_layer; ++i) {
  4913. ggml_context * ctx_layer = ctx_for_layer(i);
  4914. ggml_context * ctx_split = ctx_for_layer_split(i);
  4915. auto & layer = model.layers[i];
  4916. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4917. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4918. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4919. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4920. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4921. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4922. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4923. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4924. }
  4925. } break;
  4926. case LLM_ARCH_QWEN2:
  4927. {
  4928. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4929. // output
  4930. {
  4931. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4932. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  4933. // if output is NULL, init from the input tok embed
  4934. if (model.output == NULL) {
  4935. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  4936. }
  4937. }
  4938. for (int i = 0; i < n_layer; ++i) {
  4939. ggml_context * ctx_layer = ctx_for_layer(i);
  4940. ggml_context * ctx_split = ctx_for_layer_split(i);
  4941. auto & layer = model.layers[i];
  4942. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4943. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4944. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4945. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4946. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4947. // optional bias tensors
  4948. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4949. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4950. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4951. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4952. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4953. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4954. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4955. }
  4956. } break;
  4957. case LLM_ARCH_QWEN2MOE:
  4958. {
  4959. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4960. // output
  4961. {
  4962. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4963. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4964. }
  4965. for (int i = 0; i < n_layer; ++i) {
  4966. ggml_context * ctx_layer = ctx_for_layer(i);
  4967. ggml_context * ctx_split = ctx_for_layer_split(i);
  4968. auto & layer = model.layers[i];
  4969. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4970. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4971. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4972. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4973. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4974. // optional bias tensors
  4975. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4976. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4977. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4978. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4979. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4980. GGML_ASSERT(hparams.n_expert > 0);
  4981. GGML_ASSERT(hparams.n_expert_used > 0);
  4982. // MoE branch
  4983. auto n_ff_exp = n_ff / hparams.n_expert_used;
  4984. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  4985. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  4986. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  4987. // Shared expert branch
  4988. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  4989. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff});
  4990. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff, n_embd});
  4991. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff});
  4992. }
  4993. } break;
  4994. case LLM_ARCH_PHI2:
  4995. {
  4996. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4997. // output
  4998. {
  4999. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5000. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5001. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5002. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  5003. }
  5004. for (int i = 0; i < n_layer; ++i) {
  5005. ggml_context * ctx_layer = ctx_for_layer(i);
  5006. ggml_context * ctx_split = ctx_for_layer_split(i);
  5007. auto & layer = model.layers[i];
  5008. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5009. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5010. 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);
  5011. 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);
  5012. if (layer.wqkv == nullptr) {
  5013. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5014. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5015. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5016. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5017. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5018. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5019. }
  5020. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5021. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5022. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5023. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5024. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5025. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5026. }
  5027. } break;
  5028. case LLM_ARCH_PHI3:
  5029. {
  5030. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  5031. // output
  5032. {
  5033. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  5034. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  5035. }
  5036. for (int i = 0; i < n_layer; ++i) {
  5037. ggml_context* ctx_layer = ctx_for_layer(i);
  5038. ggml_context* ctx_split = ctx_for_layer_split(i);
  5039. auto & layer = model.layers[i];
  5040. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  5041. 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);
  5042. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  5043. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  5044. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  5045. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  5046. 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));
  5047. 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));
  5048. }
  5049. } break;
  5050. case LLM_ARCH_PLAMO:
  5051. {
  5052. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5053. // output
  5054. {
  5055. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5056. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5057. }
  5058. for (int i = 0; i < n_layer; ++i) {
  5059. ggml_context * ctx_layer = ctx_for_layer(i);
  5060. ggml_context * ctx_split = ctx_for_layer_split(i);
  5061. auto & layer = model.layers[i];
  5062. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5063. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5064. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5065. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5066. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5067. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5068. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5069. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5070. }
  5071. } break;
  5072. case LLM_ARCH_GPT2:
  5073. {
  5074. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5075. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  5076. // output
  5077. {
  5078. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5079. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5080. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5081. }
  5082. for (int i = 0; i < n_layer; ++i) {
  5083. ggml_context * ctx_layer = ctx_for_layer(i);
  5084. ggml_context * ctx_split = ctx_for_layer_split(i);
  5085. auto & layer = model.layers[i];
  5086. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5087. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5088. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5089. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5090. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5091. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5092. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5093. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5094. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5095. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5096. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5097. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5098. }
  5099. } break;
  5100. case LLM_ARCH_CODESHELL:
  5101. {
  5102. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5103. // output
  5104. {
  5105. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5106. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5107. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5108. }
  5109. for (int i = 0; i < n_layer; ++i) {
  5110. ggml_context * ctx_layer = ctx_for_layer(i);
  5111. ggml_context * ctx_split = ctx_for_layer_split(i);
  5112. auto & layer = model.layers[i];
  5113. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5114. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5115. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5116. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5117. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5118. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5119. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5120. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5121. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5122. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5123. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5124. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5125. }
  5126. } break;
  5127. case LLM_ARCH_ORION:
  5128. {
  5129. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5130. {
  5131. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5132. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5133. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5134. }
  5135. for (int i = 0; i < n_layer; ++i) {
  5136. ggml_context * ctx_layer = ctx_for_layer(i);
  5137. ggml_context * ctx_split = ctx_for_layer_split(i);
  5138. auto & layer = model.layers[i];
  5139. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5140. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5141. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5142. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5143. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5144. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5145. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5146. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5147. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5148. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5149. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5150. }
  5151. } break;
  5152. case LLM_ARCH_INTERNLM2:
  5153. {
  5154. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5155. // output
  5156. {
  5157. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5158. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5159. }
  5160. for (int i = 0; i < n_layer; ++i) {
  5161. ggml_context * ctx_layer = ctx_for_layer(i);
  5162. ggml_context * ctx_split = ctx_for_layer_split(i);
  5163. auto & layer = model.layers[i];
  5164. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5165. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5166. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5167. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5168. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5169. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5170. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5171. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5172. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5173. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5174. }
  5175. } break;
  5176. case LLM_ARCH_GEMMA:
  5177. {
  5178. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5179. // output
  5180. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5181. 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
  5182. const int64_t n_ff = hparams.n_ff;
  5183. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5184. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5185. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5186. for (uint32_t i = 0; i < n_layer; ++i) {
  5187. ggml_context * ctx_layer = ctx_for_layer(i);
  5188. ggml_context * ctx_split = ctx_for_layer_split(i);
  5189. auto & layer = model.layers[i];
  5190. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5191. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  5192. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5193. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5194. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  5195. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5196. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5197. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5198. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5199. }
  5200. } break;
  5201. case LLM_ARCH_STARCODER2:
  5202. {
  5203. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5204. // output
  5205. {
  5206. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5207. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5208. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5209. // if output is NULL, init from the input tok embed
  5210. if (model.output == NULL) {
  5211. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5212. }
  5213. }
  5214. for (int i = 0; i < n_layer; ++i) {
  5215. ggml_context * ctx_layer = ctx_for_layer(i);
  5216. ggml_context * ctx_split = ctx_for_layer_split(i);
  5217. auto & layer = model.layers[i];
  5218. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5219. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5220. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5221. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5222. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5223. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5224. // optional bias tensors
  5225. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5226. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5227. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5228. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5229. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5230. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5231. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5232. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5233. // optional bias tensors
  5234. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5235. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  5236. }
  5237. } break;
  5238. case LLM_ARCH_MAMBA:
  5239. {
  5240. const int64_t d_conv = hparams.ssm_d_conv;
  5241. const int64_t d_inner = hparams.ssm_d_inner;
  5242. const int64_t d_state = hparams.ssm_d_state;
  5243. const int64_t dt_rank = hparams.ssm_dt_rank;
  5244. // only an expansion factor of 2 is supported for now
  5245. GGML_ASSERT(2 * n_embd == d_inner);
  5246. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5247. // output
  5248. {
  5249. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5250. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5251. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  5252. if (model.output == NULL) {
  5253. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5254. }
  5255. }
  5256. for (int i = 0; i < n_layer; ++i) {
  5257. ggml_context * ctx_layer = ctx_for_layer(i);
  5258. ggml_context * ctx_split = ctx_for_layer_split(i);
  5259. auto & layer = model.layers[i];
  5260. // norm
  5261. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5262. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  5263. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  5264. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  5265. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  5266. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  5267. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  5268. // no "weight" suffix for these
  5269. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  5270. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  5271. // out_proj
  5272. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  5273. }
  5274. } break;
  5275. case LLM_ARCH_XVERSE:
  5276. {
  5277. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5278. {
  5279. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5280. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5281. }
  5282. for (int i = 0; i < n_layer; ++i) {
  5283. ggml_context * ctx_layer = ctx_for_layer(i);
  5284. ggml_context * ctx_split = ctx_for_layer_split(i);
  5285. auto & layer = model.layers[i];
  5286. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5287. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5288. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5289. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5290. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5291. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5292. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5294. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5295. }
  5296. } break;
  5297. case LLM_ARCH_COMMAND_R:
  5298. {
  5299. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5300. // output
  5301. {
  5302. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5303. // init output from the input tok embed
  5304. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5305. }
  5306. for (int i = 0; i < n_layer; ++i) {
  5307. ggml_context * ctx_layer = ctx_for_layer(i);
  5308. ggml_context * ctx_split = ctx_for_layer_split(i);
  5309. auto & layer = model.layers[i];
  5310. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5311. if (n_layer >= 64){
  5312. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {hparams.n_embd_head_k, hparams.n_head});
  5313. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {hparams.n_embd_head_k, hparams.n_head_kv});
  5314. }
  5315. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5316. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5317. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5318. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5319. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5320. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5321. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5322. }
  5323. } break;
  5324. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  5325. {
  5326. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5327. // output
  5328. {
  5329. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5330. // if output is NULL, init from the input tok embed
  5331. if (model.output == NULL) {
  5332. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5333. }
  5334. }
  5335. for (int i = 0; i < n_layer; ++i) {
  5336. ggml_context * ctx_split = ctx_for_layer_split(i);
  5337. auto & layer = model.layers[i];
  5338. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5339. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5340. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5341. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5342. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5343. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5344. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5345. }
  5346. } break;
  5347. case LLM_ARCH_GPTNEOX:
  5348. {
  5349. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5350. // output
  5351. {
  5352. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5353. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5354. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5355. }
  5356. for (int i = 0; i < n_layer; ++i) {
  5357. ggml_context * ctx_layer = ctx_for_layer(i);
  5358. ggml_context * ctx_split = ctx_for_layer_split(i);
  5359. auto & layer = model.layers[i];
  5360. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5361. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5362. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5363. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  5364. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5365. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5366. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5367. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5368. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  5369. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  5370. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5371. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  5372. }
  5373. } break;
  5374. case LLM_ARCH_ARCTIC:
  5375. {
  5376. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5377. // output
  5378. {
  5379. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5380. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_NOT_REQUIRED);
  5381. // if output is NULL, init from the input tok embed
  5382. if (model.output == NULL) {
  5383. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, llama_model_loader::TENSOR_DUPLICATED);
  5384. }
  5385. }
  5386. for (int i = 0; i < n_layer; ++i) {
  5387. ggml_context * ctx_layer = ctx_for_layer(i);
  5388. ggml_context * ctx_split = ctx_for_layer_split(i);
  5389. auto & layer = model.layers[i];
  5390. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5391. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5392. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5393. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5394. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5395. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5396. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_embd});
  5397. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_embd, n_embd});
  5398. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_embd});
  5399. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5400. layer.ffn_norm_exps = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM_EXPS, "weight", i), {n_embd});
  5401. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  5402. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  5403. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  5404. }
  5405. } break;
  5406. case LLM_ARCH_DEEPSEEK2:
  5407. {
  5408. bool is_lite = (hparams.n_layer == 27);
  5409. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  5410. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  5411. const uint32_t q_lora_rank = hparams.n_lora_q;
  5412. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  5413. const uint32_t n_ff_exp = hparams.n_ff_exp;
  5414. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5415. // output
  5416. {
  5417. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5418. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5419. }
  5420. for (int i = 0; i < n_layer; ++i) {
  5421. ggml_context * ctx_layer = ctx_for_layer(i);
  5422. ggml_context * ctx_split = ctx_for_layer_split(i);
  5423. auto & layer = model.layers[i];
  5424. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5425. if (!is_lite) {
  5426. layer.attn_q_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank});
  5427. }
  5428. layer.attn_kv_a_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank});
  5429. if (!is_lite) {
  5430. layer.wq_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank});
  5431. layer.wq_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, hparams.n_head * hparams.n_embd_head_k});
  5432. } else {
  5433. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_k_gqa});
  5434. }
  5435. 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});
  5436. layer.wkv_b = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_KV_B, "weight", i), {kv_lora_rank, hparams.n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)});
  5437. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {hparams.n_head * hparams.n_embd_head_v, n_embd});
  5438. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5439. if ((uint32_t) i < hparams.n_layer_dense_lead) {
  5440. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5441. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5442. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5443. } else {
  5444. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  5445. GGML_ASSERT(hparams.n_expert > 0);
  5446. GGML_ASSERT(hparams.n_expert_used > 0);
  5447. // MoE branch
  5448. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5449. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  5450. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  5451. // Shared expert branch
  5452. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * hparams.n_expert_shared});
  5453. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff_exp * hparams.n_expert_shared, n_embd});
  5454. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * hparams.n_expert_shared});
  5455. }
  5456. }
  5457. } break;
  5458. default:
  5459. throw std::runtime_error("unknown architecture");
  5460. }
  5461. }
  5462. ml.done_getting_tensors();
  5463. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  5464. model.mappings.reserve(ml.mappings.size());
  5465. // create the backend buffers
  5466. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  5467. ctx_bufs.reserve(ctx_map.size());
  5468. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  5469. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  5470. model.bufs.reserve(n_max_backend_buffer);
  5471. for (auto & it : ctx_map) {
  5472. ggml_backend_buffer_type_t buft = it.first;
  5473. ggml_context * ctx = it.second;
  5474. llama_buf_map bufs;
  5475. bufs.reserve(n_max_backend_buffer);
  5476. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  5477. // 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
  5478. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  5479. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  5480. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5481. void * addr = nullptr;
  5482. size_t first, last;
  5483. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  5484. if (first >= last) {
  5485. continue;
  5486. }
  5487. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  5488. if (buf == nullptr) {
  5489. throw std::runtime_error("unable to allocate backend CPU buffer");
  5490. }
  5491. model.bufs.push_back(buf);
  5492. bufs.emplace(idx, buf);
  5493. #ifdef GGML_USE_CUDA
  5494. if (n_layer >= n_gpu_layers) {
  5495. ggml_backend_cuda_register_host_buffer(
  5496. ggml_backend_buffer_get_base(buf),
  5497. ggml_backend_buffer_get_size(buf));
  5498. }
  5499. #endif
  5500. }
  5501. }
  5502. #ifdef GGML_USE_METAL
  5503. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  5504. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5505. const size_t max_size = ggml_get_max_tensor_size(ctx);
  5506. void * addr = nullptr;
  5507. size_t first, last;
  5508. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  5509. if (first >= last) {
  5510. continue;
  5511. }
  5512. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  5513. if (buf == nullptr) {
  5514. throw std::runtime_error("unable to allocate backend metal buffer");
  5515. }
  5516. model.bufs.push_back(buf);
  5517. bufs.emplace(idx, buf);
  5518. }
  5519. }
  5520. #endif
  5521. else {
  5522. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  5523. if (buf == nullptr) {
  5524. throw std::runtime_error("unable to allocate backend buffer");
  5525. }
  5526. model.bufs.push_back(buf);
  5527. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  5528. model.mlock_bufs.emplace_back(new llama_mlock);
  5529. auto & mlock_buf = model.mlock_bufs.back();
  5530. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  5531. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  5532. }
  5533. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5534. bufs.emplace(idx, buf);
  5535. }
  5536. }
  5537. if (bufs.empty()) {
  5538. throw std::runtime_error("failed to allocate buffer");
  5539. }
  5540. for (auto & buf : bufs) {
  5541. // indicate that this buffer contains weights
  5542. // 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
  5543. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  5544. }
  5545. ctx_bufs.emplace_back(ctx, bufs);
  5546. }
  5547. if (llama_supports_gpu_offload()) {
  5548. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  5549. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  5550. if (n_gpu_layers > (int) hparams.n_layer) {
  5551. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  5552. }
  5553. const int max_backend_supported_layers = hparams.n_layer + 1;
  5554. const int max_offloadable_layers = hparams.n_layer + 1;
  5555. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  5556. }
  5557. // print memory requirements
  5558. for (ggml_backend_buffer_t buf : model.bufs) {
  5559. 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);
  5560. }
  5561. // populate tensors_by_name
  5562. for (ggml_context * ctx : model.ctxs) {
  5563. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  5564. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  5565. }
  5566. }
  5567. // load tensor data
  5568. for (auto & it : ctx_bufs) {
  5569. ggml_context * ctx = it.first;
  5570. auto & bufs = it.second;
  5571. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  5572. return false;
  5573. }
  5574. }
  5575. if (use_mmap_buffer) {
  5576. for (auto & mapping : ml.mappings) {
  5577. model.mappings.emplace_back(std::move(mapping));
  5578. }
  5579. }
  5580. // loading time will be recalculate after the first eval, so
  5581. // we take page faults deferred by mmap() into consideration
  5582. model.t_load_us = ggml_time_us() - model.t_start_us;
  5583. return true;
  5584. }
  5585. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  5586. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  5587. try {
  5588. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  5589. model.hparams.vocab_only = params.vocab_only;
  5590. try {
  5591. llm_load_arch(ml, model);
  5592. } catch(const std::exception & e) {
  5593. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  5594. }
  5595. try {
  5596. llm_load_hparams(ml, model);
  5597. } catch(const std::exception & e) {
  5598. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  5599. }
  5600. try {
  5601. llm_load_vocab(ml, model);
  5602. } catch(const std::exception & e) {
  5603. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  5604. }
  5605. llm_load_print_meta(ml, model);
  5606. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  5607. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  5608. throw std::runtime_error("vocab size mismatch");
  5609. }
  5610. if (params.vocab_only) {
  5611. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  5612. return 0;
  5613. }
  5614. #ifdef GGML_USE_KOMPUTE
  5615. if (params.n_gpu_layers > 0 && (
  5616. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  5617. || !(
  5618. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  5619. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  5620. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  5621. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  5622. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  5623. )
  5624. )) {
  5625. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  5626. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  5627. params.n_gpu_layers = 0;
  5628. }
  5629. #endif
  5630. #ifdef GGML_USE_SYCL
  5631. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  5632. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  5633. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  5634. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  5635. } else {
  5636. ggml_backend_sycl_set_mul_device_mode();
  5637. }
  5638. #endif
  5639. if (!llm_load_tensors(
  5640. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  5641. params.progress_callback, params.progress_callback_user_data
  5642. )) {
  5643. return -2;
  5644. }
  5645. } catch (const std::exception & err) {
  5646. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  5647. return -1;
  5648. }
  5649. return 0;
  5650. }
  5651. //
  5652. // llm_build
  5653. //
  5654. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  5655. enum llm_ffn_op_type {
  5656. LLM_FFN_SILU,
  5657. LLM_FFN_GELU,
  5658. LLM_FFN_RELU,
  5659. LLM_FFN_RELU_SQR,
  5660. };
  5661. enum llm_ffn_gate_type {
  5662. LLM_FFN_SEQ,
  5663. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  5664. };
  5665. enum llm_norm_type {
  5666. LLM_NORM,
  5667. LLM_NORM_RMS,
  5668. };
  5669. static struct ggml_tensor * llm_build_inp_embd(
  5670. struct ggml_context * ctx,
  5671. struct llama_context & lctx,
  5672. const llama_hparams & hparams,
  5673. const llama_batch & batch,
  5674. struct ggml_tensor * tok_embd,
  5675. const llm_build_cb & cb) {
  5676. const int64_t n_embd = hparams.n_embd;
  5677. struct ggml_tensor * inpL;
  5678. if (batch.token) {
  5679. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  5680. cb(lctx.inp_tokens, "inp_tokens", -1);
  5681. ggml_set_input(lctx.inp_tokens);
  5682. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  5683. } else {
  5684. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  5685. inpL = lctx.inp_embd;
  5686. ggml_set_input(lctx.inp_embd);
  5687. }
  5688. cb(inpL, "inp_embd", -1);
  5689. return inpL;
  5690. }
  5691. static void llm_build_kv_store(
  5692. struct ggml_context * ctx,
  5693. const llama_hparams & hparams,
  5694. const llama_cparams & cparams,
  5695. const llama_kv_cache & kv,
  5696. struct ggml_cgraph * graph,
  5697. struct ggml_tensor * k_cur,
  5698. struct ggml_tensor * v_cur,
  5699. int32_t n_tokens,
  5700. int32_t kv_head,
  5701. const llm_build_cb & cb,
  5702. int64_t il) {
  5703. const int64_t n_ctx = cparams.n_ctx;
  5704. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5705. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5706. GGML_ASSERT(kv.size == n_ctx);
  5707. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  5708. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  5709. cb(k_cache_view, "k_cache_view", il);
  5710. // note: storing RoPE-ed version of K in the KV cache
  5711. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  5712. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  5713. struct ggml_tensor * v_cache_view = nullptr;
  5714. if (cparams.flash_attn) {
  5715. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  5716. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  5717. } else {
  5718. // note: the V cache is transposed when not using flash attention
  5719. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  5720. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  5721. (kv_head)*ggml_element_size(kv.v_l[il]));
  5722. v_cur = ggml_transpose(ctx, v_cur);
  5723. }
  5724. cb(v_cache_view, "v_cache_view", il);
  5725. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  5726. }
  5727. static struct ggml_tensor * llm_build_norm(
  5728. struct ggml_context * ctx,
  5729. struct ggml_tensor * cur,
  5730. const llama_hparams & hparams,
  5731. struct ggml_tensor * mw,
  5732. struct ggml_tensor * mb,
  5733. llm_norm_type type,
  5734. const llm_build_cb & cb,
  5735. int il) {
  5736. switch (type) {
  5737. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  5738. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  5739. }
  5740. if (mw || mb) {
  5741. cb(cur, "norm", il);
  5742. }
  5743. if (mw) {
  5744. cur = ggml_mul(ctx, cur, mw);
  5745. if (mb) {
  5746. cb(cur, "norm_w", il);
  5747. }
  5748. }
  5749. if (mb) {
  5750. cur = ggml_add(ctx, cur, mb);
  5751. }
  5752. return cur;
  5753. }
  5754. static struct ggml_tensor * llm_build_ffn(
  5755. struct ggml_context * ctx,
  5756. struct ggml_tensor * cur,
  5757. struct ggml_tensor * up,
  5758. struct ggml_tensor * up_b,
  5759. struct ggml_tensor * gate,
  5760. struct ggml_tensor * gate_b,
  5761. struct ggml_tensor * down,
  5762. struct ggml_tensor * down_b,
  5763. struct ggml_tensor * act_scales,
  5764. llm_ffn_op_type type_op,
  5765. llm_ffn_gate_type type_gate,
  5766. const llm_build_cb & cb,
  5767. int il) {
  5768. struct ggml_tensor * tmp = up ? ggml_mul_mat(ctx, up, cur) : cur;
  5769. cb(tmp, "ffn_up", il);
  5770. if (up_b) {
  5771. tmp = ggml_add(ctx, tmp, up_b);
  5772. cb(tmp, "ffn_up_b", il);
  5773. }
  5774. if (gate) {
  5775. switch (type_gate) {
  5776. case LLM_FFN_SEQ:
  5777. {
  5778. cur = ggml_mul_mat(ctx, gate, tmp);
  5779. cb(cur, "ffn_gate", il);
  5780. } break;
  5781. case LLM_FFN_PAR:
  5782. {
  5783. cur = ggml_mul_mat(ctx, gate, cur);
  5784. cb(cur, "ffn_gate", il);
  5785. } break;
  5786. }
  5787. if (gate_b) {
  5788. cur = ggml_add(ctx, cur, gate_b);
  5789. cb(cur, "ffn_gate_b", il);
  5790. }
  5791. } else {
  5792. cur = tmp;
  5793. }
  5794. switch (type_op) {
  5795. case LLM_FFN_SILU:
  5796. {
  5797. cur = ggml_silu(ctx, cur);
  5798. cb(cur, "ffn_silu", il);
  5799. } break;
  5800. case LLM_FFN_GELU:
  5801. {
  5802. cur = ggml_gelu(ctx, cur);
  5803. cb(cur, "ffn_gelu", il);
  5804. if (act_scales != NULL) {
  5805. cur = ggml_div(ctx, cur, act_scales);
  5806. cb(cur, "ffn_act", il);
  5807. }
  5808. } break;
  5809. case LLM_FFN_RELU:
  5810. {
  5811. cur = ggml_relu(ctx, cur);
  5812. cb(cur, "ffn_relu", il);
  5813. } break;
  5814. case LLM_FFN_RELU_SQR:
  5815. {
  5816. cur = ggml_relu(ctx, cur);
  5817. cb(cur, "ffn_relu", il);
  5818. cur = ggml_sqr(ctx, cur);
  5819. cb(cur, "ffn_sqr(relu)", il);
  5820. } break;
  5821. }
  5822. if (type_gate == LLM_FFN_PAR) {
  5823. cur = ggml_mul(ctx, cur, tmp);
  5824. cb(cur, "ffn_gate_par", il);
  5825. }
  5826. cur = ggml_mul_mat(ctx, down, cur);
  5827. if (down_b) {
  5828. cb(cur, "ffn_down", il);
  5829. }
  5830. if (down_b) {
  5831. cur = ggml_add(ctx, cur, down_b);
  5832. }
  5833. return cur;
  5834. }
  5835. static struct ggml_tensor * llm_build_moe_ffn(
  5836. struct ggml_context * ctx,
  5837. struct ggml_tensor * cur,
  5838. struct ggml_tensor * gate_inp,
  5839. struct ggml_tensor * up_exps,
  5840. struct ggml_tensor * gate_exps,
  5841. struct ggml_tensor * down_exps,
  5842. int64_t n_expert,
  5843. int64_t n_expert_used,
  5844. llm_ffn_op_type type_op,
  5845. bool norm_w,
  5846. bool scale_w,
  5847. float w_scale,
  5848. const llm_build_cb & cb,
  5849. int il) {
  5850. int64_t n_embd = cur->ne[0];
  5851. int64_t n_tokens = cur->ne[1];
  5852. ggml_tensor * logits = ggml_mul_mat(ctx, gate_inp, cur); // [n_expert, n_tokens]
  5853. cb(logits, "ffn_moe_logits", il);
  5854. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  5855. cb(probs, "ffn_moe_probs", il);
  5856. // select experts
  5857. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  5858. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5859. cb(selected_experts, "ffn_moe_topk", il);
  5860. ggml_tensor * weights = ggml_get_rows(ctx,
  5861. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  5862. cb(weights, "ffn_moe_weights", il);
  5863. if (norm_w) {
  5864. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  5865. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  5866. cb(weights_sum, "ffn_moe_weights_sum", il);
  5867. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  5868. cb(weights, "ffn_moe_weights_norm", il);
  5869. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  5870. }
  5871. if (scale_w) {
  5872. weights = ggml_scale(ctx, weights, w_scale);
  5873. cb(weights, "ffn_moe_weights_scaled", il);
  5874. }
  5875. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  5876. ggml_tensor * up = ggml_mul_mat_id(ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  5877. cb(up, "ffn_moe_up", il);
  5878. ggml_tensor * gate = ggml_mul_mat_id(ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  5879. cb(gate, "ffn_moe_gate", il);
  5880. switch (type_op) {
  5881. case LLM_FFN_SILU:
  5882. {
  5883. gate = ggml_silu(ctx, gate);
  5884. cb(gate, "ffn_moe_silu", il);
  5885. } break;
  5886. case LLM_FFN_GELU:
  5887. {
  5888. gate = ggml_gelu(ctx, gate);
  5889. cb(gate, "ffn_moe_gelu", il);
  5890. } break;
  5891. default:
  5892. GGML_ASSERT(false);
  5893. }
  5894. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  5895. cb(par, "ffn_moe_gate_par", il);
  5896. ggml_tensor * experts = ggml_mul_mat_id(ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  5897. cb(experts, "ffn_moe_down", il);
  5898. experts = ggml_mul(ctx, experts, weights);
  5899. // aggregate experts
  5900. ggml_tensor * moe_out = nullptr;
  5901. for (int i = 0; i < n_expert_used; ++i) {
  5902. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  5903. experts->nb[2], i*experts->nb[1]);
  5904. if (i == 0) {
  5905. moe_out = cur_expert;
  5906. } else {
  5907. moe_out = ggml_add(ctx, moe_out, cur_expert);
  5908. }
  5909. }
  5910. if (n_expert_used == 1) {
  5911. // avoid returning a non-contiguous tensor
  5912. moe_out = ggml_cont(ctx, moe_out);
  5913. }
  5914. return moe_out;
  5915. }
  5916. static struct ggml_tensor * llm_build_kqv(
  5917. struct ggml_context * ctx,
  5918. const llama_model & model,
  5919. const llama_hparams & hparams,
  5920. const llama_cparams & cparams,
  5921. const llama_kv_cache & kv,
  5922. struct ggml_cgraph * graph,
  5923. struct ggml_tensor * wo,
  5924. struct ggml_tensor * wo_b,
  5925. struct ggml_tensor * q_cur,
  5926. struct ggml_tensor * kq_mask,
  5927. int32_t n_tokens,
  5928. int32_t n_kv,
  5929. float kq_scale,
  5930. const llm_build_cb & cb,
  5931. int il) {
  5932. const int64_t n_ctx = cparams.n_ctx;
  5933. const int64_t n_head = hparams.n_head;
  5934. const int64_t n_head_kv = hparams.n_head_kv;
  5935. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5936. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5937. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5938. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5939. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  5940. cb(q, "q", il);
  5941. struct ggml_tensor * k =
  5942. ggml_view_3d(ctx, kv.k_l[il],
  5943. n_embd_head_k, n_kv, n_head_kv,
  5944. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  5945. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  5946. 0);
  5947. cb(k, "k", il);
  5948. struct ggml_tensor * cur;
  5949. if (cparams.flash_attn) {
  5950. GGML_UNUSED(model);
  5951. GGML_UNUSED(n_ctx);
  5952. // split cached v into n_head heads (not transposed)
  5953. struct ggml_tensor * v =
  5954. ggml_view_3d(ctx, kv.v_l[il],
  5955. n_embd_head_v, n_kv, n_head_kv,
  5956. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  5957. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  5958. 0);
  5959. cb(v, "v", il);
  5960. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  5961. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX) {
  5962. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  5963. }
  5964. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  5965. } else {
  5966. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  5967. cb(kq, "kq", il);
  5968. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3 || model.arch == LLM_ARCH_GPTNEOX) {
  5969. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  5970. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  5971. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5972. }
  5973. if (model.arch == LLM_ARCH_GROK) {
  5974. // need to do the following:
  5975. // multiply by attn_output_multiplyer of 0.08838834764831845
  5976. // and then :
  5977. // kq = 30 * tanh(kq / 30)
  5978. // before the softmax below
  5979. //try from phi2
  5980. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5981. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  5982. kq = ggml_scale(ctx, kq, 30);
  5983. }
  5984. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  5985. cb(kq, "kq_soft_max_ext", il);
  5986. GGML_ASSERT(kv.size == n_ctx);
  5987. // split cached v into n_head heads
  5988. struct ggml_tensor * v =
  5989. ggml_view_3d(ctx, kv.v_l[il],
  5990. n_kv, n_embd_head_v, n_head_kv,
  5991. ggml_element_size(kv.v_l[il])*n_ctx,
  5992. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  5993. 0);
  5994. cb(v, "v", il);
  5995. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  5996. cb(kqv, "kqv", il);
  5997. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  5998. cb(kqv_merged, "kqv_merged", il);
  5999. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  6000. cb(cur, "kqv_merged_cont", il);
  6001. }
  6002. ggml_build_forward_expand(graph, cur);
  6003. cur = ggml_mul_mat(ctx, wo, cur);
  6004. if (wo_b) {
  6005. cb(cur, "kqv_wo", il);
  6006. }
  6007. if (wo_b) {
  6008. cur = ggml_add(ctx, cur, wo_b);
  6009. }
  6010. return cur;
  6011. }
  6012. static struct ggml_tensor * llm_build_kv(
  6013. struct ggml_context * ctx,
  6014. const llama_model & model,
  6015. const llama_hparams & hparams,
  6016. const llama_cparams & cparams,
  6017. const llama_kv_cache & kv,
  6018. struct ggml_cgraph * graph,
  6019. struct ggml_tensor * wo,
  6020. struct ggml_tensor * wo_b,
  6021. struct ggml_tensor * k_cur,
  6022. struct ggml_tensor * v_cur,
  6023. struct ggml_tensor * q_cur,
  6024. struct ggml_tensor * kq_mask,
  6025. int32_t n_tokens,
  6026. int32_t kv_head,
  6027. int32_t n_kv,
  6028. float kq_scale,
  6029. const llm_build_cb & cb,
  6030. int il) {
  6031. // these nodes are added to the graph together so that they are not reordered
  6032. // by doing so, the number of splits in the graph is reduced
  6033. ggml_build_forward_expand(graph, q_cur);
  6034. ggml_build_forward_expand(graph, k_cur);
  6035. ggml_build_forward_expand(graph, v_cur);
  6036. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  6037. struct ggml_tensor * cur;
  6038. cur = llm_build_kqv(ctx, model, hparams, cparams, kv, graph, wo, wo_b,
  6039. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  6040. cb(cur, "kqv_out", il);
  6041. return cur;
  6042. }
  6043. struct llm_build_context {
  6044. const llama_model & model;
  6045. llama_context & lctx;
  6046. const llama_hparams & hparams;
  6047. const llama_cparams & cparams;
  6048. const llama_batch & batch;
  6049. const llama_kv_cache & kv_self;
  6050. const int64_t n_embd;
  6051. const int64_t n_layer;
  6052. const int64_t n_rot;
  6053. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  6054. const int64_t n_head;
  6055. const int64_t n_head_kv;
  6056. const int64_t n_embd_head_k;
  6057. const int64_t n_embd_k_gqa;
  6058. const int64_t n_embd_head_v;
  6059. const int64_t n_embd_v_gqa;
  6060. const int64_t n_expert;
  6061. const int64_t n_expert_used;
  6062. const float freq_base;
  6063. const float freq_scale;
  6064. const float ext_factor;
  6065. const float attn_factor;
  6066. const float beta_fast;
  6067. const float beta_slow;
  6068. const float norm_eps;
  6069. const float norm_rms_eps;
  6070. const int32_t n_tokens;
  6071. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  6072. const int32_t n_outputs;
  6073. const int32_t kv_head; // index of where we store new KV data in the cache
  6074. const int32_t n_orig_ctx;
  6075. const bool flash_attn;
  6076. const enum llama_pooling_type pooling_type;
  6077. const enum llama_rope_type rope_type;
  6078. const llm_build_cb & cb;
  6079. std::vector<uint8_t> & buf_compute_meta;
  6080. struct ggml_context * ctx0 = nullptr;
  6081. // TODO: consider making the entire interface noexcept
  6082. llm_build_context(
  6083. llama_context & lctx,
  6084. const llama_batch & batch,
  6085. const llm_build_cb & cb,
  6086. bool worst_case) :
  6087. model (lctx.model),
  6088. lctx (lctx),
  6089. hparams (model.hparams),
  6090. cparams (lctx.cparams),
  6091. batch (batch),
  6092. kv_self (lctx.kv_self),
  6093. n_embd (hparams.n_embd),
  6094. n_layer (hparams.n_layer),
  6095. n_rot (hparams.n_rot),
  6096. n_ctx (cparams.n_ctx),
  6097. n_head (hparams.n_head),
  6098. n_head_kv (hparams.n_head_kv),
  6099. n_embd_head_k (hparams.n_embd_head_k),
  6100. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  6101. n_embd_head_v (hparams.n_embd_head_v),
  6102. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  6103. n_expert (hparams.n_expert),
  6104. n_expert_used (hparams.n_expert_used),
  6105. freq_base (cparams.rope_freq_base),
  6106. freq_scale (cparams.rope_freq_scale),
  6107. ext_factor (cparams.yarn_ext_factor),
  6108. attn_factor (cparams.yarn_attn_factor),
  6109. beta_fast (cparams.yarn_beta_fast),
  6110. beta_slow (cparams.yarn_beta_slow),
  6111. norm_eps (hparams.f_norm_eps),
  6112. norm_rms_eps (hparams.f_norm_rms_eps),
  6113. n_tokens (batch.n_tokens),
  6114. n_kv (worst_case ? kv_self.size : kv_self.n),
  6115. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  6116. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  6117. n_orig_ctx (cparams.n_yarn_orig_ctx),
  6118. flash_attn (cparams.flash_attn),
  6119. pooling_type (cparams.pooling_type),
  6120. rope_type (hparams.rope_type),
  6121. cb (cb),
  6122. buf_compute_meta (lctx.buf_compute_meta) {
  6123. // all initializations should be done in init()
  6124. }
  6125. void init() {
  6126. struct ggml_init_params params = {
  6127. /*.mem_size =*/ buf_compute_meta.size(),
  6128. /*.mem_buffer =*/ buf_compute_meta.data(),
  6129. /*.no_alloc =*/ true,
  6130. };
  6131. ctx0 = ggml_init(params);
  6132. lctx.inp_tokens = nullptr;
  6133. lctx.inp_embd = nullptr;
  6134. lctx.inp_pos = nullptr;
  6135. lctx.inp_out_ids = nullptr;
  6136. lctx.inp_KQ_mask = nullptr;
  6137. lctx.inp_K_shift = nullptr;
  6138. lctx.inp_mean = nullptr;
  6139. lctx.inp_cls = nullptr;
  6140. lctx.inp_s_copy = nullptr;
  6141. lctx.inp_s_mask = nullptr;
  6142. lctx.inp_s_seq = nullptr;
  6143. }
  6144. void free() {
  6145. if (ctx0) {
  6146. ggml_free(ctx0);
  6147. ctx0 = nullptr;
  6148. }
  6149. }
  6150. struct ggml_cgraph * build_k_shift() {
  6151. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6152. GGML_ASSERT(kv_self.size == n_ctx);
  6153. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  6154. cb(lctx.inp_K_shift, "K_shift", -1);
  6155. ggml_set_input(lctx.inp_K_shift);
  6156. for (int il = 0; il < n_layer; ++il) {
  6157. struct ggml_tensor * rope_factors = build_rope_factors(il);
  6158. struct ggml_tensor * tmp =
  6159. // we rotate only the first n_rot dimensions
  6160. ggml_rope_ext_inplace(ctx0,
  6161. ggml_view_3d(ctx0, kv_self.k_l[il],
  6162. n_embd_head_k, n_head_kv, n_ctx,
  6163. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  6164. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  6165. 0),
  6166. lctx.inp_K_shift, rope_factors, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6167. ext_factor, attn_factor, beta_fast, beta_slow);
  6168. cb(tmp, "K_shifted", il);
  6169. ggml_build_forward_expand(gf, tmp);
  6170. }
  6171. return gf;
  6172. }
  6173. struct ggml_cgraph * build_s_copy() {
  6174. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6175. GGML_ASSERT(kv_self.recurrent);
  6176. struct ggml_tensor * state_copy = build_inp_s_copy();
  6177. for (int il = 0; il < n_layer; ++il) {
  6178. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  6179. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  6180. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  6181. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  6182. // TODO: name the intermediate tensors with cb()
  6183. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  6184. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  6185. }
  6186. return gf;
  6187. }
  6188. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  6189. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6190. for (uint32_t i = 0; i < ids.size(); ++i) {
  6191. const uint32_t id = ids[i];
  6192. if (i == id || id == ids.size()) {
  6193. continue;
  6194. }
  6195. uint32_t nm = 1;
  6196. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  6197. nm++;
  6198. }
  6199. for (int il = 0; il < n_layer; ++il) {
  6200. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  6201. n_embd_k_gqa, nm,
  6202. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  6203. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  6204. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  6205. n_embd_k_gqa, nm,
  6206. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  6207. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  6208. ggml_tensor * view_v_src;
  6209. ggml_tensor * view_v_dst;
  6210. if (flash_attn) {
  6211. // NOTE: the V cache is not transposed when using flash attention
  6212. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  6213. n_embd_v_gqa, nm,
  6214. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  6215. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  6216. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  6217. n_embd_v_gqa, nm,
  6218. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  6219. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  6220. } else {
  6221. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  6222. nm, n_embd_v_gqa,
  6223. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  6224. ggml_row_size(kv_self.v_l[il]->type, i));
  6225. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  6226. nm, n_embd_v_gqa,
  6227. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  6228. ggml_row_size(kv_self.v_l[il]->type, id));
  6229. }
  6230. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  6231. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  6232. }
  6233. i += nm - 1;
  6234. }
  6235. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  6236. return gf;
  6237. }
  6238. struct ggml_tensor * build_inp_pos() {
  6239. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  6240. cb(lctx.inp_pos, "inp_pos", -1);
  6241. ggml_set_input(lctx.inp_pos);
  6242. return lctx.inp_pos;
  6243. }
  6244. struct ggml_tensor * build_rope_factors(int il) {
  6245. // choose long/short freq factors based on the context size
  6246. const auto n_ctx_pre_seq = cparams.n_ctx / cparams.n_seq_max;
  6247. if (n_ctx_pre_seq > hparams.n_yarn_orig_ctx) {
  6248. return model.layers[il].rope_long;
  6249. }
  6250. return model.layers[il].rope_short;
  6251. }
  6252. struct ggml_tensor * build_inp_out_ids() {
  6253. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  6254. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  6255. ggml_set_input(lctx.inp_out_ids);
  6256. return lctx.inp_out_ids;
  6257. }
  6258. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  6259. if (causal) {
  6260. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  6261. } else {
  6262. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  6263. }
  6264. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  6265. ggml_set_input(lctx.inp_KQ_mask);
  6266. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  6267. }
  6268. struct ggml_tensor * build_inp_mean() {
  6269. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  6270. cb(lctx.inp_mean, "inp_mean", -1);
  6271. ggml_set_input(lctx.inp_mean);
  6272. return lctx.inp_mean;
  6273. }
  6274. struct ggml_tensor * build_inp_cls() {
  6275. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  6276. cb(lctx.inp_cls, "inp_cls", -1);
  6277. ggml_set_input(lctx.inp_cls);
  6278. return lctx.inp_cls;
  6279. }
  6280. struct ggml_tensor * build_inp_s_copy() {
  6281. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  6282. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  6283. ggml_set_input(lctx.inp_s_copy);
  6284. return lctx.inp_s_copy;
  6285. }
  6286. struct ggml_tensor * build_inp_s_mask() {
  6287. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  6288. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  6289. ggml_set_input(lctx.inp_s_mask);
  6290. return lctx.inp_s_mask;
  6291. }
  6292. struct ggml_tensor * build_inp_s_seq() {
  6293. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  6294. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  6295. ggml_set_input(lctx.inp_s_seq);
  6296. return lctx.inp_s_seq;
  6297. }
  6298. struct ggml_cgraph * build_llama() {
  6299. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6300. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6301. int32_t n_tokens = this->n_tokens;
  6302. const int64_t n_embd_head = hparams.n_embd_head_v;
  6303. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6304. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6305. struct ggml_tensor * cur;
  6306. struct ggml_tensor * inpL;
  6307. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6308. // inp_pos - contains the positions
  6309. struct ggml_tensor * inp_pos = build_inp_pos();
  6310. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6311. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6312. for (int il = 0; il < n_layer; ++il) {
  6313. struct ggml_tensor * inpSA = inpL;
  6314. // norm
  6315. cur = llm_build_norm(ctx0, inpL, hparams,
  6316. model.layers[il].attn_norm, NULL,
  6317. LLM_NORM_RMS, cb, il);
  6318. cb(cur, "attn_norm", il);
  6319. // self-attention
  6320. {
  6321. // compute Q and K and RoPE them
  6322. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6323. cb(Qcur, "Qcur", il);
  6324. if (model.layers[il].bq) {
  6325. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6326. cb(Qcur, "Qcur", il);
  6327. }
  6328. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6329. cb(Kcur, "Kcur", il);
  6330. if (model.layers[il].bk) {
  6331. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6332. cb(Kcur, "Kcur", il);
  6333. }
  6334. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6335. cb(Vcur, "Vcur", il);
  6336. if (model.layers[il].bv) {
  6337. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6338. cb(Vcur, "Vcur", il);
  6339. }
  6340. Qcur = ggml_rope_ext(
  6341. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6342. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6343. ext_factor, attn_factor, beta_fast, beta_slow
  6344. );
  6345. cb(Qcur, "Qcur", il);
  6346. Kcur = ggml_rope_ext(
  6347. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6348. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6349. ext_factor, attn_factor, beta_fast, beta_slow
  6350. );
  6351. cb(Kcur, "Kcur", il);
  6352. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6353. model.layers[il].wo, model.layers[il].bo,
  6354. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6355. }
  6356. if (il == n_layer - 1) {
  6357. // skip computing output for unused tokens
  6358. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6359. n_tokens = n_outputs;
  6360. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6361. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6362. }
  6363. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6364. cb(ffn_inp, "ffn_inp", il);
  6365. // feed-forward network
  6366. if (model.layers[il].ffn_gate_inp == nullptr) {
  6367. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6368. model.layers[il].ffn_norm, NULL,
  6369. LLM_NORM_RMS, cb, il);
  6370. cb(cur, "ffn_norm", il);
  6371. cur = llm_build_ffn(ctx0, cur,
  6372. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6373. model.layers[il].ffn_gate, model.layers[il].ffn_gate_b,
  6374. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6375. NULL,
  6376. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6377. cb(cur, "ffn_out", il);
  6378. } else {
  6379. // MoE branch
  6380. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6381. model.layers[il].ffn_norm, NULL,
  6382. LLM_NORM_RMS, cb, il);
  6383. cb(cur, "ffn_norm", il);
  6384. cur = llm_build_moe_ffn(ctx0, cur,
  6385. model.layers[il].ffn_gate_inp,
  6386. model.layers[il].ffn_up_exps,
  6387. model.layers[il].ffn_gate_exps,
  6388. model.layers[il].ffn_down_exps,
  6389. n_expert, n_expert_used,
  6390. LLM_FFN_SILU, true,
  6391. false, 0.0,
  6392. cb, il);
  6393. cb(cur, "ffn_moe_out", il);
  6394. }
  6395. cur = ggml_add(ctx0, cur, ffn_inp);
  6396. cb(cur, "ffn_out", il);
  6397. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6398. if (layer_dir != nullptr) {
  6399. cur = ggml_add(ctx0, cur, layer_dir);
  6400. }
  6401. cb(cur, "l_out", il);
  6402. // input for next layer
  6403. inpL = cur;
  6404. }
  6405. cur = inpL;
  6406. cur = llm_build_norm(ctx0, cur, hparams,
  6407. model.output_norm, NULL,
  6408. LLM_NORM_RMS, cb, -1);
  6409. cb(cur, "result_norm", -1);
  6410. // lm_head
  6411. cur = ggml_mul_mat(ctx0, model.output, cur);
  6412. cb(cur, "result_output", -1);
  6413. ggml_build_forward_expand(gf, cur);
  6414. return gf;
  6415. }
  6416. struct ggml_cgraph * build_baichuan() {
  6417. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6418. const int64_t n_embd_head = hparams.n_embd_head_v;
  6419. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6420. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6421. struct ggml_tensor * cur;
  6422. struct ggml_tensor * inpL;
  6423. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6424. // inp_pos - contains the positions
  6425. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  6426. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6427. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6428. for (int il = 0; il < n_layer; ++il) {
  6429. struct ggml_tensor * inpSA = inpL;
  6430. cur = llm_build_norm(ctx0, inpL, hparams,
  6431. model.layers[il].attn_norm, NULL,
  6432. LLM_NORM_RMS, cb, il);
  6433. cb(cur, "attn_norm", il);
  6434. // self-attention
  6435. {
  6436. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6437. cb(Qcur, "Qcur", il);
  6438. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6439. cb(Kcur, "Kcur", il);
  6440. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6441. cb(Vcur, "Vcur", il);
  6442. switch (model.type) {
  6443. case MODEL_7B:
  6444. Qcur = ggml_rope_ext(
  6445. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6446. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6447. ext_factor, attn_factor, beta_fast, beta_slow
  6448. );
  6449. Kcur = ggml_rope_ext(
  6450. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6451. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6452. ext_factor, attn_factor, beta_fast, beta_slow
  6453. );
  6454. break;
  6455. case MODEL_13B:
  6456. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  6457. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  6458. break;
  6459. default:
  6460. GGML_ASSERT(false);
  6461. }
  6462. cb(Qcur, "Qcur", il);
  6463. cb(Kcur, "Kcur", il);
  6464. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6465. model.layers[il].wo, NULL,
  6466. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6467. }
  6468. if (il == n_layer - 1) {
  6469. // skip computing output for unused tokens
  6470. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6471. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6472. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6473. }
  6474. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6475. cb(ffn_inp, "ffn_inp", il);
  6476. // feed-forward network
  6477. {
  6478. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6479. model.layers[il].ffn_norm, NULL,
  6480. LLM_NORM_RMS, cb, il);
  6481. cb(cur, "ffn_norm", il);
  6482. cur = llm_build_ffn(ctx0, cur,
  6483. model.layers[il].ffn_up, NULL,
  6484. model.layers[il].ffn_gate, NULL,
  6485. model.layers[il].ffn_down, NULL,
  6486. NULL,
  6487. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6488. cb(cur, "ffn_out", il);
  6489. }
  6490. cur = ggml_add(ctx0, cur, ffn_inp);
  6491. cb(cur, "l_out", il);
  6492. // input for next layer
  6493. inpL = cur;
  6494. }
  6495. cur = inpL;
  6496. cur = llm_build_norm(ctx0, cur, hparams,
  6497. model.output_norm, NULL,
  6498. LLM_NORM_RMS, cb, -1);
  6499. cb(cur, "result_norm", -1);
  6500. // lm_head
  6501. cur = ggml_mul_mat(ctx0, model.output, cur);
  6502. cb(cur, "result_output", -1);
  6503. ggml_build_forward_expand(gf, cur);
  6504. return gf;
  6505. }
  6506. struct ggml_cgraph * build_xverse() {
  6507. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6508. const int64_t n_embd_head = hparams.n_embd_head_v;
  6509. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6510. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6511. struct ggml_tensor * cur;
  6512. struct ggml_tensor * inpL;
  6513. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6514. // inp_pos - contains the positions
  6515. struct ggml_tensor * inp_pos = build_inp_pos();
  6516. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6517. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6518. for (int il = 0; il < n_layer; ++il) {
  6519. struct ggml_tensor * inpSA = inpL;
  6520. cur = llm_build_norm(ctx0, inpL, hparams,
  6521. model.layers[il].attn_norm, NULL,
  6522. LLM_NORM_RMS, cb, il);
  6523. cb(cur, "attn_norm", il);
  6524. // self-attention
  6525. {
  6526. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6527. cb(Qcur, "Qcur", il);
  6528. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6529. cb(Kcur, "Kcur", il);
  6530. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6531. cb(Vcur, "Vcur", il);
  6532. Qcur = ggml_rope_ext(
  6533. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6534. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6535. ext_factor, attn_factor, beta_fast, beta_slow
  6536. );
  6537. cb(Qcur, "Qcur", il);
  6538. Kcur = ggml_rope_ext(
  6539. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6540. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6541. ext_factor, attn_factor, beta_fast, beta_slow
  6542. );
  6543. cb(Kcur, "Kcur", il);
  6544. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6545. model.layers[il].wo, NULL,
  6546. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6547. }
  6548. if (il == n_layer - 1) {
  6549. // skip computing output for unused tokens
  6550. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6551. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6552. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6553. }
  6554. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6555. cb(ffn_inp, "ffn_inp", il);
  6556. // feed-forward network
  6557. {
  6558. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6559. model.layers[il].ffn_norm, NULL,
  6560. LLM_NORM_RMS, cb, il);
  6561. cb(cur, "ffn_norm", il);
  6562. cur = llm_build_ffn(ctx0, cur,
  6563. model.layers[il].ffn_up, NULL,
  6564. model.layers[il].ffn_gate, NULL,
  6565. model.layers[il].ffn_down, NULL,
  6566. NULL,
  6567. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6568. cb(cur, "ffn_out", il);
  6569. }
  6570. cur = ggml_add(ctx0, cur, ffn_inp);
  6571. cb(cur, "l_out", il);
  6572. // input for next layer
  6573. inpL = cur;
  6574. }
  6575. cur = inpL;
  6576. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  6577. cb(cur, "result_norm", -1);
  6578. // lm_head
  6579. cur = ggml_mul_mat(ctx0, model.output, cur);
  6580. cb(cur, "result_output", -1);
  6581. ggml_build_forward_expand(gf, cur);
  6582. return gf;
  6583. }
  6584. struct ggml_cgraph * build_falcon() {
  6585. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6586. const int64_t n_embd_head = hparams.n_embd_head_v;
  6587. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6588. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6589. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6590. struct ggml_tensor * cur;
  6591. struct ggml_tensor * inpL;
  6592. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6593. // inp_pos - contains the positions
  6594. struct ggml_tensor * inp_pos = build_inp_pos();
  6595. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6596. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6597. for (int il = 0; il < n_layer; ++il) {
  6598. struct ggml_tensor * attn_norm;
  6599. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6600. model.layers[il].attn_norm,
  6601. model.layers[il].attn_norm_b,
  6602. LLM_NORM, cb, il);
  6603. cb(attn_norm, "attn_norm", il);
  6604. // self-attention
  6605. {
  6606. if (model.layers[il].attn_norm_2) {
  6607. // Falcon-40B
  6608. cur = llm_build_norm(ctx0, inpL, hparams,
  6609. model.layers[il].attn_norm_2,
  6610. model.layers[il].attn_norm_2_b,
  6611. LLM_NORM, cb, il);
  6612. cb(cur, "attn_norm_2", il);
  6613. } else {
  6614. cur = attn_norm;
  6615. }
  6616. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6617. cb(cur, "wqkv", il);
  6618. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6619. 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)));
  6620. 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)));
  6621. cb(Qcur, "Qcur", il);
  6622. cb(Kcur, "Kcur", il);
  6623. cb(Vcur, "Vcur", il);
  6624. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6625. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6626. // using mode = 2 for neox mode
  6627. Qcur = ggml_rope_ext(
  6628. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  6629. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6630. );
  6631. cb(Qcur, "Qcur", il);
  6632. Kcur = ggml_rope_ext(
  6633. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  6634. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6635. );
  6636. cb(Kcur, "Kcur", il);
  6637. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6638. model.layers[il].wo, NULL,
  6639. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6640. }
  6641. if (il == n_layer - 1) {
  6642. // skip computing output for unused tokens
  6643. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6644. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6645. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6646. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  6647. }
  6648. struct ggml_tensor * ffn_inp = cur;
  6649. // feed forward
  6650. {
  6651. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  6652. model.layers[il].ffn_up, NULL,
  6653. NULL, NULL,
  6654. model.layers[il].ffn_down, NULL,
  6655. NULL,
  6656. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6657. cb(cur, "ffn_out", il);
  6658. }
  6659. cur = ggml_add(ctx0, cur, ffn_inp);
  6660. cb(cur, "l_out", il);
  6661. cur = ggml_add(ctx0, cur, inpL);
  6662. cb(cur, "l_out", il);
  6663. // input for next layer
  6664. inpL = cur;
  6665. }
  6666. cur = inpL;
  6667. // norm
  6668. cur = llm_build_norm(ctx0, cur, hparams,
  6669. model.output_norm,
  6670. model.output_norm_b,
  6671. LLM_NORM, cb, -1);
  6672. cb(cur, "result_norm", -1);
  6673. cur = ggml_mul_mat(ctx0, model.output, cur);
  6674. cb(cur, "result_output", -1);
  6675. ggml_build_forward_expand(gf, cur);
  6676. return gf;
  6677. }
  6678. struct ggml_cgraph * build_grok() {
  6679. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6680. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6681. int32_t n_tokens = this->n_tokens;
  6682. const int64_t n_embd_head = hparams.n_embd_head_v;
  6683. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6684. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6685. struct ggml_tensor * cur;
  6686. struct ggml_tensor * inpL;
  6687. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6688. // multiply by embedding_multiplier_scale of 78.38367176906169
  6689. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  6690. // inp_pos - contains the positions
  6691. struct ggml_tensor * inp_pos = build_inp_pos();
  6692. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6693. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6694. for (int il = 0; il < n_layer; ++il) {
  6695. struct ggml_tensor * inpSA = inpL;
  6696. // norm
  6697. cur = llm_build_norm(ctx0, inpL, hparams,
  6698. model.layers[il].attn_norm, NULL,
  6699. LLM_NORM_RMS, cb, il);
  6700. cb(cur, "attn_norm", il);
  6701. // self-attention
  6702. {
  6703. // compute Q and K and RoPE them
  6704. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6705. cb(Qcur, "Qcur", il);
  6706. if (model.layers[il].bq) {
  6707. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6708. cb(Qcur, "Qcur", il);
  6709. }
  6710. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6711. cb(Kcur, "Kcur", il);
  6712. if (model.layers[il].bk) {
  6713. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6714. cb(Kcur, "Kcur", il);
  6715. }
  6716. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6717. cb(Vcur, "Vcur", il);
  6718. if (model.layers[il].bv) {
  6719. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6720. cb(Vcur, "Vcur", il);
  6721. }
  6722. Qcur = ggml_rope_ext(
  6723. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6724. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6725. ext_factor, attn_factor, beta_fast, beta_slow
  6726. );
  6727. cb(Qcur, "Qcur", il);
  6728. Kcur = ggml_rope_ext(
  6729. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6730. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6731. ext_factor, attn_factor, beta_fast, beta_slow
  6732. );
  6733. cb(Kcur, "Kcur", il);
  6734. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6735. model.layers[il].wo, model.layers[il].bo,
  6736. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6737. }
  6738. if (il == n_layer - 1) {
  6739. // skip computing output for unused tokens
  6740. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6741. n_tokens = n_outputs;
  6742. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6743. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6744. }
  6745. // Grok
  6746. // if attn_out_norm is present then apply it before adding the input
  6747. if (model.layers[il].attn_out_norm) {
  6748. cur = llm_build_norm(ctx0, cur, hparams,
  6749. model.layers[il].attn_out_norm, NULL,
  6750. LLM_NORM_RMS, cb, il);
  6751. cb(cur, "attn_out_norm", il);
  6752. }
  6753. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6754. cb(ffn_inp, "ffn_inp", il);
  6755. // feed-forward network
  6756. // MoE branch
  6757. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6758. model.layers[il].ffn_norm, NULL,
  6759. LLM_NORM_RMS, cb, il);
  6760. cb(cur, "ffn_norm", il);
  6761. cur = llm_build_moe_ffn(ctx0, cur,
  6762. model.layers[il].ffn_gate_inp,
  6763. model.layers[il].ffn_up_exps,
  6764. model.layers[il].ffn_gate_exps,
  6765. model.layers[il].ffn_down_exps,
  6766. n_expert, n_expert_used,
  6767. LLM_FFN_GELU, true,
  6768. false, 0.0,
  6769. cb, il);
  6770. cb(cur, "ffn_moe_out", il);
  6771. // Grok
  6772. // if layer_out_norm is present then apply it before adding the input
  6773. // Idea: maybe ffn_out_norm is a better name
  6774. if (model.layers[il].layer_out_norm) {
  6775. cur = llm_build_norm(ctx0, cur, hparams,
  6776. model.layers[il].layer_out_norm, NULL,
  6777. LLM_NORM_RMS, cb, il);
  6778. cb(cur, "layer_out_norm", il);
  6779. }
  6780. cur = ggml_add(ctx0, cur, ffn_inp);
  6781. cb(cur, "ffn_out", il);
  6782. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6783. if (layer_dir != nullptr) {
  6784. cur = ggml_add(ctx0, cur, layer_dir);
  6785. }
  6786. cb(cur, "l_out", il);
  6787. // input for next layer
  6788. inpL = cur;
  6789. }
  6790. cur = inpL;
  6791. cur = llm_build_norm(ctx0, cur, hparams,
  6792. model.output_norm, NULL,
  6793. LLM_NORM_RMS, cb, -1);
  6794. cb(cur, "result_norm", -1);
  6795. // lm_head
  6796. cur = ggml_mul_mat(ctx0, model.output, cur);
  6797. // Grok
  6798. // multiply logits by output_multiplier_scale of 0.5773502691896257
  6799. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  6800. cb(cur, "result_output", -1);
  6801. ggml_build_forward_expand(gf, cur);
  6802. return gf;
  6803. }
  6804. struct ggml_cgraph * build_dbrx() {
  6805. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6806. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6807. int32_t n_tokens = this->n_tokens;
  6808. const int64_t n_embd_head = hparams.n_embd_head_v;
  6809. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6810. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6811. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6812. struct ggml_tensor * cur;
  6813. struct ggml_tensor * inpL;
  6814. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6815. // inp_pos - contains the positions
  6816. struct ggml_tensor * inp_pos = build_inp_pos();
  6817. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6818. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6819. for (int il = 0; il < n_layer; ++il) {
  6820. struct ggml_tensor * inpSA = inpL;
  6821. // norm
  6822. cur = llm_build_norm(ctx0, inpL, hparams,
  6823. model.layers[il].attn_norm, NULL,
  6824. LLM_NORM, cb, il);
  6825. cb(cur, "attn_norm", il);
  6826. // self-attention
  6827. {
  6828. struct ggml_tensor * Qcur = nullptr;
  6829. struct ggml_tensor * Kcur = nullptr;
  6830. struct ggml_tensor * Vcur = nullptr;
  6831. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6832. cb(cur, "wqkv", il);
  6833. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6834. cb(cur, "wqkv_clamped", il);
  6835. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6836. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6837. 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)));
  6838. cb(Qcur, "Qcur", il);
  6839. cb(Kcur, "Kcur", il);
  6840. cb(Vcur, "Vcur", il);
  6841. Qcur = ggml_rope_ext(
  6842. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  6843. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6844. ext_factor, attn_factor, beta_fast, beta_slow
  6845. );
  6846. cb(Qcur, "Qcur", il);
  6847. Kcur = ggml_rope_ext(
  6848. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  6849. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6850. ext_factor, attn_factor, beta_fast, beta_slow
  6851. );
  6852. cb(Kcur, "Kcur", il);
  6853. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6854. model.layers[il].wo, NULL,
  6855. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6856. }
  6857. if (il == n_layer - 1) {
  6858. // skip computing output for unused tokens
  6859. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6860. n_tokens = n_outputs;
  6861. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6862. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6863. }
  6864. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6865. cb(ffn_inp, "ffn_inp", il);
  6866. // feed-forward network
  6867. // MoE branch
  6868. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6869. model.layers[il].attn_out_norm, NULL,
  6870. LLM_NORM, cb, il);
  6871. cb(cur, "attn_out_norm", il);
  6872. cur = llm_build_moe_ffn(ctx0, cur,
  6873. model.layers[il].ffn_gate_inp,
  6874. model.layers[il].ffn_up_exps,
  6875. model.layers[il].ffn_gate_exps,
  6876. model.layers[il].ffn_down_exps,
  6877. n_expert, n_expert_used,
  6878. LLM_FFN_SILU, true,
  6879. false, 0.0,
  6880. cb, il);
  6881. cb(cur, "ffn_moe_out", il);
  6882. cur = ggml_add(ctx0, cur, ffn_inp);
  6883. cb(cur, "ffn_out", il);
  6884. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6885. if (layer_dir != nullptr) {
  6886. cur = ggml_add(ctx0, cur, layer_dir);
  6887. }
  6888. cb(cur, "l_out", il);
  6889. // input for next layer
  6890. inpL = cur;
  6891. }
  6892. cur = inpL;
  6893. cur = llm_build_norm(ctx0, cur, hparams,
  6894. model.output_norm, NULL,
  6895. LLM_NORM, cb, -1);
  6896. cb(cur, "result_norm", -1);
  6897. // lm_head
  6898. cur = ggml_mul_mat(ctx0, model.output, cur);
  6899. cb(cur, "result_output", -1);
  6900. ggml_build_forward_expand(gf, cur);
  6901. return gf;
  6902. }
  6903. struct ggml_cgraph * build_starcoder() {
  6904. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6905. const int64_t n_embd_head = hparams.n_embd_head_v;
  6906. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6907. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6908. struct ggml_tensor * cur;
  6909. struct ggml_tensor * inpL;
  6910. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6911. // inp_pos - contains the positions
  6912. struct ggml_tensor * inp_pos = build_inp_pos();
  6913. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6914. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6915. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6916. cb(pos, "pos_embd", -1);
  6917. inpL = ggml_add(ctx0, inpL, pos);
  6918. cb(inpL, "inpL", -1);
  6919. for (int il = 0; il < n_layer; ++il) {
  6920. cur = llm_build_norm(ctx0, inpL, hparams,
  6921. model.layers[il].attn_norm,
  6922. model.layers[il].attn_norm_b,
  6923. LLM_NORM, cb, il);
  6924. cb(cur, "attn_norm", il);
  6925. // self-attention
  6926. {
  6927. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6928. cb(cur, "wqkv", il);
  6929. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6930. cb(cur, "bqkv", il);
  6931. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6932. 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)));
  6933. 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)));
  6934. cb(Qcur, "Qcur", il);
  6935. cb(Kcur, "Kcur", il);
  6936. cb(Vcur, "Vcur", il);
  6937. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6938. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6939. model.layers[il].wo, model.layers[il].bo,
  6940. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6941. }
  6942. if (il == n_layer - 1) {
  6943. // skip computing output for unused tokens
  6944. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6945. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6946. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6947. }
  6948. // add the input
  6949. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6950. cb(ffn_inp, "ffn_inp", il);
  6951. // FF
  6952. {
  6953. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6954. model.layers[il].ffn_norm,
  6955. model.layers[il].ffn_norm_b,
  6956. LLM_NORM, cb, il);
  6957. cb(cur, "ffn_norm", il);
  6958. cur = llm_build_ffn(ctx0, cur,
  6959. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6960. NULL, NULL,
  6961. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6962. NULL,
  6963. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6964. cb(cur, "ffn_out", il);
  6965. }
  6966. inpL = ggml_add(ctx0, cur, ffn_inp);
  6967. cb(inpL, "l_out", il);
  6968. }
  6969. cur = llm_build_norm(ctx0, inpL, hparams,
  6970. model.output_norm,
  6971. model.output_norm_b,
  6972. LLM_NORM, cb, -1);
  6973. cb(cur, "result_norm", -1);
  6974. cur = ggml_mul_mat(ctx0, model.output, cur);
  6975. cb(cur, "result_output", -1);
  6976. ggml_build_forward_expand(gf, cur);
  6977. return gf;
  6978. }
  6979. struct ggml_cgraph * build_refact() {
  6980. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6981. const int64_t n_embd_head = hparams.n_embd_head_v;
  6982. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6983. struct ggml_tensor * cur;
  6984. struct ggml_tensor * inpL;
  6985. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6986. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6987. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6988. for (int il = 0; il < n_layer; ++il) {
  6989. struct ggml_tensor * inpSA = inpL;
  6990. cur = llm_build_norm(ctx0, inpL, hparams,
  6991. model.layers[il].attn_norm, NULL,
  6992. LLM_NORM_RMS, cb, il);
  6993. cb(cur, "attn_norm", il);
  6994. // self-attention
  6995. {
  6996. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6997. cb(Qcur, "Qcur", il);
  6998. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6999. cb(Kcur, "Kcur", il);
  7000. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7001. cb(Vcur, "Vcur", il);
  7002. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7003. cb(Kcur, "Kcur", il);
  7004. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7005. cb(Qcur, "Qcur", il);
  7006. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7007. model.layers[il].wo, NULL,
  7008. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7009. }
  7010. if (il == n_layer - 1) {
  7011. // skip computing output for unused tokens
  7012. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7013. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7014. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7015. }
  7016. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7017. cb(ffn_inp, "ffn_inp", il);
  7018. // feed-forward network
  7019. {
  7020. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7021. model.layers[il].ffn_norm, NULL,
  7022. LLM_NORM_RMS, cb, il);
  7023. cb(cur, "ffn_norm", il);
  7024. cur = llm_build_ffn(ctx0, cur,
  7025. model.layers[il].ffn_up, NULL,
  7026. model.layers[il].ffn_gate, NULL,
  7027. model.layers[il].ffn_down, NULL,
  7028. NULL,
  7029. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7030. cb(cur, "ffn_out", il);
  7031. }
  7032. cur = ggml_add(ctx0, cur, ffn_inp);
  7033. cb(cur, "l_out", il);
  7034. // input for next layer
  7035. inpL = cur;
  7036. }
  7037. cur = inpL;
  7038. cur = llm_build_norm(ctx0, cur, hparams,
  7039. model.output_norm, NULL,
  7040. LLM_NORM_RMS, cb, -1);
  7041. cb(cur, "result_norm", -1);
  7042. // lm_head
  7043. cur = ggml_mul_mat(ctx0, model.output, cur);
  7044. cb(cur, "result_output", -1);
  7045. ggml_build_forward_expand(gf, cur);
  7046. return gf;
  7047. }
  7048. struct ggml_cgraph * build_bert() {
  7049. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7050. const int64_t n_embd_head = hparams.n_embd_head_v;
  7051. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7052. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7053. struct ggml_tensor * cur;
  7054. struct ggml_tensor * inpL;
  7055. struct ggml_tensor * inp_pos = nullptr;
  7056. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  7057. inp_pos = build_inp_pos();
  7058. }
  7059. struct ggml_tensor * inp_mean = build_inp_mean();
  7060. struct ggml_tensor * inp_cls = build_inp_cls();
  7061. // construct input embeddings (token, type, position)
  7062. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7063. // token types are hardcoded to zero ("Sentence A")
  7064. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  7065. inpL = ggml_add(ctx0, inpL, type_row0);
  7066. if (model.arch == LLM_ARCH_BERT) {
  7067. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  7068. }
  7069. cb(inpL, "inp_embd", -1);
  7070. // embed layer norm
  7071. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  7072. cb(inpL, "inp_norm", -1);
  7073. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7074. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  7075. // iterate layers
  7076. for (int il = 0; il < n_layer; ++il) {
  7077. struct ggml_tensor * cur = inpL;
  7078. struct ggml_tensor * Qcur;
  7079. struct ggml_tensor * Kcur;
  7080. struct ggml_tensor * Vcur;
  7081. // self-attention
  7082. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  7083. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  7084. cb(Qcur, "Qcur", il);
  7085. if (model.layers[il].attn_q_norm) {
  7086. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7087. model.layers[il].attn_q_norm,
  7088. model.layers[il].attn_q_norm_b,
  7089. LLM_NORM, cb, il);
  7090. }
  7091. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  7092. cb(Kcur, "Kcur", il);
  7093. if (model.layers[il].attn_k_norm) {
  7094. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7095. model.layers[il].attn_k_norm,
  7096. model.layers[il].attn_k_norm_b,
  7097. LLM_NORM, cb, il);
  7098. }
  7099. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  7100. cb(Vcur, "Vcur", il);
  7101. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7102. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7103. } else {
  7104. // compute Q and K and RoPE them
  7105. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7106. cb(cur, "wqkv", il);
  7107. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7108. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7109. 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)));
  7110. cb(Qcur, "Qcur", il);
  7111. cb(Kcur, "Kcur", il);
  7112. cb(Vcur, "Vcur", il);
  7113. Qcur = ggml_rope_ext(
  7114. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7115. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7116. ext_factor, attn_factor, beta_fast, beta_slow
  7117. );
  7118. cb(Qcur, "Qcur", il);
  7119. Kcur = ggml_rope_ext(
  7120. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7121. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7122. ext_factor, attn_factor, beta_fast, beta_slow
  7123. );
  7124. cb(Kcur, "Kcur", il);
  7125. }
  7126. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  7127. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  7128. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  7129. cb(kq, "kq", il);
  7130. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  7131. cb(kq, "kq_soft_max_ext", il);
  7132. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  7133. cb(v, "v", il);
  7134. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  7135. cb(kqv, "kqv", il);
  7136. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  7137. cb(kqv_merged, "kqv_merged", il);
  7138. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  7139. cb(cur, "kqv_merged_cont", il);
  7140. ggml_build_forward_expand(gf, cur);
  7141. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  7142. if (model.layers[il].bo) {
  7143. cb(cur, "kqv_wo", il);
  7144. }
  7145. if (model.layers[il].bo) {
  7146. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  7147. }
  7148. cb(cur, "kqv_out", il);
  7149. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  7150. // skip computing output for unused tokens
  7151. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7152. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7153. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7154. }
  7155. // re-add the layer input
  7156. cur = ggml_add(ctx0, cur, inpL);
  7157. // attention layer norm
  7158. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  7159. struct ggml_tensor * ffn_inp = cur;
  7160. cb(ffn_inp, "ffn_inp", il);
  7161. // feed-forward network
  7162. if (model.arch == LLM_ARCH_BERT) {
  7163. cur = llm_build_ffn(ctx0, cur,
  7164. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7165. NULL, NULL,
  7166. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7167. NULL,
  7168. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7169. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  7170. cur = llm_build_ffn(ctx0, cur,
  7171. model.layers[il].ffn_up, NULL,
  7172. model.layers[il].ffn_gate, NULL,
  7173. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7174. NULL,
  7175. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7176. } else {
  7177. cur = llm_build_ffn(ctx0, cur,
  7178. model.layers[il].ffn_up, NULL,
  7179. model.layers[il].ffn_gate, NULL,
  7180. model.layers[il].ffn_down, NULL,
  7181. NULL,
  7182. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7183. }
  7184. cb(cur, "ffn_out", il);
  7185. // attentions bypass the intermediate layer
  7186. cur = ggml_add(ctx0, cur, ffn_inp);
  7187. // output layer norm
  7188. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  7189. // input for next layer
  7190. inpL = cur;
  7191. }
  7192. // final output
  7193. cur = inpL;
  7194. cb(cur, "result_embd", -1);
  7195. // pooling layer
  7196. switch (pooling_type) {
  7197. case LLAMA_POOLING_TYPE_NONE:
  7198. {
  7199. // nop
  7200. } break;
  7201. case LLAMA_POOLING_TYPE_MEAN:
  7202. {
  7203. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  7204. cb(cur, "result_embd_pooled", -1);
  7205. } break;
  7206. case LLAMA_POOLING_TYPE_CLS:
  7207. {
  7208. cur = ggml_get_rows(ctx0, cur, inp_cls);
  7209. cb(cur, "result_embd_pooled", -1);
  7210. } break;
  7211. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7212. {
  7213. GGML_ASSERT(false && "Invalid pooling type");
  7214. } break;
  7215. }
  7216. ggml_build_forward_expand(gf, cur);
  7217. return gf;
  7218. }
  7219. struct ggml_cgraph * build_bloom() {
  7220. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7221. const int64_t n_embd_head = hparams.n_embd_head_v;
  7222. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7223. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7224. struct ggml_tensor * cur;
  7225. struct ggml_tensor * inpL;
  7226. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7227. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7228. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7229. inpL = llm_build_norm(ctx0, inpL, hparams,
  7230. model.tok_norm,
  7231. model.tok_norm_b,
  7232. LLM_NORM, cb, -1);
  7233. cb(inpL, "inp_norm", -1);
  7234. for (int il = 0; il < n_layer; ++il) {
  7235. cur = llm_build_norm(ctx0, inpL, hparams,
  7236. model.layers[il].attn_norm,
  7237. model.layers[il].attn_norm_b,
  7238. LLM_NORM, cb, il);
  7239. cb(cur, "attn_norm", il);
  7240. // self-attention
  7241. {
  7242. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7243. cb(cur, "wqkv", il);
  7244. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7245. cb(cur, "bqkv", il);
  7246. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7247. 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)));
  7248. 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)));
  7249. cb(Qcur, "Qcur", il);
  7250. cb(Kcur, "Kcur", il);
  7251. cb(Vcur, "Vcur", il);
  7252. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7253. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7254. model.layers[il].wo, model.layers[il].bo,
  7255. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7256. }
  7257. if (il == n_layer - 1) {
  7258. // skip computing output for unused tokens
  7259. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7260. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7261. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7262. }
  7263. // Add the input
  7264. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7265. cb(ffn_inp, "ffn_inp", il);
  7266. // FF
  7267. {
  7268. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7269. model.layers[il].ffn_norm,
  7270. model.layers[il].ffn_norm_b,
  7271. LLM_NORM, cb, il);
  7272. cb(cur, "ffn_norm", il);
  7273. cur = llm_build_ffn(ctx0, cur,
  7274. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7275. NULL, NULL,
  7276. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7277. NULL,
  7278. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7279. cb(cur, "ffn_out", il);
  7280. }
  7281. inpL = ggml_add(ctx0, cur, ffn_inp);
  7282. cb(inpL, "l_out", il);
  7283. }
  7284. cur = llm_build_norm(ctx0, inpL, hparams,
  7285. model.output_norm,
  7286. model.output_norm_b,
  7287. LLM_NORM, cb, -1);
  7288. cb(cur, "result_norm", -1);
  7289. cur = ggml_mul_mat(ctx0, model.output, cur);
  7290. cb(cur, "result_output", -1);
  7291. ggml_build_forward_expand(gf, cur);
  7292. return gf;
  7293. }
  7294. struct ggml_cgraph * build_mpt() {
  7295. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7296. const int64_t n_embd_head = hparams.n_embd_head_v;
  7297. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7298. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7299. struct ggml_tensor * cur;
  7300. struct ggml_tensor * pos;
  7301. struct ggml_tensor * inpL;
  7302. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7303. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7304. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7305. if (model.pos_embd) {
  7306. // inp_pos - contains the positions
  7307. struct ggml_tensor * inp_pos = build_inp_pos();
  7308. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7309. cb(pos, "pos_embd", -1);
  7310. inpL = ggml_add(ctx0, inpL, pos);
  7311. cb(inpL, "inpL", -1);
  7312. }
  7313. for (int il = 0; il < n_layer; ++il) {
  7314. struct ggml_tensor * attn_norm;
  7315. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  7316. model.layers[il].attn_norm,
  7317. model.layers[il].attn_norm_b,
  7318. LLM_NORM, cb, il);
  7319. cb(attn_norm, "attn_norm", il);
  7320. // self-attention
  7321. {
  7322. cur = attn_norm;
  7323. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7324. cb(cur, "wqkv", il);
  7325. if (model.layers[il].bqkv){
  7326. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7327. cb(cur, "bqkv", il);
  7328. }
  7329. if (hparams.f_clamp_kqv > 0.0f) {
  7330. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  7331. cb(cur, "wqkv_clamped", il);
  7332. }
  7333. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7334. 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)));
  7335. 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)));
  7336. cb(Qcur, "Qcur", il);
  7337. cb(Kcur, "Kcur", il);
  7338. cb(Vcur, "Vcur", il);
  7339. // Q/K Layernorm
  7340. if (model.layers[il].attn_q_norm) {
  7341. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7342. model.layers[il].attn_q_norm,
  7343. model.layers[il].attn_q_norm_b,
  7344. LLM_NORM, cb, il);
  7345. cb(Qcur, "Qcur", il);
  7346. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7347. model.layers[il].attn_k_norm,
  7348. model.layers[il].attn_k_norm_b,
  7349. LLM_NORM, cb, il);
  7350. cb(Kcur, "Kcur", il);
  7351. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7352. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7353. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7354. model.layers[il].wo, model.layers[il].bo,
  7355. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7356. } else {
  7357. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7358. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7359. model.layers[il].wo, model.layers[il].bo,
  7360. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7361. }
  7362. }
  7363. if (il == n_layer - 1) {
  7364. // skip computing output for unused tokens
  7365. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7366. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7367. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7368. }
  7369. // Add the input
  7370. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7371. cb(ffn_inp, "ffn_inp", il);
  7372. // feed forward
  7373. {
  7374. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7375. model.layers[il].ffn_norm,
  7376. model.layers[il].ffn_norm_b,
  7377. LLM_NORM, cb, il);
  7378. cb(cur, "ffn_norm", il);
  7379. cur = llm_build_ffn(ctx0, cur,
  7380. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7381. NULL, NULL,
  7382. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7383. model.layers[il].ffn_act,
  7384. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7385. cb(cur, "ffn_out", il);
  7386. }
  7387. cur = ggml_add(ctx0, cur, ffn_inp);
  7388. cb(cur, "l_out", il);
  7389. // input for next layer
  7390. inpL = cur;
  7391. }
  7392. cur = inpL;
  7393. cur = llm_build_norm(ctx0, cur, hparams,
  7394. model.output_norm,
  7395. model.output_norm_b,
  7396. LLM_NORM, cb, -1);
  7397. cb(cur, "result_norm", -1);
  7398. cur = ggml_mul_mat(ctx0, model.output, cur);
  7399. cb(cur, "result_output", -1);
  7400. ggml_build_forward_expand(gf, cur);
  7401. return gf;
  7402. }
  7403. struct ggml_cgraph * build_stablelm() {
  7404. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  7405. const int64_t n_embd_head = hparams.n_embd_head_v;
  7406. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7407. struct ggml_tensor * cur;
  7408. struct ggml_tensor * inpL;
  7409. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7410. // inp_pos - contains the positions
  7411. struct ggml_tensor * inp_pos = build_inp_pos();
  7412. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7413. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7414. for (int il = 0; il < n_layer; ++il) {
  7415. // norm
  7416. cur = llm_build_norm(ctx0, inpL, hparams,
  7417. model.layers[il].attn_norm,
  7418. model.layers[il].attn_norm_b,
  7419. LLM_NORM, cb, il);
  7420. cb(cur, "attn_norm", il);
  7421. struct ggml_tensor * inpSA = cur;
  7422. // self-attention
  7423. {
  7424. // compute Q and K and RoPE them
  7425. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7426. cb(Qcur, "Qcur", il);
  7427. if (model.layers[il].bq) {
  7428. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7429. cb(Qcur, "Qcur", il);
  7430. }
  7431. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7432. cb(Kcur, "Kcur", il);
  7433. if (model.layers[il].bk) {
  7434. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7435. cb(Kcur, "Kcur", il);
  7436. }
  7437. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7438. cb(Vcur, "Vcur", il);
  7439. if (model.layers[il].bv) {
  7440. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7441. cb(Vcur, "Vcur", il);
  7442. }
  7443. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7444. cb(Qcur, "Qcur", il);
  7445. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7446. cb(Kcur, "Kcur", il);
  7447. if (model.layers[il].attn_q_norm) {
  7448. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7449. model.layers[il].attn_q_norm,
  7450. NULL,
  7451. LLM_NORM, cb, il);
  7452. cb(Qcur, "Qcur", il);
  7453. }
  7454. if (model.layers[il].attn_k_norm) {
  7455. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7456. model.layers[il].attn_k_norm,
  7457. NULL,
  7458. LLM_NORM, cb, il);
  7459. cb(Kcur, "Kcur", il);
  7460. }
  7461. Qcur = ggml_rope_ext(
  7462. ctx0, Qcur, inp_pos, nullptr,
  7463. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7464. ext_factor, attn_factor, beta_fast, beta_slow
  7465. );
  7466. cb(Qcur, "Qcur", il);
  7467. Kcur = ggml_rope_ext(
  7468. ctx0, Kcur, inp_pos, nullptr,
  7469. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7470. ext_factor, attn_factor, beta_fast, beta_slow
  7471. );
  7472. cb(Kcur, "Kcur", il);
  7473. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7474. model.layers[il].wo, NULL,
  7475. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7476. }
  7477. if (il == n_layer - 1) {
  7478. // skip computing output for unused tokens
  7479. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7480. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7481. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7482. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7483. }
  7484. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7485. cb(ffn_inp, "ffn_inp", il);
  7486. // feed-forward network
  7487. {
  7488. if (model.layers[il].ffn_norm) {
  7489. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7490. model.layers[il].ffn_norm,
  7491. model.layers[il].ffn_norm_b,
  7492. LLM_NORM, cb, il);
  7493. cb(cur, "ffn_norm", il);
  7494. } else {
  7495. // parallel residual
  7496. cur = inpSA;
  7497. }
  7498. cur = llm_build_ffn(ctx0, cur,
  7499. model.layers[il].ffn_up, NULL,
  7500. model.layers[il].ffn_gate, NULL,
  7501. model.layers[il].ffn_down, NULL,
  7502. NULL,
  7503. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7504. cb(cur, "ffn_out", il);
  7505. }
  7506. cur = ggml_add(ctx0, cur, ffn_inp);
  7507. cb(cur, "l_out", il);
  7508. // input for next layer
  7509. inpL = cur;
  7510. }
  7511. cur = inpL;
  7512. cur = llm_build_norm(ctx0, cur, hparams,
  7513. model.output_norm,
  7514. model.output_norm_b,
  7515. LLM_NORM, cb, -1);
  7516. cb(cur, "result_norm", -1);
  7517. // lm_head
  7518. cur = ggml_mul_mat(ctx0, model.output, cur);
  7519. cb(cur, "result_output", -1);
  7520. ggml_build_forward_expand(gf, cur);
  7521. return gf;
  7522. }
  7523. struct ggml_cgraph * build_qwen() {
  7524. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7525. const int64_t n_embd_head = hparams.n_embd_head_v;
  7526. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7527. struct ggml_tensor * cur;
  7528. struct ggml_tensor * inpL;
  7529. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7530. // inp_pos - contains the positions
  7531. struct ggml_tensor * inp_pos = build_inp_pos();
  7532. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7533. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7534. for (int il = 0; il < n_layer; ++il) {
  7535. struct ggml_tensor * inpSA = inpL;
  7536. cur = llm_build_norm(ctx0, inpL, hparams,
  7537. model.layers[il].attn_norm, NULL,
  7538. LLM_NORM_RMS, cb, il);
  7539. cb(cur, "attn_norm", il);
  7540. // self-attention
  7541. {
  7542. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7543. cb(cur, "wqkv", il);
  7544. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7545. cb(cur, "bqkv", il);
  7546. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7547. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7548. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  7549. cb(Qcur, "Qcur", il);
  7550. cb(Kcur, "Kcur", il);
  7551. cb(Vcur, "Vcur", il);
  7552. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7553. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7554. // using mode = 2 for neox mode
  7555. Qcur = ggml_rope_ext(
  7556. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  7557. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7558. );
  7559. cb(Qcur, "Qcur", il);
  7560. Kcur = ggml_rope_ext(
  7561. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  7562. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7563. );
  7564. cb(Kcur, "Kcur", il);
  7565. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7566. model.layers[il].wo, NULL,
  7567. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7568. }
  7569. if (il == n_layer - 1) {
  7570. // skip computing output for unused tokens
  7571. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7572. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7573. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7574. }
  7575. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7576. cb(ffn_inp, "ffn_inp", il);
  7577. // feed-forward forward
  7578. {
  7579. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7580. model.layers[il].ffn_norm, NULL,
  7581. LLM_NORM_RMS, cb, il);
  7582. cb(cur, "ffn_norm", il);
  7583. cur = llm_build_ffn(ctx0, cur,
  7584. model.layers[il].ffn_up, NULL,
  7585. model.layers[il].ffn_gate, NULL,
  7586. model.layers[il].ffn_down, NULL,
  7587. NULL,
  7588. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7589. cb(cur, "ffn_out", il);
  7590. }
  7591. cur = ggml_add(ctx0, cur, ffn_inp);
  7592. cb(cur, "l_out", il);
  7593. // input for next layer
  7594. inpL = cur;
  7595. }
  7596. cur = inpL;
  7597. cur = llm_build_norm(ctx0, cur, hparams,
  7598. model.output_norm, NULL,
  7599. LLM_NORM_RMS, cb, -1);
  7600. cb(cur, "result_norm", -1);
  7601. // lm_head
  7602. cur = ggml_mul_mat(ctx0, model.output, cur);
  7603. cb(cur, "result_output", -1);
  7604. ggml_build_forward_expand(gf, cur);
  7605. return gf;
  7606. }
  7607. struct ggml_cgraph * build_qwen2() {
  7608. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7609. const int64_t n_embd_head = hparams.n_embd_head_v;
  7610. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7611. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7612. struct ggml_tensor * cur;
  7613. struct ggml_tensor * inpL;
  7614. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7615. // inp_pos - contains the positions
  7616. struct ggml_tensor * inp_pos = build_inp_pos();
  7617. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7618. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7619. for (int il = 0; il < n_layer; ++il) {
  7620. struct ggml_tensor * inpSA = inpL;
  7621. // norm
  7622. cur = llm_build_norm(ctx0, inpL, hparams,
  7623. model.layers[il].attn_norm, NULL,
  7624. LLM_NORM_RMS, cb, il);
  7625. cb(cur, "attn_norm", il);
  7626. // self-attention
  7627. {
  7628. // compute Q and K and RoPE them
  7629. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7630. cb(Qcur, "Qcur", il);
  7631. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7632. cb(Qcur, "Qcur", il);
  7633. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7634. cb(Kcur, "Kcur", il);
  7635. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7636. cb(Kcur, "Kcur", il);
  7637. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7638. cb(Vcur, "Vcur", il);
  7639. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7640. cb(Vcur, "Vcur", il);
  7641. Qcur = ggml_rope_ext(
  7642. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7643. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7644. ext_factor, attn_factor, beta_fast, beta_slow
  7645. );
  7646. cb(Qcur, "Qcur", il);
  7647. Kcur = ggml_rope_ext(
  7648. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7649. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7650. ext_factor, attn_factor, beta_fast, beta_slow
  7651. );
  7652. cb(Kcur, "Kcur", il);
  7653. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7654. model.layers[il].wo, model.layers[il].bo,
  7655. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7656. }
  7657. if (il == n_layer - 1) {
  7658. // skip computing output for unused tokens
  7659. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7660. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7661. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7662. }
  7663. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7664. cb(ffn_inp, "ffn_inp", il);
  7665. // feed-forward network
  7666. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7667. model.layers[il].ffn_norm, NULL,
  7668. LLM_NORM_RMS, cb, il);
  7669. cb(cur, "ffn_norm", il);
  7670. cur = llm_build_ffn(ctx0, cur,
  7671. model.layers[il].ffn_up, NULL,
  7672. model.layers[il].ffn_gate, NULL,
  7673. model.layers[il].ffn_down, NULL,
  7674. NULL,
  7675. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7676. cb(cur, "ffn_out", il);
  7677. cur = ggml_add(ctx0, cur, ffn_inp);
  7678. cb(cur, "l_out", il);
  7679. // input for next layer
  7680. inpL = cur;
  7681. }
  7682. cur = inpL;
  7683. cur = llm_build_norm(ctx0, cur, hparams,
  7684. model.output_norm, NULL,
  7685. LLM_NORM_RMS, cb, -1);
  7686. cb(cur, "result_norm", -1);
  7687. // lm_head
  7688. cur = ggml_mul_mat(ctx0, model.output, cur);
  7689. cb(cur, "result_output", -1);
  7690. ggml_build_forward_expand(gf, cur);
  7691. return gf;
  7692. }
  7693. struct ggml_cgraph * build_qwen2moe() {
  7694. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7695. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7696. int32_t n_tokens = this->n_tokens;
  7697. const int64_t n_embd_head = hparams.n_embd_head_v;
  7698. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7699. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7700. struct ggml_tensor * cur;
  7701. struct ggml_tensor * inpL;
  7702. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7703. // inp_pos - contains the positions
  7704. struct ggml_tensor * inp_pos = build_inp_pos();
  7705. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7706. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7707. for (int il = 0; il < n_layer; ++il) {
  7708. struct ggml_tensor * inpSA = inpL;
  7709. // norm
  7710. cur = llm_build_norm(ctx0, inpL, hparams,
  7711. model.layers[il].attn_norm, NULL,
  7712. LLM_NORM_RMS, cb, il);
  7713. cb(cur, "attn_norm", il);
  7714. // self_attention
  7715. {
  7716. // compute Q and K and RoPE them
  7717. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7718. cb(Qcur, "Qcur", il);
  7719. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7720. cb(Qcur, "Qcur", il);
  7721. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7722. cb(Kcur, "Kcur", il);
  7723. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7724. cb(Kcur, "Kcur", il);
  7725. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7726. cb(Vcur, "Vcur", il);
  7727. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7728. cb(Vcur, "Vcur", il);
  7729. Qcur = ggml_rope_ext(
  7730. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  7731. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7732. ext_factor, attn_factor, beta_fast, beta_slow
  7733. );
  7734. cb(Qcur, "Qcur", il);
  7735. Kcur = ggml_rope_ext(
  7736. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  7737. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7738. ext_factor, attn_factor, beta_fast, beta_slow
  7739. );
  7740. cb(Kcur, "Kcur", il);
  7741. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7742. model.layers[il].wo, model.layers[il].bo,
  7743. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7744. }
  7745. if (il == n_layer - 1) {
  7746. // skip computing output for unused tokens
  7747. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7748. n_tokens = n_outputs;
  7749. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7750. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7751. }
  7752. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7753. cb(ffn_inp, "ffn_inp", il);
  7754. // MoE branch
  7755. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7756. model.layers[il].ffn_norm, NULL,
  7757. LLM_NORM_RMS, cb, il);
  7758. cb(cur, "ffn_norm", il);
  7759. ggml_tensor * moe_out =
  7760. llm_build_moe_ffn(ctx0, cur,
  7761. model.layers[il].ffn_gate_inp,
  7762. model.layers[il].ffn_up_exps,
  7763. model.layers[il].ffn_gate_exps,
  7764. model.layers[il].ffn_down_exps,
  7765. n_expert, n_expert_used,
  7766. LLM_FFN_SILU, false,
  7767. false, 0.0,
  7768. cb, il);
  7769. cb(cur, "ffn_moe_out", il);
  7770. // FFN shared expert
  7771. {
  7772. ggml_tensor * cur_gate_inp = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  7773. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  7774. // sigmoid
  7775. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  7776. cb(cur_gate, "ffn_shexp_gate", il);
  7777. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, cur,
  7778. model.layers[il].ffn_up_shexp, NULL,
  7779. model.layers[il].ffn_gate_shexp, NULL,
  7780. model.layers[il].ffn_down_shexp, NULL,
  7781. NULL,
  7782. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7783. cb(cur_ffn, "ffn_shexp", il);
  7784. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  7785. cb(ffn_shexp_out, "ffn_shexp_out", il);
  7786. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  7787. cb(moe_out, "ffn_out", il);
  7788. cur = moe_out;
  7789. }
  7790. cur = ggml_add(ctx0, cur, ffn_inp);
  7791. cb(cur, "l_out", il);
  7792. // input for next layer
  7793. inpL = cur;
  7794. }
  7795. cur = inpL;
  7796. cur = llm_build_norm(ctx0, cur, hparams,
  7797. model.output_norm, NULL,
  7798. LLM_NORM_RMS, cb, -1);
  7799. cb(cur, "result_norm", -1);
  7800. // lm_head
  7801. cur = ggml_mul_mat(ctx0, model.output, cur);
  7802. cb(cur, "result_output", -1);
  7803. ggml_build_forward_expand(gf, cur);
  7804. return gf;
  7805. }
  7806. struct ggml_cgraph * build_phi2() {
  7807. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7808. const int64_t n_embd_head = hparams.n_embd_head_v;
  7809. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7810. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7811. struct ggml_tensor * cur;
  7812. struct ggml_tensor * attn_norm_output;
  7813. struct ggml_tensor * ffn_output;
  7814. struct ggml_tensor * inpL;
  7815. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7816. // inp_pos - contains the positions
  7817. struct ggml_tensor * inp_pos = build_inp_pos();
  7818. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7819. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7820. for (int il = 0; il < n_layer; ++il) {
  7821. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  7822. model.layers[il].attn_norm,
  7823. model.layers[il].attn_norm_b,
  7824. LLM_NORM, cb, il);
  7825. cb(attn_norm_output, "attn_norm", il);
  7826. // self-attention
  7827. {
  7828. struct ggml_tensor * Qcur = nullptr;
  7829. struct ggml_tensor * Kcur = nullptr;
  7830. struct ggml_tensor * Vcur = nullptr;
  7831. if (model.layers[il].wqkv) {
  7832. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  7833. cb(cur, "wqkv", il);
  7834. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7835. cb(cur, "bqkv", il);
  7836. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7837. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7838. 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)));
  7839. } else {
  7840. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  7841. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  7842. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  7843. }
  7844. cb(Qcur, "Qcur", il);
  7845. cb(Kcur, "Kcur", il);
  7846. cb(Vcur, "Vcur", il);
  7847. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7848. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7849. Qcur = ggml_rope_ext(
  7850. ctx0, Qcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  7851. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7852. );
  7853. cb(Qcur, "Qcur", il);
  7854. // with phi2, we scale the Q to avoid precision issues
  7855. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  7856. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  7857. cb(Qcur, "Qcur", il);
  7858. Kcur = ggml_rope_ext(
  7859. ctx0, Kcur, inp_pos, nullptr, n_rot, rope_type, 0, n_orig_ctx,
  7860. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7861. );
  7862. cb(Kcur, "Kcur", il);
  7863. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7864. model.layers[il].wo, model.layers[il].bo,
  7865. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7866. }
  7867. if (il == n_layer - 1) {
  7868. // skip computing output for unused tokens
  7869. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7870. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7871. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7872. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  7873. }
  7874. // FF
  7875. {
  7876. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  7877. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7878. NULL, NULL,
  7879. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7880. NULL,
  7881. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7882. cb(ffn_output, "ffn_out", il);
  7883. }
  7884. cur = ggml_add(ctx0, cur, ffn_output);
  7885. cb(cur, "l_out", il);
  7886. cur = ggml_add(ctx0, cur, inpL);
  7887. cb(cur, "l_out", il);
  7888. inpL = cur;
  7889. }
  7890. cur = llm_build_norm(ctx0, inpL, hparams,
  7891. model.output_norm,
  7892. model.output_norm_b,
  7893. LLM_NORM, cb, -1);
  7894. cb(cur, "result_norm", -1);
  7895. cur = ggml_mul_mat(ctx0, model.output, cur);
  7896. cb(cur, "result_output_no_bias", -1);
  7897. cur = ggml_add(ctx0, cur, model.output_b);
  7898. cb(cur, "result_output", -1);
  7899. ggml_build_forward_expand(gf, cur);
  7900. return gf;
  7901. }
  7902. struct ggml_cgraph * build_phi3() {
  7903. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7904. const int64_t n_embd_head = hparams.n_embd_head_v;
  7905. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7906. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7907. struct ggml_tensor * cur;
  7908. struct ggml_tensor * inpL;
  7909. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7910. // inp_pos - contains the positions
  7911. struct ggml_tensor * inp_pos = build_inp_pos();
  7912. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7913. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7914. for (int il = 0; il < n_layer; ++il) {
  7915. auto residual = inpL;
  7916. // self-attention
  7917. {
  7918. // rope freq factors for 128k context
  7919. struct ggml_tensor * rope_factors = build_rope_factors(il);
  7920. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  7921. model.layers[il].attn_norm,
  7922. NULL,
  7923. LLM_NORM_RMS, cb, il);
  7924. cb(attn_norm_output, "attn_norm", il);
  7925. struct ggml_tensor * Qcur = nullptr;
  7926. struct ggml_tensor * Kcur = nullptr;
  7927. struct ggml_tensor * Vcur = nullptr;
  7928. if (model.layers[il].wqkv) {
  7929. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  7930. cb(cur, "wqkv", il);
  7931. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  7932. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  7933. 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)));
  7934. }
  7935. else {
  7936. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  7937. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  7938. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  7939. }
  7940. cb(Qcur, "Qcur", il);
  7941. cb(Kcur, "Kcur", il);
  7942. cb(Vcur, "Vcur", il);
  7943. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7944. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7945. Qcur = ggml_rope_ext(
  7946. ctx0, Qcur, inp_pos, rope_factors, n_rot, rope_type, 0, n_orig_ctx,
  7947. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7948. );
  7949. cb(Qcur, "Qcur", il);
  7950. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  7951. cb(Qcur, "Qcur", il);
  7952. Kcur = ggml_rope_ext(
  7953. ctx0, Kcur, inp_pos, rope_factors, n_rot, rope_type, 0, n_orig_ctx,
  7954. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7955. );
  7956. cb(Kcur, "Kcur", il);
  7957. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7958. model.layers[il].wo, model.layers[il].bo,
  7959. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7960. }
  7961. if (il == n_layer - 1) {
  7962. // skip computing output for unused tokens
  7963. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  7964. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7965. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  7966. }
  7967. cur = ggml_add(ctx0, cur, residual);
  7968. residual = cur;
  7969. cur = llm_build_norm(ctx0, cur, hparams,
  7970. model.layers[il].ffn_norm, NULL,
  7971. LLM_NORM_RMS, cb, il);
  7972. cb(cur, "ffn_norm", il);
  7973. // FF
  7974. // special-case: the up and gate tensors are merged into a single tensor
  7975. // TOOD: support into llm_build_ffn
  7976. {
  7977. struct ggml_tensor* up = ggml_mul_mat(ctx0, model.layers[il].ffn_up, cur);
  7978. cb(up, "ffn_up", il);
  7979. auto g = ggml_cont(ctx0, ggml_view_2d(ctx0, up, up->ne[0] / 2, up->ne[1], ggml_row_size(up->type, up->ne[0]), 0));
  7980. auto y = ggml_cont(ctx0, ggml_view_2d(ctx0, up, up->ne[0] / 2, up->ne[1], ggml_row_size(up->type, up->ne[0]), up->nb[1] / 2));
  7981. y = ggml_mul(ctx0, y, ggml_silu(ctx0, g));
  7982. cb(y, "ffn_gate", il);
  7983. auto down = ggml_mul_mat(ctx0, model.layers[il].ffn_down, y);
  7984. cb(down, "ffn_down", il);
  7985. cur = down;
  7986. cb(cur, "ffn_out", il);
  7987. }
  7988. cur = ggml_add(ctx0, residual, cur);
  7989. cb(cur, "l_out", il);
  7990. inpL = cur;
  7991. }
  7992. cur = llm_build_norm(ctx0, inpL, hparams,
  7993. model.output_norm,
  7994. NULL,
  7995. LLM_NORM_RMS, cb, -1);
  7996. cb(cur, "result_norm", -1);
  7997. cur = ggml_mul_mat(ctx0, model.output, cur);
  7998. cb(cur, "result_output", -1);
  7999. ggml_build_forward_expand(gf, cur);
  8000. return gf;
  8001. }
  8002. struct ggml_cgraph * build_plamo() {
  8003. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  8004. const int64_t n_embd_head = hparams.n_embd_head_v;
  8005. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8006. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8007. struct ggml_tensor * cur;
  8008. struct ggml_tensor * inpL;
  8009. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8010. // inp_pos - contains the positions
  8011. struct ggml_tensor * inp_pos = build_inp_pos();
  8012. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8013. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8014. for (int il = 0; il < n_layer; ++il) {
  8015. // norm
  8016. cur = llm_build_norm(ctx0, inpL, hparams,
  8017. model.layers[il].attn_norm, NULL,
  8018. LLM_NORM_RMS, cb, il);
  8019. cb(cur, "attn_norm", il);
  8020. struct ggml_tensor * attention_norm = cur;
  8021. // self-attention
  8022. {
  8023. // compute Q and K and RoPE them
  8024. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8025. cb(Qcur, "Qcur", il);
  8026. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8027. cb(Kcur, "Kcur", il);
  8028. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8029. cb(Vcur, "Vcur", il);
  8030. Qcur = ggml_rope_ext(
  8031. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos, nullptr,
  8032. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8033. ext_factor, attn_factor, beta_fast, beta_slow);
  8034. cb(Qcur, "Qcur", il);
  8035. Kcur = ggml_rope_ext(
  8036. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos, nullptr,
  8037. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8038. ext_factor, attn_factor, beta_fast, beta_slow);
  8039. cb(Kcur, "Kcur", il);
  8040. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8041. model.layers[il].wo, NULL,
  8042. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8043. }
  8044. struct ggml_tensor * sa_out = cur;
  8045. cur = attention_norm;
  8046. if (il == n_layer - 1) {
  8047. // skip computing output for unused tokens
  8048. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8049. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8050. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  8051. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8052. }
  8053. // feed-forward network
  8054. {
  8055. cur = llm_build_ffn(ctx0, cur,
  8056. model.layers[il].ffn_up, NULL,
  8057. model.layers[il].ffn_gate, NULL,
  8058. model.layers[il].ffn_down, NULL,
  8059. NULL,
  8060. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8061. cb(cur, "ffn_out", il);
  8062. }
  8063. cur = ggml_add(ctx0, cur, sa_out);
  8064. cb(cur, "l_out", il);
  8065. cur = ggml_add(ctx0, cur, inpL);
  8066. cb(cur, "l_out", il);
  8067. // input for next layer
  8068. inpL = cur;
  8069. }
  8070. cur = inpL;
  8071. cur = llm_build_norm(ctx0, cur, hparams,
  8072. model.output_norm, NULL,
  8073. LLM_NORM_RMS, cb, -1);
  8074. cb(cur, "result_norm", -1);
  8075. // lm_head
  8076. cur = ggml_mul_mat(ctx0, model.output, cur);
  8077. cb(cur, "result_output", -1);
  8078. ggml_build_forward_expand(gf, cur);
  8079. return gf;
  8080. }
  8081. struct ggml_cgraph * build_gpt2() {
  8082. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8083. const int64_t n_embd_head = hparams.n_embd_head_v;
  8084. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8085. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8086. struct ggml_tensor * cur;
  8087. struct ggml_tensor * pos;
  8088. struct ggml_tensor * inpL;
  8089. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8090. // inp_pos - contains the positions
  8091. struct ggml_tensor * inp_pos = build_inp_pos();
  8092. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8093. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8094. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  8095. cb(pos, "pos_embd", -1);
  8096. inpL = ggml_add(ctx0, inpL, pos);
  8097. cb(inpL, "inpL", -1);
  8098. for (int il = 0; il < n_layer; ++il) {
  8099. cur = llm_build_norm(ctx0, inpL, hparams,
  8100. model.layers[il].attn_norm,
  8101. model.layers[il].attn_norm_b,
  8102. LLM_NORM, cb, il);
  8103. cb(cur, "attn_norm", il);
  8104. // self-attention
  8105. {
  8106. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  8107. cb(cur, "wqkv", il);
  8108. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8109. cb(cur, "bqkv", il);
  8110. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8111. 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)));
  8112. 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)));
  8113. cb(Qcur, "Qcur", il);
  8114. cb(Kcur, "Kcur", il);
  8115. cb(Vcur, "Vcur", il);
  8116. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8117. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8118. model.layers[il].wo, model.layers[il].bo,
  8119. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8120. }
  8121. if (il == n_layer - 1) {
  8122. // skip computing output for unused tokens
  8123. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8124. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8125. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8126. }
  8127. // add the input
  8128. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8129. cb(ffn_inp, "ffn_inp", il);
  8130. // FF
  8131. {
  8132. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8133. model.layers[il].ffn_norm,
  8134. model.layers[il].ffn_norm_b,
  8135. LLM_NORM, cb, il);
  8136. cb(cur, "ffn_norm", il);
  8137. cur = llm_build_ffn(ctx0, cur,
  8138. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8139. NULL, NULL,
  8140. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8141. NULL,
  8142. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8143. cb(cur, "ffn_out", il);
  8144. }
  8145. inpL = ggml_add(ctx0, cur, ffn_inp);
  8146. cb(inpL, "l_out", il);
  8147. }
  8148. cur = llm_build_norm(ctx0, inpL, hparams,
  8149. model.output_norm,
  8150. model.output_norm_b,
  8151. LLM_NORM, cb, -1);
  8152. cb(cur, "result_norm", -1);
  8153. cur = ggml_mul_mat(ctx0, model.output, cur);
  8154. cb(cur, "result_output", -1);
  8155. ggml_build_forward_expand(gf, cur);
  8156. return gf;
  8157. }
  8158. struct ggml_cgraph * build_codeshell() {
  8159. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8160. const int64_t n_embd_head = hparams.n_embd_head_v;
  8161. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8162. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8163. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8164. struct ggml_tensor * cur;
  8165. struct ggml_tensor * inpL;
  8166. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8167. // inp_pos - contains the positions
  8168. struct ggml_tensor * inp_pos = build_inp_pos();
  8169. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8170. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8171. for (int il = 0; il < n_layer; ++il) {
  8172. cur = llm_build_norm(ctx0, inpL, hparams,
  8173. model.layers[il].attn_norm,
  8174. model.layers[il].attn_norm_b,
  8175. LLM_NORM, cb, il);
  8176. cb(cur, "attn_norm", il);
  8177. // self-attention
  8178. {
  8179. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  8180. cb(cur, "wqkv", il);
  8181. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8182. cb(cur, "bqkv", il);
  8183. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8184. 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)));
  8185. 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)));
  8186. cb(tmpq, "tmpq", il);
  8187. cb(tmpk, "tmpk", il);
  8188. cb(Vcur, "Vcur", il);
  8189. struct ggml_tensor * Qcur = ggml_rope_ext(
  8190. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8191. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8192. ext_factor, attn_factor, beta_fast, beta_slow
  8193. );
  8194. cb(Qcur, "Qcur", il);
  8195. struct ggml_tensor * Kcur = ggml_rope_ext(
  8196. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8197. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8198. ext_factor, attn_factor, beta_fast, beta_slow
  8199. );
  8200. cb(Kcur, "Kcur", il);
  8201. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8202. model.layers[il].wo, model.layers[il].bo,
  8203. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8204. }
  8205. if (il == n_layer - 1) {
  8206. // skip computing output for unused tokens
  8207. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8208. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8209. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8210. }
  8211. // add the input
  8212. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8213. cb(ffn_inp, "ffn_inp", il);
  8214. // FF
  8215. {
  8216. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8217. model.layers[il].ffn_norm,
  8218. model.layers[il].ffn_norm_b,
  8219. LLM_NORM, cb, il);
  8220. cb(cur, "ffn_norm", il);
  8221. cur = llm_build_ffn(ctx0, cur,
  8222. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8223. NULL, NULL,
  8224. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8225. NULL,
  8226. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8227. cb(cur, "ffn_out", il);
  8228. }
  8229. inpL = ggml_add(ctx0, cur, ffn_inp);
  8230. cb(inpL, "l_out", il);
  8231. }
  8232. cur = llm_build_norm(ctx0, inpL, hparams,
  8233. model.output_norm,
  8234. model.output_norm_b,
  8235. LLM_NORM, cb, -1);
  8236. cb(cur, "result_norm", -1);
  8237. cur = ggml_mul_mat(ctx0, model.output, cur);
  8238. cb(cur, "result_output", -1);
  8239. ggml_build_forward_expand(gf, cur);
  8240. return gf;
  8241. }
  8242. struct ggml_cgraph * build_orion() {
  8243. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8244. const int64_t n_embd_head = hparams.n_embd_head_v;
  8245. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8246. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8247. struct ggml_tensor * cur;
  8248. struct ggml_tensor * inpL;
  8249. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8250. // inp_pos - contains the positions
  8251. struct ggml_tensor * inp_pos = build_inp_pos();
  8252. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8253. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8254. for (int il = 0; il < n_layer; ++il) {
  8255. struct ggml_tensor * inpSA = inpL;
  8256. // norm
  8257. cur = llm_build_norm(ctx0, inpL, hparams,
  8258. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  8259. LLM_NORM, cb, il);
  8260. cb(cur, "attn_norm", il);
  8261. // self-attention
  8262. {
  8263. // compute Q and K and RoPE them
  8264. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8265. cb(Qcur, "Qcur", il);
  8266. // if (model.layers[il].bq) {
  8267. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8268. // cb(Qcur, "Qcur", il);
  8269. // }
  8270. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8271. cb(Kcur, "Kcur", il);
  8272. // if (model.layers[il].bk) {
  8273. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8274. // cb(Kcur, "Kcur", il);
  8275. // }
  8276. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8277. cb(Vcur, "Vcur", il);
  8278. // if (model.layers[il].bv) {
  8279. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8280. // cb(Vcur, "Vcur", il);
  8281. // }
  8282. Qcur = ggml_rope_ext(
  8283. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8284. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8285. ext_factor, attn_factor, beta_fast, beta_slow
  8286. );
  8287. cb(Qcur, "Qcur", il);
  8288. Kcur = ggml_rope_ext(
  8289. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8290. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8291. ext_factor, attn_factor, beta_fast, beta_slow
  8292. );
  8293. cb(Kcur, "Kcur", il);
  8294. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8295. model.layers[il].wo, NULL,
  8296. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8297. }
  8298. if (il == n_layer - 1) {
  8299. // skip computing output for unused tokens
  8300. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8301. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8302. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8303. }
  8304. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8305. cb(ffn_inp, "ffn_inp", il);
  8306. // feed-forward network
  8307. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8308. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  8309. LLM_NORM, cb, il);
  8310. cb(cur, "ffn_norm", il);
  8311. cur = llm_build_ffn(ctx0, cur,
  8312. model.layers[il].ffn_up, NULL,
  8313. model.layers[il].ffn_gate, NULL,
  8314. model.layers[il].ffn_down, NULL,
  8315. NULL,
  8316. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8317. cb(cur, "ffn_out", il);
  8318. cur = ggml_add(ctx0, cur, ffn_inp);
  8319. cb(cur, "l_out", il);
  8320. // input for next layer
  8321. inpL = cur;
  8322. }
  8323. cur = inpL;
  8324. cur = llm_build_norm(ctx0, cur, hparams,
  8325. model.output_norm, model.output_norm_b,
  8326. LLM_NORM, cb, -1);
  8327. cb(cur, "result_norm", -1);
  8328. // lm_head
  8329. cur = ggml_mul_mat(ctx0, model.output, cur);
  8330. cb(cur, "result_output", -1);
  8331. ggml_build_forward_expand(gf, cur);
  8332. return gf;
  8333. }
  8334. struct ggml_cgraph * build_internlm2() {
  8335. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8336. const int64_t n_embd_head = hparams.n_embd_head_v;
  8337. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8338. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8339. struct ggml_tensor * cur;
  8340. struct ggml_tensor * inpL;
  8341. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8342. // inp_pos - contains the positions
  8343. struct ggml_tensor * inp_pos = build_inp_pos();
  8344. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8345. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8346. for (int il = 0; il < n_layer; ++il) {
  8347. struct ggml_tensor * inpSA = inpL;
  8348. // norm
  8349. cur = llm_build_norm(ctx0, inpL, hparams,
  8350. model.layers[il].attn_norm, NULL,
  8351. LLM_NORM_RMS, cb, il);
  8352. cb(cur, "attn_norm", il);
  8353. // self-attention
  8354. {
  8355. // compute Q and K and RoPE them
  8356. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8357. cb(Qcur, "Qcur", il);
  8358. if (model.layers[il].bq) {
  8359. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8360. cb(Qcur, "Qcur", il);
  8361. }
  8362. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8363. cb(Kcur, "Kcur", il);
  8364. if (model.layers[il].bk) {
  8365. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8366. cb(Kcur, "Kcur", il);
  8367. }
  8368. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8369. cb(Vcur, "Vcur", il);
  8370. if (model.layers[il].bv) {
  8371. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8372. cb(Vcur, "Vcur", il);
  8373. }
  8374. Qcur = ggml_rope_ext(
  8375. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8376. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8377. ext_factor, attn_factor, beta_fast, beta_slow
  8378. );
  8379. cb(Qcur, "Qcur", il);
  8380. Kcur = ggml_rope_ext(
  8381. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8382. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8383. ext_factor, attn_factor, beta_fast, beta_slow
  8384. );
  8385. cb(Kcur, "Kcur", il);
  8386. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8387. model.layers[il].wo, model.layers[il].bo,
  8388. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8389. }
  8390. if (il == n_layer - 1) {
  8391. // skip computing output for unused tokens
  8392. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8393. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8394. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8395. }
  8396. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8397. cb(ffn_inp, "ffn_inp", il);
  8398. // feed-forward network
  8399. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8400. model.layers[il].ffn_norm, NULL,
  8401. LLM_NORM_RMS, cb, il);
  8402. cb(cur, "ffn_norm", il);
  8403. cur = llm_build_ffn(ctx0, cur,
  8404. model.layers[il].ffn_up, NULL,
  8405. model.layers[il].ffn_gate, NULL,
  8406. model.layers[il].ffn_down, NULL,
  8407. NULL,
  8408. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8409. cb(cur, "ffn_out", il);
  8410. cur = ggml_add(ctx0, cur, ffn_inp);
  8411. cb(cur, "l_out", il);
  8412. // input for next layer
  8413. inpL = cur;
  8414. }
  8415. cur = inpL;
  8416. cur = llm_build_norm(ctx0, cur, hparams,
  8417. model.output_norm, NULL,
  8418. LLM_NORM_RMS, cb, -1);
  8419. cb(cur, "result_norm", -1);
  8420. // lm_head
  8421. cur = ggml_mul_mat(ctx0, model.output, cur);
  8422. cb(cur, "result_output", -1);
  8423. ggml_build_forward_expand(gf, cur);
  8424. return gf;
  8425. }
  8426. // ref: https://arxiv.org/abs/2203.03466
  8427. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  8428. // based on the original build_llama() function
  8429. struct ggml_cgraph * build_minicpm() {
  8430. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8431. const int64_t n_embd_head = hparams.n_embd_head_v;
  8432. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8433. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8434. const int64_t n_embd = hparams.n_embd;
  8435. //TODO: if the model varies, these parameters need to be read from the model
  8436. const int64_t n_embd_base = 256;
  8437. const float scale_embd = 12.0f;
  8438. const float scale_depth = 1.4f;
  8439. struct ggml_tensor * cur;
  8440. struct ggml_tensor * inpL;
  8441. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8442. // scale the input embeddings
  8443. inpL = ggml_scale(ctx0, inpL, scale_embd);
  8444. cb(inpL, "inp_scaled", -1);
  8445. // inp_pos - contains the positions
  8446. struct ggml_tensor * inp_pos = build_inp_pos();
  8447. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8448. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8449. for (int il = 0; il < n_layer; ++il) {
  8450. struct ggml_tensor * inpSA = inpL;
  8451. // norm
  8452. cur = llm_build_norm(ctx0, inpL, hparams,
  8453. model.layers[il].attn_norm, NULL,
  8454. LLM_NORM_RMS, cb, il);
  8455. cb(cur, "attn_norm", il);
  8456. // self-attention
  8457. {
  8458. // compute Q and K and RoPE them
  8459. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8460. cb(Qcur, "Qcur", il);
  8461. if (model.layers[il].bq) {
  8462. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8463. cb(Qcur, "Qcur", il);
  8464. }
  8465. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8466. cb(Kcur, "Kcur", il);
  8467. if (model.layers[il].bk) {
  8468. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8469. cb(Kcur, "Kcur", il);
  8470. }
  8471. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8472. cb(Vcur, "Vcur", il);
  8473. if (model.layers[il].bv) {
  8474. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8475. cb(Vcur, "Vcur", il);
  8476. }
  8477. Qcur = ggml_rope_ext(
  8478. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8479. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8480. ext_factor, attn_factor, beta_fast, beta_slow
  8481. );
  8482. cb(Qcur, "Qcur", il);
  8483. Kcur = ggml_rope_ext(
  8484. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8485. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8486. ext_factor, attn_factor, beta_fast, beta_slow
  8487. );
  8488. cb(Kcur, "Kcur", il);
  8489. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8490. model.layers[il].wo, model.layers[il].bo,
  8491. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8492. }
  8493. if (il == n_layer - 1) {
  8494. // skip computing output for unused tokens
  8495. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8496. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8497. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8498. }
  8499. // scale_res - scale the hidden states for residual connection
  8500. const float scale_res = scale_depth/sqrtf(float(n_layer));
  8501. cur = ggml_scale(ctx0, cur, scale_res);
  8502. cb(cur, "hidden_scaled", -1);
  8503. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8504. cb(ffn_inp, "ffn_inp", il);
  8505. // feed-forward network
  8506. {
  8507. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8508. model.layers[il].ffn_norm, NULL,
  8509. LLM_NORM_RMS, cb, il);
  8510. cb(cur, "ffn_norm", il);
  8511. cur = llm_build_ffn(ctx0, cur,
  8512. model.layers[il].ffn_up, NULL,
  8513. model.layers[il].ffn_gate, NULL,
  8514. model.layers[il].ffn_down, NULL,
  8515. NULL,
  8516. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8517. cb(cur, "ffn_out", il);
  8518. }
  8519. // scale the hidden states for residual connection
  8520. cur = ggml_scale(ctx0, cur, scale_res);
  8521. cb(cur, "hidden_scaled_ffn", -1);
  8522. cur = ggml_add(ctx0, cur, ffn_inp);
  8523. cb(cur, "l_out", il);
  8524. // input for next layer
  8525. inpL = cur;
  8526. }
  8527. cur = inpL;
  8528. cur = llm_build_norm(ctx0, cur, hparams,
  8529. model.output_norm, NULL,
  8530. LLM_NORM_RMS, cb, -1);
  8531. cb(cur, "result_norm", -1);
  8532. // lm_head scaling
  8533. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  8534. cur = ggml_scale(ctx0, cur, scale_lmhead);
  8535. cb(cur, "lmhead_scaling", -1);
  8536. // lm_head
  8537. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  8538. cb(cur, "result_output", -1);
  8539. ggml_build_forward_expand(gf, cur);
  8540. return gf;
  8541. }
  8542. struct ggml_cgraph * build_gemma() {
  8543. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8544. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8545. struct ggml_tensor * cur;
  8546. struct ggml_tensor * inpL;
  8547. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8548. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  8549. cb(inpL, "inp_scaled", -1);
  8550. // inp_pos - contains the positions
  8551. struct ggml_tensor * inp_pos = build_inp_pos();
  8552. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8553. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8554. for (int il = 0; il < n_layer; ++il) {
  8555. // norm
  8556. cur = llm_build_norm(ctx0, inpL, hparams,
  8557. model.layers[il].attn_norm, NULL,
  8558. LLM_NORM_RMS, cb, il);
  8559. cb(cur, "attn_norm", il);
  8560. // self-attention
  8561. {
  8562. // compute Q and K and RoPE them
  8563. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8564. cb(Qcur, "Qcur", il);
  8565. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8566. cb(Kcur, "Kcur", il);
  8567. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8568. cb(Vcur, "Vcur", il);
  8569. Qcur = ggml_rope_ext(
  8570. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos, nullptr,
  8571. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8572. ext_factor, attn_factor, beta_fast, beta_slow);
  8573. cb(Qcur, "Qcur", il);
  8574. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  8575. cb(Qcur, "Qcur_scaled", il);
  8576. Kcur = ggml_rope_ext(
  8577. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos, nullptr,
  8578. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8579. ext_factor, attn_factor, beta_fast, beta_slow);
  8580. cb(Kcur, "Kcur", il);
  8581. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8582. model.layers[il].wo, NULL,
  8583. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  8584. }
  8585. if (il == n_layer - 1) {
  8586. // skip computing output for unused tokens
  8587. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8588. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8589. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8590. }
  8591. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  8592. cb(sa_out, "sa_out", il);
  8593. cur = llm_build_norm(ctx0, sa_out, hparams,
  8594. model.layers[il].ffn_norm, NULL,
  8595. LLM_NORM_RMS, cb, il);
  8596. cb(cur, "ffn_norm", il);
  8597. // feed-forward network
  8598. {
  8599. cur = llm_build_ffn(ctx0, cur,
  8600. model.layers[il].ffn_up, NULL,
  8601. model.layers[il].ffn_gate, NULL,
  8602. model.layers[il].ffn_down, NULL,
  8603. NULL,
  8604. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  8605. cb(cur, "ffn_out", il);
  8606. }
  8607. cur = ggml_add(ctx0, cur, sa_out);
  8608. cb(cur, "l_out", il);
  8609. // input for next layer
  8610. inpL = cur;
  8611. }
  8612. cur = inpL;
  8613. cur = llm_build_norm(ctx0, cur, hparams,
  8614. model.output_norm, NULL,
  8615. LLM_NORM_RMS, cb, -1);
  8616. cb(cur, "result_norm", -1);
  8617. // lm_head
  8618. cur = ggml_mul_mat(ctx0, model.output, cur);
  8619. cb(cur, "result_output", -1);
  8620. ggml_build_forward_expand(gf, cur);
  8621. return gf;
  8622. }
  8623. struct ggml_cgraph * build_starcoder2() {
  8624. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8625. const int64_t n_embd_head = hparams.n_embd_head_v;
  8626. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8627. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8628. struct ggml_tensor * cur;
  8629. struct ggml_tensor * inpL;
  8630. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8631. // inp_pos - contains the positions
  8632. struct ggml_tensor * inp_pos = build_inp_pos();
  8633. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8634. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8635. for (int il = 0; il < n_layer; ++il) {
  8636. struct ggml_tensor * inpSA = inpL;
  8637. // norm
  8638. cur = llm_build_norm(ctx0, inpL, hparams,
  8639. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  8640. LLM_NORM, cb, il);
  8641. cb(cur, "attn_norm", il);
  8642. // self-attention
  8643. {
  8644. // compute Q and K and RoPE them
  8645. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8646. cb(Qcur, "Qcur", il);
  8647. if (model.layers[il].bq) {
  8648. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8649. cb(Qcur, "Qcur", il);
  8650. }
  8651. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8652. cb(Kcur, "Kcur", il);
  8653. if (model.layers[il].bk) {
  8654. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8655. cb(Kcur, "Kcur", il);
  8656. }
  8657. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8658. cb(Vcur, "Vcur", il);
  8659. if (model.layers[il].bv) {
  8660. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8661. cb(Vcur, "Vcur", il);
  8662. }
  8663. Qcur = ggml_rope_ext(
  8664. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8665. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8666. ext_factor, attn_factor, beta_fast, beta_slow
  8667. );
  8668. cb(Qcur, "Qcur", il);
  8669. Kcur = ggml_rope_ext(
  8670. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8671. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8672. ext_factor, attn_factor, beta_fast, beta_slow
  8673. );
  8674. cb(Kcur, "Kcur", il);
  8675. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8676. model.layers[il].wo, model.layers[il].bo,
  8677. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8678. }
  8679. if (il == n_layer - 1) {
  8680. // skip computing output for unused tokens
  8681. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8682. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8683. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8684. }
  8685. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8686. cb(ffn_inp, "ffn_inp", il);
  8687. // feed-forward network
  8688. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8689. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  8690. LLM_NORM, cb, il);
  8691. cb(cur, "ffn_norm", il);
  8692. cur = llm_build_ffn(ctx0, cur,
  8693. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8694. NULL, NULL,
  8695. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8696. NULL,
  8697. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8698. cb(cur, "ffn_out", il);
  8699. cur = ggml_add(ctx0, cur, ffn_inp);
  8700. cb(cur, "l_out", il);
  8701. // input for next layer
  8702. inpL = cur;
  8703. }
  8704. cur = inpL;
  8705. cur = llm_build_norm(ctx0, cur, hparams,
  8706. model.output_norm, model.output_norm_b,
  8707. LLM_NORM, cb, -1);
  8708. cb(cur, "result_norm", -1);
  8709. // lm_head
  8710. cur = ggml_mul_mat(ctx0, model.output, cur);
  8711. cb(cur, "result_output", -1);
  8712. ggml_build_forward_expand(gf, cur);
  8713. return gf;
  8714. }
  8715. struct ggml_cgraph * build_mamba() {
  8716. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8717. const int64_t d_model = n_embd;
  8718. const int64_t d_conv = hparams.ssm_d_conv;
  8719. const int64_t d_inner = hparams.ssm_d_inner;
  8720. GGML_ASSERT(2 * d_model == d_inner);
  8721. const int64_t d_state = hparams.ssm_d_state;
  8722. const int64_t dt_rank = hparams.ssm_dt_rank;
  8723. struct ggml_tensor * cur;
  8724. struct ggml_tensor * inpL;
  8725. // {n_embd, n_tokens}
  8726. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8727. struct ggml_tensor * state_mask = build_inp_s_mask();
  8728. struct ggml_tensor * state_seq = build_inp_s_seq();
  8729. for (int il = 0; il < n_layer; ++il) {
  8730. // (ab)using the KV cache to store the states
  8731. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  8732. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  8733. // clear states of sequences which are starting at the beginning of this batch
  8734. {
  8735. conv_states = ggml_mul(ctx0,
  8736. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  8737. state_mask);
  8738. ssm_states = ggml_mul(ctx0,
  8739. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  8740. state_mask);
  8741. }
  8742. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  8743. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  8744. // norm
  8745. cur = llm_build_norm(ctx0, inpL, hparams,
  8746. model.layers[il].attn_norm, NULL,
  8747. LLM_NORM_RMS, cb, il);
  8748. cb(cur, "attn_norm", il);
  8749. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  8750. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  8751. // split the above in two
  8752. // => {d_inner, n_tokens}
  8753. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  8754. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  8755. // conv
  8756. {
  8757. // Custom operator which is needed only to ease simultaneous sequence processing.
  8758. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  8759. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  8760. // then element-wise multiply that with the conv1d weigth,
  8761. // then sum the elements of each row,
  8762. // (the last two steps are a dot product over rows (also doable with mul_mat))
  8763. // then permute away the ne[0] dimension,
  8764. // and then you're left with the resulting x tensor.
  8765. // The new conv_states is the last (d_conv - 1) columns
  8766. // of the last 3rd dimensional "layer" of the self-overlapping view.
  8767. // For simultaneous sequences, it's more complicated.
  8768. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  8769. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  8770. ggml_build_forward_expand(gf,
  8771. ggml_cpy(ctx0,
  8772. 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)),
  8773. 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))));
  8774. // extract x from x_conv
  8775. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  8776. // bias
  8777. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  8778. x = ggml_silu(ctx0, x);
  8779. }
  8780. // ssm
  8781. {
  8782. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  8783. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  8784. // split
  8785. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  8786. 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);
  8787. 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));
  8788. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  8789. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  8790. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  8791. // Custom operator to optimize the parallel associative scan
  8792. // as described in the Annex D of the Mamba paper.
  8793. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  8794. // because only a single tensor can be returned.
  8795. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  8796. // store last states (the second part of y_ssm_states)
  8797. ggml_build_forward_expand(gf,
  8798. ggml_cpy(ctx0,
  8799. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  8800. 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))));
  8801. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  8802. if (il == n_layer - 1) {
  8803. // skip computing output for unused tokens
  8804. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8805. x = ggml_get_rows(ctx0, x, inp_out_ids);
  8806. y = ggml_get_rows(ctx0, y, inp_out_ids);
  8807. z = ggml_get_rows(ctx0, z, inp_out_ids);
  8808. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8809. }
  8810. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  8811. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  8812. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  8813. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  8814. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  8815. }
  8816. // residual
  8817. cur = ggml_add(ctx0, cur, inpL);
  8818. cb(cur, "l_out", il);
  8819. // input for next layer
  8820. inpL = cur;
  8821. }
  8822. // final rmsnorm
  8823. cur = llm_build_norm(ctx0, inpL, hparams,
  8824. model.output_norm, NULL,
  8825. LLM_NORM_RMS, cb, -1);
  8826. cb(cur, "result_norm", -1);
  8827. // lm_head
  8828. cur = ggml_mul_mat(ctx0, model.output, cur);
  8829. cb(cur, "result_output", -1);
  8830. ggml_build_forward_expand(gf, cur);
  8831. return gf;
  8832. }
  8833. struct ggml_cgraph * build_command_r() {
  8834. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8835. const int64_t n_embd_head = hparams.n_embd_head_v;
  8836. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8837. const float f_logit_scale = hparams.f_logit_scale;
  8838. struct ggml_tensor * cur;
  8839. struct ggml_tensor * inpL;
  8840. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8841. // inp_pos - contains the positions
  8842. struct ggml_tensor * inp_pos = build_inp_pos();
  8843. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8844. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8845. for (int il = 0; il < n_layer; ++il) {
  8846. // norm
  8847. cur = llm_build_norm(ctx0, inpL, hparams,
  8848. model.layers[il].attn_norm, NULL,
  8849. LLM_NORM, cb, il);
  8850. cb(cur, "attn_norm", il);
  8851. struct ggml_tensor * ffn_inp = cur;
  8852. // self-attention
  8853. {
  8854. // compute Q and K and RoPE them
  8855. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8856. cb(Qcur, "Qcur", il);
  8857. if (model.layers[il].bq) {
  8858. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8859. cb(Qcur, "Qcur", il);
  8860. }
  8861. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8862. cb(Kcur, "Kcur", il);
  8863. if (model.layers[il].bk) {
  8864. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8865. cb(Kcur, "Kcur", il);
  8866. }
  8867. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8868. cb(Vcur, "Vcur", il);
  8869. if (model.layers[il].bv) {
  8870. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8871. cb(Vcur, "Vcur", il);
  8872. }
  8873. if (model.layers[il].attn_q_norm) {
  8874. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  8875. ggml_element_size(Qcur) * n_embd_head,
  8876. ggml_element_size(Qcur) * n_embd_head * n_head,
  8877. 0);
  8878. cb(Qcur, "Qcur", il);
  8879. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  8880. ggml_element_size(Kcur) * n_embd_head,
  8881. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  8882. 0);
  8883. cb(Kcur, "Kcur", il);
  8884. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8885. model.layers[il].attn_q_norm,
  8886. NULL,
  8887. LLM_NORM, cb, il);
  8888. cb(Qcur, "Qcur", il);
  8889. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8890. model.layers[il].attn_k_norm,
  8891. NULL,
  8892. LLM_NORM, cb, il);
  8893. cb(Kcur, "Kcur", il);
  8894. }
  8895. Qcur = ggml_rope_ext(
  8896. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  8897. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8898. ext_factor, attn_factor, beta_fast, beta_slow
  8899. );
  8900. cb(Qcur, "Qcur", il);
  8901. Kcur = ggml_rope_ext(
  8902. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  8903. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8904. ext_factor, attn_factor, beta_fast, beta_slow
  8905. );
  8906. cb(Kcur, "Kcur", il);
  8907. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8908. model.layers[il].wo, model.layers[il].bo,
  8909. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8910. }
  8911. if (il == n_layer - 1) {
  8912. // skip computing output for unused tokens
  8913. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8914. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8915. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8916. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  8917. }
  8918. struct ggml_tensor * attn_out = cur;
  8919. // feed-forward network
  8920. {
  8921. cur = llm_build_ffn(ctx0, ffn_inp,
  8922. model.layers[il].ffn_up, NULL,
  8923. model.layers[il].ffn_gate, NULL,
  8924. model.layers[il].ffn_down, NULL,
  8925. NULL,
  8926. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8927. cb(cur, "ffn_out", il);
  8928. }
  8929. // add together residual + FFN + self-attention
  8930. cur = ggml_add(ctx0, cur, inpL);
  8931. cur = ggml_add(ctx0, cur, attn_out);
  8932. cb(cur, "l_out", il);
  8933. // input for next layer
  8934. inpL = cur;
  8935. }
  8936. cur = inpL;
  8937. cur = llm_build_norm(ctx0, cur, hparams,
  8938. model.output_norm, NULL,
  8939. LLM_NORM, cb, -1);
  8940. cb(cur, "result_norm", -1);
  8941. // lm_head
  8942. cur = ggml_mul_mat(ctx0, model.output, cur);
  8943. if (f_logit_scale) {
  8944. cur = ggml_scale(ctx0, cur, f_logit_scale);
  8945. }
  8946. cb(cur, "result_output", -1);
  8947. ggml_build_forward_expand(gf, cur);
  8948. return gf;
  8949. }
  8950. // ref: https://allenai.org/olmo
  8951. // based on the original build_llama() function, changes:
  8952. // * non-parametric layer norm
  8953. // * clamp qkv
  8954. // * removed bias
  8955. // * removed MoE
  8956. struct ggml_cgraph * build_olmo() {
  8957. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8958. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8959. int32_t n_tokens = this->n_tokens;
  8960. const int64_t n_embd_head = hparams.n_embd_head_v;
  8961. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8962. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8963. struct ggml_tensor * cur;
  8964. struct ggml_tensor * inpL;
  8965. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8966. // inp_pos - contains the positions
  8967. struct ggml_tensor * inp_pos = build_inp_pos();
  8968. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8969. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8970. for (int il = 0; il < n_layer; ++il) {
  8971. struct ggml_tensor * inpSA = inpL;
  8972. // norm
  8973. cur = llm_build_norm(ctx0, inpL, hparams,
  8974. NULL, NULL,
  8975. LLM_NORM, cb, il);
  8976. cb(cur, "attn_norm", il);
  8977. // self-attention
  8978. {
  8979. // compute Q and K and RoPE them
  8980. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8981. cb(Qcur, "Qcur", il);
  8982. if (hparams.f_clamp_kqv > 0.0f) {
  8983. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8984. cb(Qcur, "Qcur", il);
  8985. }
  8986. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8987. cb(Kcur, "Kcur", il);
  8988. if (hparams.f_clamp_kqv > 0.0f) {
  8989. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8990. cb(Kcur, "Kcur", il);
  8991. }
  8992. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8993. cb(Vcur, "Vcur", il);
  8994. if (hparams.f_clamp_kqv > 0.0f) {
  8995. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8996. cb(Vcur, "Vcur", il);
  8997. }
  8998. Qcur = ggml_rope_ext(
  8999. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9000. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9001. ext_factor, attn_factor, beta_fast, beta_slow
  9002. );
  9003. cb(Qcur, "Qcur", il);
  9004. Kcur = ggml_rope_ext(
  9005. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9006. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9007. ext_factor, attn_factor, beta_fast, beta_slow
  9008. );
  9009. cb(Kcur, "Kcur", il);
  9010. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  9011. model.layers[il].wo, nullptr,
  9012. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9013. }
  9014. if (il == n_layer - 1) {
  9015. // skip computing output for unused tokens
  9016. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9017. n_tokens = n_outputs;
  9018. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9019. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9020. }
  9021. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9022. cb(ffn_inp, "ffn_inp", il);
  9023. // feed-forward network
  9024. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9025. NULL, NULL,
  9026. LLM_NORM, cb, il);
  9027. cb(cur, "ffn_norm", il);
  9028. cur = llm_build_ffn(ctx0, cur,
  9029. model.layers[il].ffn_up, NULL,
  9030. model.layers[il].ffn_gate, NULL,
  9031. model.layers[il].ffn_down, NULL,
  9032. NULL,
  9033. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9034. cb(cur, "ffn_out", il);
  9035. cur = ggml_add(ctx0, cur, ffn_inp);
  9036. cb(cur, "ffn_out", il);
  9037. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  9038. if (layer_dir != nullptr) {
  9039. cur = ggml_add(ctx0, cur, layer_dir);
  9040. }
  9041. cb(cur, "l_out", il);
  9042. // input for next layer
  9043. inpL = cur;
  9044. }
  9045. cur = inpL;
  9046. cur = llm_build_norm(ctx0, cur, hparams,
  9047. NULL, NULL,
  9048. LLM_NORM, cb, -1);
  9049. cb(cur, "result_norm", -1);
  9050. // lm_head
  9051. cur = ggml_mul_mat(ctx0, model.output, cur);
  9052. cb(cur, "result_output", -1);
  9053. ggml_build_forward_expand(gf, cur);
  9054. return gf;
  9055. }
  9056. struct ggml_cgraph * build_gptneox() {
  9057. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  9058. const int64_t n_embd_head = hparams.n_embd_head_v;
  9059. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  9060. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9061. struct ggml_tensor * cur;
  9062. struct ggml_tensor * inpL;
  9063. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9064. // inp_pos - contains the positions
  9065. struct ggml_tensor * inp_pos = build_inp_pos();
  9066. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9067. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9068. for (int il = 0; il < n_layer; ++il) {
  9069. cur = llm_build_norm(ctx0, inpL, hparams,
  9070. model.layers[il].attn_norm,
  9071. model.layers[il].attn_norm_b,
  9072. LLM_NORM, cb, il);
  9073. cb(cur, "attn_norm", il);
  9074. // self-attention
  9075. {
  9076. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  9077. cb(cur, "wqkv", il);
  9078. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  9079. cb(cur, "bqkv", il);
  9080. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  9081. 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)));
  9082. 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)));
  9083. cb(Qcur, "Qcur", il);
  9084. cb(Kcur, "Kcur", il);
  9085. cb(Vcur, "Vcur", il);
  9086. Qcur = ggml_rope_ext(
  9087. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9088. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9089. ext_factor, attn_factor, beta_fast, beta_slow
  9090. );
  9091. cb(Qcur, "Qcur", il);
  9092. Kcur = ggml_rope_ext(
  9093. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9094. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9095. ext_factor, attn_factor, beta_fast, beta_slow
  9096. );
  9097. cb(Kcur, "Kcur", il);
  9098. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  9099. model.layers[il].wo, model.layers[il].bo,
  9100. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9101. }
  9102. if (il == n_layer - 1) {
  9103. // skip computing output for unused tokens
  9104. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9105. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9106. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  9107. }
  9108. // ffn
  9109. if (hparams.use_par_res) {
  9110. // attention and ffn are computed in parallel
  9111. // x = x + attn(ln1(x)) + ffn(ln2(x))
  9112. struct ggml_tensor * attn_out = cur;
  9113. cur = llm_build_norm(ctx0, inpL, hparams,
  9114. model.layers[il].ffn_norm,
  9115. model.layers[il].ffn_norm_b,
  9116. LLM_NORM, cb, il);
  9117. cb(cur, "ffn_norm", il);
  9118. cur = llm_build_ffn(ctx0, cur,
  9119. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  9120. NULL, NULL,
  9121. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  9122. NULL,
  9123. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9124. cb(cur, "ffn_out", il);
  9125. cur = ggml_add(ctx0, cur, inpL);
  9126. cb(cur, "ffn_out", il);
  9127. inpL = ggml_add(ctx0, cur, attn_out);
  9128. cb(inpL, "l_out", il);
  9129. } else {
  9130. // attention and ffn are computed sequentially
  9131. // x = x + attn(ln1(x))
  9132. // x = x + ffn(ln2(x))
  9133. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  9134. cb(ffn_inp, "ffn_inp", il);
  9135. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9136. model.layers[il].ffn_norm,
  9137. model.layers[il].ffn_norm_b,
  9138. LLM_NORM, cb, il);
  9139. cb(cur, "ffn_norm", il);
  9140. cur = llm_build_ffn(ctx0, cur,
  9141. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  9142. NULL, NULL,
  9143. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  9144. NULL,
  9145. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  9146. cb(cur, "ffn_out", il);
  9147. inpL = ggml_add(ctx0, cur, ffn_inp);
  9148. cb(inpL, "l_out", il);
  9149. }
  9150. }
  9151. cur = llm_build_norm(ctx0, inpL, hparams,
  9152. model.output_norm,
  9153. model.output_norm_b,
  9154. LLM_NORM, cb, -1);
  9155. cb(cur, "result_norm", -1);
  9156. cur = ggml_mul_mat(ctx0, model.output, cur);
  9157. cb(cur, "result_output", -1);
  9158. ggml_build_forward_expand(gf, cur);
  9159. return gf;
  9160. }
  9161. struct ggml_cgraph * build_arctic() {
  9162. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  9163. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9164. int32_t n_tokens = this->n_tokens;
  9165. const int64_t n_embd_head = hparams.n_embd_head_v;
  9166. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  9167. GGML_ASSERT(n_embd_head == hparams.n_rot);
  9168. struct ggml_tensor * cur;
  9169. struct ggml_tensor * inpL;
  9170. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9171. // inp_pos - contains the positions
  9172. struct ggml_tensor * inp_pos = build_inp_pos();
  9173. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9174. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9175. for (int il = 0; il < n_layer; ++il) {
  9176. struct ggml_tensor * inpSA = inpL;
  9177. // norm
  9178. cur = llm_build_norm(ctx0, inpL, hparams,
  9179. model.layers[il].attn_norm, NULL,
  9180. LLM_NORM_RMS, cb, il);
  9181. cb(cur, "attn_norm", il);
  9182. // self-attention
  9183. {
  9184. // compute Q and K and RoPE them
  9185. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  9186. cb(Qcur, "Qcur", il);
  9187. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  9188. cb(Kcur, "Kcur", il);
  9189. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  9190. cb(Vcur, "Vcur", il);
  9191. Qcur = ggml_rope_ext(
  9192. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos, nullptr,
  9193. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9194. ext_factor, attn_factor, beta_fast, beta_slow
  9195. );
  9196. cb(Qcur, "Qcur", il);
  9197. Kcur = ggml_rope_ext(
  9198. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos, nullptr,
  9199. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9200. ext_factor, attn_factor, beta_fast, beta_slow
  9201. );
  9202. cb(Kcur, "Kcur", il);
  9203. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  9204. model.layers[il].wo, NULL,
  9205. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  9206. }
  9207. if (il == n_layer - 1) {
  9208. // skip computing output for unused tokens
  9209. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9210. n_tokens = n_outputs;
  9211. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9212. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9213. }
  9214. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9215. cb(ffn_inp, "ffn_inp", il);
  9216. // feed-forward network
  9217. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9218. model.layers[il].ffn_norm, NULL,
  9219. LLM_NORM_RMS, cb, il);
  9220. cb(cur, "ffn_norm", il);
  9221. cur = llm_build_ffn(ctx0, cur,
  9222. model.layers[il].ffn_up, NULL,
  9223. model.layers[il].ffn_gate, NULL,
  9224. model.layers[il].ffn_down, NULL,
  9225. NULL,
  9226. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9227. cb(cur, "ffn_out", il);
  9228. struct ggml_tensor * ffn_out = ggml_add(ctx0, cur, ffn_inp);
  9229. cb(ffn_out, "ffn_out", il);
  9230. // MoE
  9231. cur = llm_build_norm(ctx0, inpSA, hparams,
  9232. model.layers[il].ffn_norm_exps, NULL,
  9233. LLM_NORM_RMS, cb, il);
  9234. cb(cur, "ffn_norm_exps", il);
  9235. cur = llm_build_moe_ffn(ctx0, cur,
  9236. model.layers[il].ffn_gate_inp,
  9237. model.layers[il].ffn_up_exps,
  9238. model.layers[il].ffn_gate_exps,
  9239. model.layers[il].ffn_down_exps,
  9240. n_expert, n_expert_used,
  9241. LLM_FFN_SILU, true,
  9242. false, 0.0,
  9243. cb, il);
  9244. cb(cur, "ffn_moe_out", il);
  9245. cur = ggml_add(ctx0, cur, ffn_out);
  9246. cb(cur, "ffn_out", il);
  9247. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  9248. if (layer_dir != nullptr) {
  9249. cur = ggml_add(ctx0, cur, layer_dir);
  9250. }
  9251. cb(cur, "l_out", il);
  9252. // input for next layer
  9253. inpL = cur;
  9254. }
  9255. cur = inpL;
  9256. cur = llm_build_norm(ctx0, cur, hparams,
  9257. model.output_norm, NULL,
  9258. LLM_NORM_RMS, cb, -1);
  9259. cb(cur, "result_norm", -1);
  9260. // lm_head
  9261. cur = ggml_mul_mat(ctx0, model.output, cur);
  9262. cb(cur, "result_output", -1);
  9263. ggml_build_forward_expand(gf, cur);
  9264. return gf;
  9265. }
  9266. struct ggml_cgraph * build_deepseek2() {
  9267. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  9268. // mutable variable, needed during the last layer of the computation to skip unused tokens
  9269. int32_t n_tokens = this->n_tokens;
  9270. bool is_lite = (hparams.n_layer == 27);
  9271. // We have to pre-scale kq_scale and attn_factor to make the YaRN RoPE work correctly.
  9272. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation.
  9273. const float mscale = attn_factor * (1.0f + hparams.rope_yarn_log_mul * logf(1.0f / freq_scale));
  9274. const float kq_scale = 1.0f*mscale*mscale/sqrtf(float(hparams.n_embd_head_k));
  9275. const float attn_factor_scaled = 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale));
  9276. const uint32_t n_embd_head_qk_rope = hparams.n_rot;
  9277. const uint32_t n_embd_head_qk_nope = hparams.n_embd_head_k - hparams.n_rot;
  9278. const uint32_t kv_lora_rank = hparams.n_lora_kv;
  9279. struct ggml_tensor * cur;
  9280. struct ggml_tensor * inpL;
  9281. // {n_embd, n_tokens}
  9282. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  9283. // inp_pos - contains the positions
  9284. struct ggml_tensor * inp_pos = build_inp_pos();
  9285. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  9286. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  9287. for (int il = 0; il < n_layer; ++il) {
  9288. struct ggml_tensor * inpSA = inpL;
  9289. // norm
  9290. cur = llm_build_norm(ctx0, inpL, hparams,
  9291. model.layers[il].attn_norm, NULL,
  9292. LLM_NORM_RMS, cb, il);
  9293. cb(cur, "attn_norm", il);
  9294. // self_attention
  9295. {
  9296. struct ggml_tensor * q = NULL;
  9297. if (!is_lite) {
  9298. // {n_embd, q_lora_rank} * {n_embd, n_tokens} -> {q_lora_rank, n_tokens}
  9299. q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
  9300. cb(q, "q", il);
  9301. q = llm_build_norm(ctx0, q, hparams,
  9302. model.layers[il].attn_q_a_norm, NULL,
  9303. LLM_NORM_RMS, cb, il);
  9304. cb(q, "q", il);
  9305. // {q_lora_rank, n_head * hparams.n_embd_head_k} * {q_lora_rank, n_tokens} -> {n_head * hparams.n_embd_head_k, n_tokens}
  9306. q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
  9307. cb(q, "q", il);
  9308. } else {
  9309. q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  9310. cb(q, "q", il);
  9311. }
  9312. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  9313. struct ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head, n_tokens,
  9314. ggml_row_size(q->type, hparams.n_embd_head_k),
  9315. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  9316. 0);
  9317. cb(q_nope, "q_nope", il);
  9318. // and {n_head * n_embd_head_qk_rope, n_tokens}
  9319. struct ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head, n_tokens,
  9320. ggml_row_size(q->type, hparams.n_embd_head_k),
  9321. ggml_row_size(q->type, hparams.n_embd_head_k * n_head),
  9322. ggml_row_size(q->type, n_embd_head_qk_nope));
  9323. cb(q_pe, "q_pe", il);
  9324. // {n_embd, kv_lora_rank + n_embd_head_qk_rope} * {n_embd, n_tokens} -> {kv_lora_rank + n_embd_head_qk_rope, n_tokens}
  9325. struct ggml_tensor * kv_pe_compresseed = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
  9326. cb(kv_pe_compresseed, "kv_pe_compresseed", il);
  9327. // split into {kv_lora_rank, n_tokens}
  9328. struct ggml_tensor * kv_compressed = ggml_view_2d(ctx0, kv_pe_compresseed, kv_lora_rank, n_tokens,
  9329. kv_pe_compresseed->nb[1],
  9330. 0);
  9331. cb(kv_compressed, "kv_compressed", il);
  9332. // and {n_embd_head_qk_rope, n_tokens}
  9333. struct ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_pe_compresseed, n_embd_head_qk_rope, 1, n_tokens,
  9334. kv_pe_compresseed->nb[1],
  9335. kv_pe_compresseed->nb[1],
  9336. ggml_row_size(kv_pe_compresseed->type, kv_lora_rank));
  9337. cb(k_pe, "k_pe", il);
  9338. kv_compressed = ggml_cont(ctx0, kv_compressed); // TODO: the CUDA backend does not support non-contiguous norm
  9339. kv_compressed = llm_build_norm(ctx0, kv_compressed, hparams,
  9340. model.layers[il].attn_kv_a_norm, NULL,
  9341. LLM_NORM_RMS, cb, il);
  9342. cb(kv_compressed, "kv_compressed", il);
  9343. // {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}
  9344. struct ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_compressed);
  9345. cb(kv, "kv", il);
  9346. // split into {n_head * n_embd_head_qk_nope, n_tokens}
  9347. struct ggml_tensor * k_nope = ggml_view_3d(ctx0, kv, n_embd_head_qk_nope, n_head, n_tokens,
  9348. ggml_row_size(kv->type, n_embd_head_qk_nope + hparams.n_embd_head_v),
  9349. ggml_row_size(kv->type, n_head * (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  9350. 0);
  9351. cb(k_nope, "k_nope", il);
  9352. // and {n_head * n_embd_head_v, n_tokens}
  9353. struct ggml_tensor * v_states = ggml_view_3d(ctx0, kv, hparams.n_embd_head_v, n_head, n_tokens,
  9354. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)),
  9355. ggml_row_size(kv->type, (n_embd_head_qk_nope + hparams.n_embd_head_v)*n_head),
  9356. ggml_row_size(kv->type, (n_embd_head_qk_nope)));
  9357. cb(v_states, "v_states", il);
  9358. v_states = ggml_cont(ctx0, v_states);
  9359. cb(v_states, "v_states", il);
  9360. v_states = ggml_view_2d(ctx0, v_states, hparams.n_embd_head_v * n_head, n_tokens,
  9361. ggml_row_size(kv->type, hparams.n_embd_head_v * n_head),
  9362. 0);
  9363. cb(v_states, "v_states", il);
  9364. q_pe = ggml_cont(ctx0, q_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  9365. q_pe = ggml_rope_ext(
  9366. ctx0, q_pe, inp_pos, nullptr,
  9367. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9368. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  9369. );
  9370. cb(q_pe, "q_pe", il);
  9371. // shared RoPE key
  9372. k_pe = ggml_cont(ctx0, k_pe); // TODO: the CUDA backend does not support non-contiguous RoPE
  9373. k_pe = ggml_rope_ext(
  9374. ctx0, k_pe, inp_pos, nullptr,
  9375. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  9376. ext_factor, attn_factor_scaled, beta_fast, beta_slow
  9377. );
  9378. cb(k_pe, "k_pe", il);
  9379. struct ggml_tensor * q_states = ggml_concat(ctx0, q_nope, q_pe, 0);
  9380. cb(q_states, "q_states", il);
  9381. struct ggml_tensor * k_states = ggml_concat(ctx0, k_nope, ggml_repeat(ctx0, k_pe, q_pe), 0);
  9382. cb(k_states, "k_states", il);
  9383. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  9384. model.layers[il].wo, NULL,
  9385. k_states, v_states, q_states, KQ_mask, n_tokens, kv_head, n_kv, kq_scale, cb, il);
  9386. }
  9387. if (il == n_layer - 1) {
  9388. // skip computing output for unused tokens
  9389. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  9390. n_tokens = n_outputs;
  9391. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  9392. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  9393. }
  9394. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  9395. cb(ffn_inp, "ffn_inp", il);
  9396. if ((uint32_t) il < hparams.n_layer_dense_lead) {
  9397. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9398. model.layers[il].ffn_norm, NULL,
  9399. LLM_NORM_RMS, cb, il);
  9400. cb(cur, "ffn_norm", il);
  9401. cur = llm_build_ffn(ctx0, cur,
  9402. model.layers[il].ffn_up, NULL,
  9403. model.layers[il].ffn_gate, NULL,
  9404. model.layers[il].ffn_down, NULL,
  9405. NULL,
  9406. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9407. cb(cur, "ffn_out", il);
  9408. } else {
  9409. // MoE branch
  9410. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  9411. model.layers[il].ffn_norm, NULL,
  9412. LLM_NORM_RMS, cb, il);
  9413. cb(cur, "ffn_norm", il);
  9414. ggml_tensor * moe_out =
  9415. llm_build_moe_ffn(ctx0, cur,
  9416. model.layers[il].ffn_gate_inp,
  9417. model.layers[il].ffn_up_exps,
  9418. model.layers[il].ffn_gate_exps,
  9419. model.layers[il].ffn_down_exps,
  9420. n_expert, n_expert_used,
  9421. LLM_FFN_SILU, false,
  9422. true, hparams.expert_weights_scale,
  9423. cb, il);
  9424. cb(moe_out, "ffn_moe_out", il);
  9425. // FFN shared expert
  9426. {
  9427. ggml_tensor * ffn_shexp = llm_build_ffn(ctx0, cur,
  9428. model.layers[il].ffn_up_shexp, NULL,
  9429. model.layers[il].ffn_gate_shexp, NULL,
  9430. model.layers[il].ffn_down_shexp, NULL,
  9431. NULL,
  9432. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  9433. cb(ffn_shexp, "ffn_shexp", il);
  9434. cur = ggml_add(ctx0, moe_out, ffn_shexp);
  9435. cb(cur, "ffn_out", il);
  9436. }
  9437. }
  9438. cur = ggml_add(ctx0, cur, ffn_inp);
  9439. cb(cur, "l_out", il);
  9440. // input for next layer
  9441. inpL = cur;
  9442. }
  9443. cur = inpL;
  9444. cur = llm_build_norm(ctx0, cur, hparams,
  9445. model.output_norm, NULL,
  9446. LLM_NORM_RMS, cb, -1);
  9447. cb(cur, "result_norm", -1);
  9448. // lm_head
  9449. cur = ggml_mul_mat(ctx0, model.output, cur);
  9450. cb(cur, "result_output", -1);
  9451. ggml_build_forward_expand(gf, cur);
  9452. return gf;
  9453. }
  9454. };
  9455. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  9456. llama_batch dummy;
  9457. dummy.n_tokens = 0;
  9458. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  9459. struct llm_build_context llm(lctx, dummy, cb, false);
  9460. llm.init();
  9461. struct ggml_cgraph * result = llm.build_defrag(ids);
  9462. llm.free();
  9463. return result;
  9464. }
  9465. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  9466. llama_batch dummy;
  9467. dummy.n_tokens = 0;
  9468. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  9469. struct llm_build_context llm(lctx, dummy, cb, false);
  9470. llm.init();
  9471. struct ggml_cgraph * result = llm.build_k_shift();
  9472. llm.free();
  9473. return result;
  9474. }
  9475. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  9476. llama_batch dummy;
  9477. dummy.n_tokens = 0;
  9478. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  9479. struct llm_build_context llm(lctx, dummy, cb, false);
  9480. llm.init();
  9481. struct ggml_cgraph * result = llm.build_s_copy();
  9482. llm.free();
  9483. return result;
  9484. }
  9485. static struct ggml_cgraph * llama_build_graph(
  9486. llama_context & lctx,
  9487. const llama_batch & batch,
  9488. bool worst_case) {
  9489. const auto & model = lctx.model;
  9490. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  9491. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  9492. if (il >= 0) {
  9493. ggml_format_name(cur, "%s-%d", name, il);
  9494. } else {
  9495. ggml_set_name(cur, name);
  9496. }
  9497. if (!lctx.cparams.offload_kqv) {
  9498. if (strcmp(name, "kqv_merged_cont") == 0) {
  9499. // all nodes between the KV store and the attention output are run on the CPU
  9500. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  9501. }
  9502. }
  9503. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  9504. // FIXME: fix in ggml_backend_sched
  9505. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  9506. if (batch.n_tokens < 32 || full_offload) {
  9507. if (il != -1 && strcmp(name, "norm") == 0) {
  9508. for (auto * backend : lctx.backends) {
  9509. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  9510. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  9511. break;
  9512. }
  9513. }
  9514. }
  9515. }
  9516. };
  9517. struct ggml_cgraph * result = NULL;
  9518. struct llm_build_context llm(lctx, batch, cb, worst_case);
  9519. llm.init();
  9520. switch (model.arch) {
  9521. case LLM_ARCH_LLAMA:
  9522. {
  9523. result = llm.build_llama();
  9524. } break;
  9525. case LLM_ARCH_BAICHUAN:
  9526. {
  9527. result = llm.build_baichuan();
  9528. } break;
  9529. case LLM_ARCH_FALCON:
  9530. {
  9531. result = llm.build_falcon();
  9532. } break;
  9533. case LLM_ARCH_GROK:
  9534. {
  9535. result = llm.build_grok();
  9536. } break;
  9537. case LLM_ARCH_STARCODER:
  9538. {
  9539. result = llm.build_starcoder();
  9540. } break;
  9541. case LLM_ARCH_REFACT:
  9542. {
  9543. result = llm.build_refact();
  9544. } break;
  9545. case LLM_ARCH_BERT:
  9546. case LLM_ARCH_JINA_BERT_V2:
  9547. case LLM_ARCH_NOMIC_BERT:
  9548. {
  9549. result = llm.build_bert();
  9550. } break;
  9551. case LLM_ARCH_BLOOM:
  9552. {
  9553. result = llm.build_bloom();
  9554. } break;
  9555. case LLM_ARCH_MPT:
  9556. {
  9557. result = llm.build_mpt();
  9558. } break;
  9559. case LLM_ARCH_STABLELM:
  9560. {
  9561. result = llm.build_stablelm();
  9562. } break;
  9563. case LLM_ARCH_QWEN:
  9564. {
  9565. result = llm.build_qwen();
  9566. } break;
  9567. case LLM_ARCH_QWEN2:
  9568. {
  9569. result = llm.build_qwen2();
  9570. } break;
  9571. case LLM_ARCH_QWEN2MOE:
  9572. {
  9573. result = llm.build_qwen2moe();
  9574. } break;
  9575. case LLM_ARCH_PHI2:
  9576. {
  9577. result = llm.build_phi2();
  9578. } break;
  9579. case LLM_ARCH_PHI3:
  9580. {
  9581. result = llm.build_phi3();
  9582. } break;
  9583. case LLM_ARCH_PLAMO:
  9584. {
  9585. result = llm.build_plamo();
  9586. } break;
  9587. case LLM_ARCH_GPT2:
  9588. {
  9589. result = llm.build_gpt2();
  9590. } break;
  9591. case LLM_ARCH_CODESHELL:
  9592. {
  9593. result = llm.build_codeshell();
  9594. } break;
  9595. case LLM_ARCH_ORION:
  9596. {
  9597. result = llm.build_orion();
  9598. } break;
  9599. case LLM_ARCH_INTERNLM2:
  9600. {
  9601. result = llm.build_internlm2();
  9602. } break;
  9603. case LLM_ARCH_MINICPM:
  9604. {
  9605. result = llm.build_minicpm();
  9606. } break;
  9607. case LLM_ARCH_GEMMA:
  9608. {
  9609. result = llm.build_gemma();
  9610. } break;
  9611. case LLM_ARCH_STARCODER2:
  9612. {
  9613. result = llm.build_starcoder2();
  9614. } break;
  9615. case LLM_ARCH_MAMBA:
  9616. {
  9617. result = llm.build_mamba();
  9618. } break;
  9619. case LLM_ARCH_XVERSE:
  9620. {
  9621. result = llm.build_xverse();
  9622. } break;
  9623. case LLM_ARCH_COMMAND_R:
  9624. {
  9625. result = llm.build_command_r();
  9626. } break;
  9627. case LLM_ARCH_DBRX:
  9628. {
  9629. result = llm.build_dbrx();
  9630. } break;
  9631. case LLM_ARCH_OLMO:
  9632. {
  9633. result = llm.build_olmo();
  9634. } break;
  9635. case LLM_ARCH_GPTNEOX:
  9636. {
  9637. result = llm.build_gptneox();
  9638. } break;
  9639. case LLM_ARCH_ARCTIC:
  9640. {
  9641. result = llm.build_arctic();
  9642. } break;
  9643. case LLM_ARCH_DEEPSEEK2:
  9644. {
  9645. result = llm.build_deepseek2();
  9646. } break;
  9647. default:
  9648. GGML_ASSERT(false);
  9649. }
  9650. llm.free();
  9651. return result;
  9652. }
  9653. static void llama_set_k_shift(llama_context & lctx) {
  9654. const int64_t kv_size = lctx.kv_self.size;
  9655. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  9656. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  9657. for (int i = 0; i < kv_size; ++i) {
  9658. data[i] = lctx.kv_self.cells[i].delta;
  9659. }
  9660. }
  9661. static void llama_set_s_copy(llama_context & lctx) {
  9662. const int64_t kv_size = lctx.kv_self.size;
  9663. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  9664. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  9665. for (int i = 0; i < kv_size; ++i) {
  9666. data[i] = lctx.kv_self.cells[i].src;
  9667. }
  9668. }
  9669. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  9670. //
  9671. // set input data
  9672. //
  9673. const auto & hparams = lctx.model.hparams;
  9674. const auto & cparams = lctx.cparams;
  9675. const auto & kv_self = lctx.kv_self;
  9676. if (batch.token) {
  9677. const int64_t n_tokens = batch.n_tokens;
  9678. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  9679. }
  9680. if (batch.embd) {
  9681. const int64_t n_embd = hparams.n_embd;
  9682. const int64_t n_tokens = batch.n_tokens;
  9683. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  9684. }
  9685. if (batch.pos && lctx.inp_pos) {
  9686. const int64_t n_tokens = batch.n_tokens;
  9687. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  9688. }
  9689. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  9690. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  9691. const int64_t n_tokens = batch.n_tokens;
  9692. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  9693. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  9694. if (lctx.n_outputs == n_tokens) {
  9695. for (int i = 0; i < n_tokens; ++i) {
  9696. data[i] = i;
  9697. }
  9698. } else if (batch.logits) {
  9699. int32_t n_outputs = 0;
  9700. for (int i = 0; i < n_tokens; ++i) {
  9701. if (batch.logits[i]) {
  9702. data[n_outputs++] = i;
  9703. }
  9704. }
  9705. // the graph needs to have been passed the correct number of outputs
  9706. GGML_ASSERT(lctx.n_outputs == n_outputs);
  9707. } else if (lctx.n_outputs == 1) {
  9708. // only keep last output
  9709. data[0] = n_tokens - 1;
  9710. } else {
  9711. GGML_ASSERT(lctx.n_outputs == 0);
  9712. }
  9713. }
  9714. GGML_ASSERT(
  9715. // (!a || b) is a logical implication (a -> b)
  9716. // !hparams.causal_attn -> !cparams.causal_attn
  9717. (hparams.causal_attn || !cparams.causal_attn) &&
  9718. "causal attention with embedding models is not supported"
  9719. );
  9720. if (lctx.inp_KQ_mask) {
  9721. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  9722. if (cparams.causal_attn) {
  9723. const int64_t n_kv = kv_self.n;
  9724. const int64_t n_tokens = batch.n_tokens;
  9725. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  9726. float * data = (float *) lctx.inp_KQ_mask->data;
  9727. // For causal attention, use only the previous KV cells
  9728. // of the correct sequence for each token of the batch.
  9729. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  9730. for (int h = 0; h < 1; ++h) {
  9731. for (int j = 0; j < n_tokens; ++j) {
  9732. const llama_pos pos = batch.pos[j];
  9733. const llama_seq_id seq_id = batch.seq_id[j][0];
  9734. for (int i = 0; i < n_kv; ++i) {
  9735. float f;
  9736. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  9737. f = -INFINITY;
  9738. } else {
  9739. if (hparams.use_alibi) {
  9740. f = -fabs(lctx.kv_self.cells[i].pos - pos);
  9741. } else {
  9742. f = 0.0f;
  9743. }
  9744. }
  9745. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  9746. }
  9747. }
  9748. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  9749. for (int j = 0; j < n_kv; ++j) {
  9750. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  9751. }
  9752. }
  9753. }
  9754. } else {
  9755. // when using kv cache, the mask needs to match the kv cache size
  9756. const int64_t n_tokens = batch.n_tokens;
  9757. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  9758. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  9759. float * data = (float *) lctx.inp_KQ_mask->data;
  9760. for (int h = 0; h < 1; ++h) {
  9761. for (int j = 0; j < n_tokens; ++j) {
  9762. const llama_seq_id seq_id = batch.seq_id[j][0];
  9763. for (int i = 0; i < n_tokens; ++i) {
  9764. float f = -INFINITY;
  9765. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  9766. if (batch.seq_id[i][s] == seq_id) {
  9767. if (hparams.use_alibi) {
  9768. f = -fabs(batch.pos[i] - batch.pos[j]);
  9769. } else {
  9770. f = 0.0f;
  9771. }
  9772. break;
  9773. }
  9774. }
  9775. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  9776. }
  9777. for (int i = n_tokens; i < n_stride; ++i) {
  9778. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  9779. }
  9780. }
  9781. }
  9782. }
  9783. }
  9784. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  9785. const int64_t n_tokens = batch.n_tokens;
  9786. GGML_ASSERT(lctx.inp_mean);
  9787. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  9788. float * data = (float *) lctx.inp_mean->data;
  9789. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  9790. std::vector<uint64_t> sum(n_tokens, 0);
  9791. for (int i = 0; i < n_tokens; ++i) {
  9792. const llama_seq_id seq_id = batch.seq_id[i][0];
  9793. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  9794. sum[seq_id] += 1;
  9795. }
  9796. std::vector<float> div(n_tokens, 0.0f);
  9797. for (int i = 0; i < n_tokens; ++i) {
  9798. const uint64_t s = sum[i];
  9799. if (s > 0) {
  9800. div[i] = 1.0f/float(s);
  9801. }
  9802. }
  9803. for (int i = 0; i < n_tokens; ++i) {
  9804. const llama_seq_id seq_id = batch.seq_id[i][0];
  9805. data[seq_id*n_tokens + i] = div[seq_id];
  9806. }
  9807. }
  9808. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  9809. const int64_t n_tokens = batch.n_tokens;
  9810. GGML_ASSERT(lctx.inp_cls);
  9811. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  9812. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  9813. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  9814. for (int i = 0; i < n_tokens; ++i) {
  9815. const llama_seq_id seq_id = batch.seq_id[i][0];
  9816. const llama_pos pos = batch.pos[i];
  9817. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  9818. if (pos == 0) {
  9819. data[seq_id] = i;
  9820. }
  9821. }
  9822. }
  9823. if (kv_self.recurrent) {
  9824. const int64_t n_kv = kv_self.n;
  9825. if (lctx.inp_s_mask) {
  9826. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  9827. float * data = (float *) lctx.inp_s_mask->data;
  9828. // states which are not affected by the current batch are left untouched
  9829. for (int i = 0; i < n_kv; ++i) {
  9830. llama_seq_id seq_id = i + lctx.kv_self.head;
  9831. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  9832. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  9833. data[i] = (float) has_self_seq;
  9834. // ensure current sequences will be kept
  9835. if (!has_self_seq && kv_cell.pos >= 0) {
  9836. kv_cell.seq_id.insert(seq_id);
  9837. }
  9838. }
  9839. }
  9840. // For Mamba (and other recurrent architectures),
  9841. // update the correct state(s)/sequence(s) for each token of the batch.
  9842. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  9843. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  9844. if (lctx.inp_s_seq) {
  9845. const int64_t n_tokens = batch.n_tokens;
  9846. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  9847. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  9848. for (int j = 0; j < n_tokens; ++j) {
  9849. const int32_t n_seq = batch.n_seq_id[j];
  9850. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  9851. for (int i = 0; i < n_kv; ++i) {
  9852. if (i < n_seq) {
  9853. // for this type of model, the head is the minimum seq_id of the batch
  9854. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  9855. } else {
  9856. data[j*n_kv + i] = -1;
  9857. }
  9858. }
  9859. }
  9860. }
  9861. }
  9862. }
  9863. // Make sure enough space is available for outputs.
  9864. // Returns max number of outputs for which space was reserved.
  9865. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  9866. const auto & cparams = lctx.cparams;
  9867. const auto & hparams = lctx.model.hparams;
  9868. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  9869. const auto n_batch = cparams.n_batch;
  9870. const auto n_vocab = hparams.n_vocab;
  9871. const auto n_embd = hparams.n_embd;
  9872. // TODO: use a per-batch flag for logits presence instead
  9873. const bool has_logits = cparams.causal_attn;
  9874. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  9875. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  9876. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  9877. if (lctx.output_ids.empty()) {
  9878. // init, never resized afterwards
  9879. lctx.output_ids.resize(n_batch);
  9880. }
  9881. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  9882. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  9883. // alloc only when more than the current capacity is required
  9884. // TODO: also consider shrinking the buffer
  9885. if (!lctx.buf_output || prev_size < new_size) {
  9886. if (lctx.buf_output) {
  9887. #ifndef NDEBUG
  9888. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  9889. 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);
  9890. #endif
  9891. ggml_backend_buffer_free(lctx.buf_output);
  9892. lctx.buf_output = nullptr;
  9893. lctx.logits = nullptr;
  9894. lctx.embd = nullptr;
  9895. }
  9896. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  9897. if (lctx.buf_output == nullptr) {
  9898. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  9899. return 0;
  9900. }
  9901. }
  9902. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  9903. lctx.logits = has_logits ? output_base : nullptr;
  9904. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  9905. lctx.output_size = n_outputs_max;
  9906. lctx.logits_size = logits_size;
  9907. lctx.embd_size = embd_size;
  9908. // set all ids as invalid (negative)
  9909. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  9910. ggml_backend_buffer_clear(lctx.buf_output, 0);
  9911. lctx.n_outputs = 0;
  9912. return n_outputs_max;
  9913. }
  9914. static void llama_graph_compute(
  9915. llama_context & lctx,
  9916. ggml_cgraph * gf,
  9917. int n_threads) {
  9918. #ifdef GGML_USE_METAL
  9919. if (ggml_backend_is_metal(lctx.backend_metal)) {
  9920. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  9921. }
  9922. #endif
  9923. if (lctx.backend_cpu != nullptr) {
  9924. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  9925. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  9926. }
  9927. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  9928. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  9929. }
  9930. // decode a batch of tokens by evaluating the transformer
  9931. //
  9932. // - lctx: llama context
  9933. // - batch: batch to evaluate
  9934. //
  9935. // return 0 on success
  9936. // return positive int on warning
  9937. // return negative int on error
  9938. //
  9939. static int llama_decode_internal(
  9940. llama_context & lctx,
  9941. llama_batch batch_all) { // TODO: rename back to batch
  9942. const uint32_t n_tokens_all = batch_all.n_tokens;
  9943. if (n_tokens_all == 0) {
  9944. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  9945. return -1;
  9946. }
  9947. const auto & model = lctx.model;
  9948. const auto & hparams = model.hparams;
  9949. const auto & cparams = lctx.cparams;
  9950. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  9951. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  9952. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  9953. if (lctx.t_compute_start_us == 0) {
  9954. lctx.t_compute_start_us = ggml_time_us();
  9955. }
  9956. lctx.n_queued_tokens += n_tokens_all;
  9957. auto & kv_self = lctx.kv_self;
  9958. const int64_t n_embd = hparams.n_embd;
  9959. const int64_t n_vocab = hparams.n_vocab;
  9960. uint32_t n_outputs = 0;
  9961. uint32_t n_outputs_prev = 0;
  9962. const auto n_ubatch = cparams.n_ubatch;
  9963. std::vector<llama_pos> pos;
  9964. std::vector<int32_t> n_seq_id;
  9965. std::vector<llama_seq_id *> seq_id_arr;
  9966. std::vector<std::vector<llama_seq_id>> seq_id;
  9967. // count outputs
  9968. if (batch_all.logits) {
  9969. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  9970. n_outputs += batch_all.logits[i] != 0;
  9971. }
  9972. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  9973. n_outputs = n_tokens_all;
  9974. } else {
  9975. // keep last output only
  9976. n_outputs = 1;
  9977. }
  9978. // reserve output buffer
  9979. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  9980. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  9981. return -2;
  9982. };
  9983. // set output mappings
  9984. if (batch_all.logits) {
  9985. int32_t i_logits = 0;
  9986. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  9987. if (batch_all.logits[i]) {
  9988. lctx.output_ids[i] = i_logits++;
  9989. }
  9990. }
  9991. } else {
  9992. for (uint32_t i = 0; i < n_outputs; ++i) {
  9993. lctx.output_ids[i] = i;
  9994. }
  9995. }
  9996. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  9997. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  9998. llama_batch u_batch = {
  9999. /* .n_tokens = */ (int32_t) n_tokens,
  10000. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  10001. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  10002. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  10003. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  10004. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  10005. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  10006. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  10007. /* .all_pos_1 = */ batch_all.all_pos_1,
  10008. /* .all_seq_id = */ batch_all.all_seq_id,
  10009. };
  10010. // count the outputs in this u_batch
  10011. {
  10012. int32_t n_outputs_new = 0;
  10013. if (u_batch.logits) {
  10014. for (uint32_t i = 0; i < n_tokens; i++) {
  10015. n_outputs_new += u_batch.logits[i] != 0;
  10016. }
  10017. } else if (n_outputs == n_tokens_all) {
  10018. n_outputs_new = n_tokens;
  10019. } else {
  10020. // keep last output only
  10021. if (cur_token + n_tokens >= n_tokens_all) {
  10022. n_outputs_new = 1;
  10023. }
  10024. }
  10025. // needs to happen before the graph is built
  10026. lctx.n_outputs = n_outputs_new;
  10027. }
  10028. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  10029. GGML_ASSERT(n_threads > 0);
  10030. // helpers for smoother batch API transition
  10031. // after deprecating the llama_eval calls, these will be removed
  10032. if (u_batch.pos == nullptr) {
  10033. pos.resize(n_tokens);
  10034. for (uint32_t i = 0; i < n_tokens; i++) {
  10035. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  10036. }
  10037. u_batch.pos = pos.data();
  10038. }
  10039. if (u_batch.seq_id == nullptr) {
  10040. n_seq_id.resize(n_tokens);
  10041. seq_id.resize(n_tokens);
  10042. seq_id_arr.resize(n_tokens);
  10043. for (uint32_t i = 0; i < n_tokens; i++) {
  10044. n_seq_id[i] = 1;
  10045. seq_id[i].resize(1);
  10046. seq_id[i][0] = u_batch.all_seq_id;
  10047. seq_id_arr[i] = seq_id[i].data();
  10048. }
  10049. u_batch.n_seq_id = n_seq_id.data();
  10050. u_batch.seq_id = seq_id_arr.data();
  10051. }
  10052. // non-causal masks do not use the KV cache
  10053. if (hparams.causal_attn) {
  10054. llama_kv_cache_update(&lctx);
  10055. // if we have enough unused cells before the current head ->
  10056. // better to start searching from the beginning of the cache, hoping to fill it
  10057. if (kv_self.head > kv_self.used + 2*n_tokens) {
  10058. kv_self.head = 0;
  10059. }
  10060. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  10061. return 1;
  10062. }
  10063. if (!kv_self.recurrent) {
  10064. // a heuristic, to avoid attending the full cache if it is not yet utilized
  10065. // after enough generations, the benefit from this heuristic disappears
  10066. // if we start defragmenting the cache, the benefit from this will be more important
  10067. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  10068. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  10069. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  10070. }
  10071. }
  10072. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  10073. ggml_backend_sched_reset(lctx.sched);
  10074. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  10075. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  10076. // the output is always the last tensor in the graph
  10077. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  10078. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  10079. if (lctx.n_outputs == 0) {
  10080. // no output
  10081. res = nullptr;
  10082. embd = nullptr;
  10083. } else if (!hparams.causal_attn) {
  10084. res = nullptr; // do not extract logits for embedding models such as BERT
  10085. // token or sequence embeddings
  10086. embd = gf->nodes[gf->n_nodes - 1];
  10087. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  10088. } else if (cparams.embeddings) {
  10089. // the embeddings could be in the second to last tensor, or any of the previous tensors
  10090. int i_embd = gf->n_nodes - 2;
  10091. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  10092. i_embd = gf->n_nodes - i;
  10093. if (i_embd < 0) { break; }
  10094. embd = gf->nodes[i_embd];
  10095. }
  10096. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  10097. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  10098. if (!cparams.causal_attn) {
  10099. res = nullptr; // do not extract logits when not needed
  10100. // skip computing logits
  10101. // TODO: is this safe?
  10102. gf->n_nodes = i_embd + 1;
  10103. }
  10104. } else {
  10105. embd = nullptr; // do not extract embeddings when not needed
  10106. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  10107. }
  10108. // 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);
  10109. // for big prompts, if BLAS is enabled, it is better to use only one thread
  10110. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  10111. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  10112. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  10113. // with the BLAS calls. need a better solution
  10114. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  10115. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  10116. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  10117. n_threads = std::min(4, n_threads);
  10118. }
  10119. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  10120. llama_set_inputs(lctx, u_batch);
  10121. llama_graph_compute(lctx, gf, n_threads);
  10122. // update the kv ring buffer
  10123. {
  10124. kv_self.head += n_tokens;
  10125. // Ensure kv cache head points to a valid index.
  10126. if (kv_self.head >= kv_self.size) {
  10127. kv_self.head = 0;
  10128. }
  10129. }
  10130. #ifdef GGML_PERF
  10131. // print timing information per ggml operation (for debugging purposes)
  10132. // requires GGML_PERF to be defined
  10133. ggml_graph_print(gf);
  10134. #endif
  10135. // plot the computation graph in dot format (for debugging purposes)
  10136. //if (n_past%100 == 0) {
  10137. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  10138. //}
  10139. // extract logits
  10140. if (res) {
  10141. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  10142. GGML_ASSERT(backend_res != nullptr);
  10143. GGML_ASSERT(lctx.logits != nullptr);
  10144. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  10145. const int32_t n_outputs_new = lctx.n_outputs;
  10146. if (n_outputs_new) {
  10147. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  10148. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  10149. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  10150. }
  10151. }
  10152. // extract embeddings
  10153. if (embd) {
  10154. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  10155. GGML_ASSERT(backend_embd != nullptr);
  10156. switch (cparams.pooling_type) {
  10157. case LLAMA_POOLING_TYPE_NONE:
  10158. {
  10159. // extract token embeddings
  10160. GGML_ASSERT(lctx.embd != nullptr);
  10161. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  10162. const int32_t n_outputs_new = lctx.n_outputs;
  10163. if (n_outputs_new) {
  10164. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  10165. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  10166. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  10167. }
  10168. } break;
  10169. case LLAMA_POOLING_TYPE_CLS:
  10170. case LLAMA_POOLING_TYPE_MEAN:
  10171. {
  10172. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  10173. // extract sequence embeddings
  10174. auto & embd_seq_out = lctx.embd_seq;
  10175. embd_seq_out.clear();
  10176. for (uint32_t i = 0; i < n_tokens; i++) {
  10177. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  10178. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  10179. continue;
  10180. }
  10181. embd_seq_out[seq_id].resize(n_embd);
  10182. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  10183. }
  10184. } break;
  10185. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  10186. {
  10187. GGML_ASSERT(false && "unknown pooling type");
  10188. } break;
  10189. }
  10190. }
  10191. n_outputs_prev += lctx.n_outputs;
  10192. }
  10193. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  10194. lctx.n_outputs = n_outputs;
  10195. // wait for the computation to finish (automatically done when obtaining the model output)
  10196. //llama_synchronize(&lctx);
  10197. // decide if we need to defrag the kv cache
  10198. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  10199. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  10200. // queue defragmentation for next llama_kv_cache_update
  10201. if (fragmentation > cparams.defrag_thold) {
  10202. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  10203. llama_kv_cache_defrag(kv_self);
  10204. }
  10205. }
  10206. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  10207. // overlap with device computation.
  10208. ggml_backend_sched_reset(lctx.sched);
  10209. return 0;
  10210. }
  10211. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  10212. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  10213. auto & kv_self = lctx.kv_self;
  10214. const auto & hparams = lctx.model.hparams;
  10215. const uint32_t n_layer = hparams.n_layer;
  10216. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  10217. const uint32_t n_used = kv_self.used;
  10218. assert(n_used <= n_kv);
  10219. //const int64_t t_start = ggml_time_us();
  10220. // number of cells moved
  10221. uint32_t n_moves = 0;
  10222. // each move requires 6*n_layer tensors (see build_defrag)
  10223. // - source view, destination view, copy operation
  10224. // - x2 for keys and values
  10225. //const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  10226. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  10227. const uint32_t max_moves = (LLAMA_MAX_NODES - 2*n_layer)/(6*n_layer);
  10228. // determine which KV cells to move where
  10229. //
  10230. // cell i moves to ids[i]
  10231. //
  10232. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  10233. //
  10234. std::vector<uint32_t> ids(n_kv, n_kv);
  10235. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  10236. const auto & cell0 = kv_self.cells[i0];
  10237. if (!cell0.is_empty()) {
  10238. ids[i0] = i0;
  10239. continue;
  10240. }
  10241. // found a hole - fill it with data from the end of the cache
  10242. uint32_t nh = 1;
  10243. // determine the size of the hole
  10244. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  10245. nh++;
  10246. }
  10247. uint32_t nf = 0;
  10248. uint32_t is = n_kv - 1;
  10249. // starting from the end, find nh non-empty cells
  10250. for (; is > i0; --is) {
  10251. const auto & cell1 = kv_self.cells[is];
  10252. if (cell1.is_empty() || ids[is] != n_kv) {
  10253. continue;
  10254. }
  10255. // non-empty cell which is not yet moved
  10256. nf++;
  10257. if (nf == nh) {
  10258. break;
  10259. }
  10260. }
  10261. // this can only happen if `n_used` is not accurate, which would be a bug
  10262. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  10263. nf = 0;
  10264. uint32_t i1 = is;
  10265. // are we moving a continuous block of memory?
  10266. bool cont = false;
  10267. // should we stop searching for the next move?
  10268. bool stop = false;
  10269. // go back and move the nf cells to the hole
  10270. for (; i1 < n_kv; ++i1) {
  10271. auto & cell1 = kv_self.cells[i1];
  10272. if (cell1.is_empty() || ids[i1] != n_kv) {
  10273. if (n_moves == max_moves) {
  10274. stop = true;
  10275. break;
  10276. }
  10277. cont = false;
  10278. continue;
  10279. }
  10280. // this cell goes to (i0 + nf)
  10281. ids[i1] = i0 + nf;
  10282. // move the cell meta data
  10283. kv_self.cells[i0 + nf] = cell1;
  10284. // clear the old cell and move the head there
  10285. cell1 = llama_kv_cell();
  10286. kv_self.head = n_used;
  10287. if (!cont) {
  10288. n_moves++;
  10289. cont = true;
  10290. }
  10291. nf++;
  10292. if (nf == nh) {
  10293. break;
  10294. }
  10295. }
  10296. if (stop || n_moves == max_moves) {
  10297. break;
  10298. }
  10299. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  10300. i0 += nh - 1;
  10301. }
  10302. if (n_moves == 0) {
  10303. return;
  10304. }
  10305. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  10306. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  10307. #if 0
  10308. // CPU defrag
  10309. //
  10310. // TODO: optimizations are possible:
  10311. // - multiple threads
  10312. // - avoid copying to the host memory when already there
  10313. //
  10314. // likely not worth the effort, as we have ggml_graph based defrag
  10315. //
  10316. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10317. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10318. const uint32_t kv_size = kv_self.size;
  10319. std::vector<uint8_t> buf_k;
  10320. std::vector<uint8_t> buf_v;
  10321. for (uint32_t il = 0; il < n_layer; ++il) {
  10322. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  10323. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  10324. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  10325. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  10326. buf_k.resize(k_size);
  10327. buf_v.resize(v_size);
  10328. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  10329. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  10330. // batch move [i, i+nm) to [id, id+nm)
  10331. // note: cells can move only to a lower index
  10332. for (uint32_t i = 0; i < n_kv; ++i) {
  10333. const uint32_t id = ids[i];
  10334. if (i == id || id == n_kv) {
  10335. continue;
  10336. }
  10337. uint32_t nm = 1;
  10338. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  10339. nm++;
  10340. }
  10341. // move keys
  10342. {
  10343. const int64_t os = i*k_size_row;
  10344. const int64_t od = id*k_size_row;
  10345. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  10346. }
  10347. // move values (note: they are transposed)
  10348. {
  10349. const int64_t os = i;
  10350. const int64_t od = id;
  10351. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  10352. 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);
  10353. }
  10354. }
  10355. i += nm - 1;
  10356. }
  10357. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  10358. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  10359. }
  10360. #else
  10361. // ggml_graph defrag
  10362. ggml_backend_sched_reset(lctx.sched);
  10363. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  10364. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  10365. #endif
  10366. //const int64_t t_end = ggml_time_us();
  10367. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  10368. }
  10369. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  10370. bool need_reserve = false;
  10371. // apply K-shift if needed
  10372. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  10373. {
  10374. ggml_backend_sched_reset(lctx.sched);
  10375. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  10376. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  10377. llama_set_k_shift(lctx);
  10378. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  10379. need_reserve = true;
  10380. }
  10381. {
  10382. auto & kv_self = lctx.kv_self;
  10383. kv_self.has_shift = false;
  10384. for (uint32_t i = 0; i < kv_self.size; ++i) {
  10385. kv_self.cells[i].delta = 0;
  10386. }
  10387. }
  10388. }
  10389. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  10390. {
  10391. ggml_backend_sched_reset(lctx.sched);
  10392. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  10393. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  10394. llama_set_s_copy(lctx);
  10395. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  10396. need_reserve = true;
  10397. }
  10398. {
  10399. auto & kv_self = lctx.kv_self;
  10400. kv_self.do_copy = false;
  10401. for (uint32_t i = 0; i < kv_self.size; ++i) {
  10402. kv_self.cells[i].src = i;
  10403. }
  10404. }
  10405. }
  10406. // defragment the KV cache if needed
  10407. if (lctx.kv_self.do_defrag) {
  10408. llama_kv_cache_defrag_internal(lctx);
  10409. need_reserve = true;
  10410. lctx.kv_self.do_defrag = false;
  10411. }
  10412. // reserve a worst case graph again
  10413. if (need_reserve) {
  10414. // TODO: extract to a function
  10415. // build worst-case graph
  10416. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  10417. int n_past = lctx.cparams.n_ctx - n_tokens;
  10418. 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
  10419. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10420. // initialize scheduler with the worst-case graph
  10421. ggml_backend_sched_reset(lctx.sched);
  10422. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  10423. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10424. }
  10425. }
  10426. }
  10427. //
  10428. // tokenizer
  10429. //
  10430. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  10431. return vocab.type;
  10432. }
  10433. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  10434. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  10435. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  10436. }
  10437. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  10438. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  10439. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  10440. }
  10441. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  10442. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  10443. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  10444. }
  10445. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  10446. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  10447. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  10448. }
  10449. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  10450. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  10451. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  10452. }
  10453. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  10454. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  10455. GGML_ASSERT(llama_is_byte_token(vocab, id));
  10456. const auto & token_data = vocab.id_to_token.at(id);
  10457. switch (llama_vocab_get_type(vocab)) {
  10458. case LLAMA_VOCAB_TYPE_SPM: {
  10459. auto buf = token_data.text.substr(3, 2);
  10460. return strtol(buf.c_str(), NULL, 16);
  10461. }
  10462. case LLAMA_VOCAB_TYPE_BPE: {
  10463. GGML_ASSERT(false);
  10464. return unicode_utf8_to_byte(token_data.text); // TODO: why is this here after GGML_ASSERT?
  10465. }
  10466. case LLAMA_VOCAB_TYPE_WPM: {
  10467. GGML_ASSERT(false);
  10468. }
  10469. default:
  10470. GGML_ASSERT(false);
  10471. }
  10472. }
  10473. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  10474. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  10475. static const char * hex = "0123456789ABCDEF";
  10476. switch (llama_vocab_get_type(vocab)) {
  10477. case LLAMA_VOCAB_TYPE_SPM: {
  10478. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  10479. auto token = vocab.token_to_id.find(buf);
  10480. if (token != vocab.token_to_id.end()) {
  10481. return (*token).second;
  10482. }
  10483. // Try to fall back to just the byte as a string
  10484. const char buf2[2] = { (char)ch, 0 };
  10485. return vocab.token_to_id.at(buf2);
  10486. }
  10487. case LLAMA_VOCAB_TYPE_WPM:
  10488. case LLAMA_VOCAB_TYPE_BPE: {
  10489. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  10490. }
  10491. default:
  10492. GGML_ASSERT(false);
  10493. }
  10494. }
  10495. static void llama_escape_whitespace(std::string & text) {
  10496. replace_all(text, " ", "\xe2\x96\x81");
  10497. }
  10498. static void llama_unescape_whitespace(std::string & word) {
  10499. replace_all(word, "\xe2\x96\x81", " ");
  10500. }
  10501. struct llm_symbol {
  10502. using index = int;
  10503. index prev;
  10504. index next;
  10505. const char * text;
  10506. size_t n;
  10507. };
  10508. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  10509. // SPM tokenizer
  10510. // original implementation:
  10511. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  10512. struct llm_bigram_spm {
  10513. struct comparator {
  10514. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  10515. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  10516. }
  10517. };
  10518. using queue_storage = std::vector<llm_bigram_spm>;
  10519. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  10520. llm_symbol::index left;
  10521. llm_symbol::index right;
  10522. float score;
  10523. size_t size;
  10524. };
  10525. struct llm_tokenizer_spm {
  10526. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  10527. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10528. // split string into utf8 chars
  10529. int index = 0;
  10530. size_t offs = 0;
  10531. while (offs < text.size()) {
  10532. llm_symbol sym;
  10533. size_t len = utf8_len(text[offs]);
  10534. sym.text = text.c_str() + offs;
  10535. sym.n = std::min(len, text.size() - offs);
  10536. offs += sym.n;
  10537. sym.prev = index - 1;
  10538. sym.next = offs == text.size() ? -1 : index + 1;
  10539. index++;
  10540. symbols.emplace_back(sym);
  10541. }
  10542. // seed the work queue with all possible 2-character tokens.
  10543. for (size_t i = 1; i < symbols.size(); ++i) {
  10544. try_add_bigram(i - 1, i);
  10545. }
  10546. // keep substituting the highest frequency pairs for as long as we can.
  10547. while (!work_queue.empty()) {
  10548. auto bigram = work_queue.top();
  10549. work_queue.pop();
  10550. auto & left_sym = symbols[bigram.left];
  10551. auto & right_sym = symbols[bigram.right];
  10552. // if one of the symbols already got merged, skip it.
  10553. if (left_sym.n == 0 || right_sym.n == 0 ||
  10554. left_sym.n + right_sym.n != bigram.size) {
  10555. continue;
  10556. }
  10557. // merge the right sym into the left one
  10558. left_sym.n += right_sym.n;
  10559. right_sym.n = 0;
  10560. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  10561. // remove the right sym from the chain
  10562. left_sym.next = right_sym.next;
  10563. if (right_sym.next >= 0) {
  10564. symbols[right_sym.next].prev = bigram.left;
  10565. }
  10566. // find more substitutions
  10567. try_add_bigram(left_sym.prev, bigram.left);
  10568. try_add_bigram(bigram.left, left_sym.next);
  10569. }
  10570. for (int i = 0; i != -1; i = symbols[i].next) {
  10571. auto & symbol = symbols[i];
  10572. resegment(symbol, output);
  10573. }
  10574. }
  10575. private:
  10576. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  10577. auto text = std::string(symbol.text, symbol.n);
  10578. auto token = vocab.token_to_id.find(text);
  10579. // Do we need to support is_unused?
  10580. if (token != vocab.token_to_id.end()) {
  10581. output.push_back((*token).second);
  10582. return;
  10583. }
  10584. const auto p = rev_merge.find(text);
  10585. if (p == rev_merge.end()) {
  10586. // output any symbols that did not form tokens as bytes.
  10587. output.reserve(output.size() + symbol.n);
  10588. for (int j = 0; j < (int)symbol.n; ++j) {
  10589. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  10590. output.push_back(token_id);
  10591. }
  10592. return;
  10593. }
  10594. resegment(symbols[p->second.first], output);
  10595. resegment(symbols[p->second.second], output);
  10596. }
  10597. void try_add_bigram(int left, int right) {
  10598. if (left == -1 || right == -1) {
  10599. return;
  10600. }
  10601. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  10602. auto token = vocab.token_to_id.find(text);
  10603. if (token == vocab.token_to_id.end()) {
  10604. return;
  10605. }
  10606. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  10607. return;
  10608. }
  10609. const auto & tok_data = vocab.id_to_token[(*token).second];
  10610. llm_bigram_spm bigram;
  10611. bigram.left = left;
  10612. bigram.right = right;
  10613. bigram.score = tok_data.score;
  10614. bigram.size = text.size();
  10615. work_queue.push(bigram);
  10616. // Do we need to support is_unused?
  10617. rev_merge[text] = std::make_pair(left, right);
  10618. }
  10619. const llama_vocab & vocab;
  10620. std::vector<llm_symbol> symbols;
  10621. llm_bigram_spm::queue work_queue;
  10622. std::map<std::string, std::pair<int, int>> rev_merge;
  10623. };
  10624. // BPE tokenizer
  10625. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  10626. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  10627. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  10628. struct llm_bigram_bpe {
  10629. struct comparator {
  10630. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  10631. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  10632. }
  10633. };
  10634. using queue_storage = std::vector<llm_bigram_bpe>;
  10635. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  10636. llm_symbol::index left;
  10637. llm_symbol::index right;
  10638. std::string text;
  10639. int rank;
  10640. size_t size;
  10641. };
  10642. struct llm_tokenizer_bpe {
  10643. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  10644. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10645. int final_prev_index = -1;
  10646. bool ignore_merges = false;
  10647. std::vector<std::string> word_collection;
  10648. switch (vocab.type) {
  10649. case LLAMA_VOCAB_TYPE_BPE:
  10650. switch (vocab.type_pre) {
  10651. case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
  10652. ignore_merges = true;
  10653. word_collection = unicode_regex_split(text, {
  10654. // original regex from tokenizer.json
  10655. //"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  10656. // adapted: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2080233989
  10657. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  10658. });
  10659. break;
  10660. case LLAMA_VOCAB_PRE_TYPE_DBRX:
  10661. case LLAMA_VOCAB_PRE_TYPE_SMAUG:
  10662. word_collection = unicode_regex_split(text, {
  10663. // same as llama3
  10664. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  10665. });
  10666. break;
  10667. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
  10668. word_collection = unicode_regex_split(text, {
  10669. "[\r\n]",
  10670. "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+",
  10671. "\\s?[!-/:-~!-/:-~‘-‟ -。]+",
  10672. "\\s+$",
  10673. "[一-龥ࠀ-一가-퟿]+",
  10674. "\\p{N}+",
  10675. });
  10676. break;
  10677. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
  10678. word_collection = unicode_regex_split(text, {
  10679. "[\r\n]",
  10680. "\\s?\\p{L}+",
  10681. "\\s?\\p{P}+",
  10682. "[一-龥ࠀ-一가-퟿]+",
  10683. "\\p{N}",
  10684. });
  10685. break;
  10686. case LLAMA_VOCAB_PRE_TYPE_FALCON:
  10687. word_collection = unicode_regex_split(text, {
  10688. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  10689. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10690. "[0-9][0-9][0-9]",
  10691. });
  10692. break;
  10693. case LLAMA_VOCAB_PRE_TYPE_MPT:
  10694. // TODO: MPT pre-tokenization regexes are unknown
  10695. // the following are close, but not exact. run the following:
  10696. // ./bin/test-tokenizer-0 ../models/ggml-vocab-mpt.gguf
  10697. GGML_ASSERT("MPT pre-tokenization regexes are unknown - fixes needed");
  10698. word_collection = unicode_regex_split(text, {
  10699. "\\s?\\p{L}+",
  10700. "\\s?\\p{P}+",
  10701. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10702. });
  10703. break;
  10704. case LLAMA_VOCAB_PRE_TYPE_STARCODER:
  10705. case LLAMA_VOCAB_PRE_TYPE_REFACT:
  10706. case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
  10707. word_collection = unicode_regex_split(text, {
  10708. "\\p{N}",
  10709. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10710. });
  10711. break;
  10712. case LLAMA_VOCAB_PRE_TYPE_GPT2:
  10713. case LLAMA_VOCAB_PRE_TYPE_OLMO:
  10714. word_collection = unicode_regex_split(text, {
  10715. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10716. });
  10717. break;
  10718. case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
  10719. case LLAMA_VOCAB_PRE_TYPE_QWEN2:
  10720. word_collection = unicode_regex_split(text, {
  10721. // original regex from tokenizer.json
  10722. // "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
  10723. "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
  10724. });
  10725. break;
  10726. default:
  10727. // default regex for BPE tokenization pre-processing
  10728. word_collection = unicode_regex_split(text, {
  10729. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  10730. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10731. "\\p{N}+",
  10732. "[0-9][0-9][0-9]",
  10733. });
  10734. break;
  10735. }
  10736. break;
  10737. default:
  10738. GGML_ASSERT(false);
  10739. break;
  10740. }
  10741. symbols_final.clear();
  10742. for (auto & word : word_collection) {
  10743. work_queue = llm_bigram_bpe::queue();
  10744. symbols.clear();
  10745. int index = 0;
  10746. size_t offset = 0;
  10747. if (ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
  10748. symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
  10749. offset = word.size();
  10750. }
  10751. while (offset < word.size()) {
  10752. llm_symbol sym;
  10753. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  10754. sym.text = word.c_str() + offset;
  10755. sym.n = char_len;
  10756. offset += sym.n;
  10757. sym.prev = index - 1;
  10758. sym.next = offset == word.size() ? -1 : index + 1;
  10759. index++;
  10760. symbols.emplace_back(sym);
  10761. }
  10762. for (size_t i = 1; i < symbols.size(); ++i) {
  10763. add_new_bigram(i - 1, i);
  10764. }
  10765. // build token(s)
  10766. while (!work_queue.empty()) {
  10767. auto bigram = work_queue.top();
  10768. work_queue.pop();
  10769. auto & left_symbol = symbols[bigram.left];
  10770. auto & right_symbol = symbols[bigram.right];
  10771. if (left_symbol.n == 0 || right_symbol.n == 0) {
  10772. continue;
  10773. }
  10774. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  10775. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  10776. if (left_token + right_token != bigram.text) {
  10777. continue; // Skip this bigram if it's outdated
  10778. }
  10779. // merge the right sym into the left one
  10780. left_symbol.n += right_symbol.n;
  10781. right_symbol.n = 0;
  10782. // remove the right sym from the chain
  10783. left_symbol.next = right_symbol.next;
  10784. if (right_symbol.next >= 0) {
  10785. symbols[right_symbol.next].prev = bigram.left;
  10786. }
  10787. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  10788. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  10789. }
  10790. // add the finished tokens to the final list keeping correct order for next and prev
  10791. for (auto & sym : symbols) {
  10792. if (sym.n > 0) {
  10793. sym.prev = final_prev_index;
  10794. sym.next = -1;
  10795. if (final_prev_index != -1) {
  10796. symbols_final[final_prev_index].next = symbols_final.size();
  10797. }
  10798. symbols_final.emplace_back(sym);
  10799. final_prev_index = symbols_final.size() - 1;
  10800. }
  10801. }
  10802. }
  10803. symbols = symbols_final;
  10804. if (!symbols.empty()) {
  10805. for (int i = 0; i != -1; i = symbols[i].next) {
  10806. auto & symbol = symbols[i];
  10807. if (symbol.n == 0) {
  10808. continue;
  10809. }
  10810. const std::string str = std::string(symbol.text, symbol.n);
  10811. const auto token = vocab.token_to_id.find(str);
  10812. if (token == vocab.token_to_id.end()) {
  10813. for (auto j = str.begin(); j != str.end(); ++j) {
  10814. std::string byte_str(1, *j);
  10815. auto token_multibyte = vocab.token_to_id.find(byte_str);
  10816. if (token_multibyte == vocab.token_to_id.end()) {
  10817. throw std::runtime_error("ERROR: byte not found in vocab");
  10818. }
  10819. output.push_back((*token_multibyte).second);
  10820. }
  10821. } else {
  10822. output.push_back((*token).second);
  10823. }
  10824. }
  10825. }
  10826. }
  10827. private:
  10828. void add_new_bigram(int left, int right) {
  10829. if (left == -1 || right == -1) {
  10830. return;
  10831. }
  10832. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  10833. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  10834. int rank_found = -1;
  10835. rank_found = vocab.find_bpe_rank(left_token, right_token);
  10836. if (rank_found < 0) {
  10837. return;
  10838. }
  10839. llm_bigram_bpe bigram;
  10840. bigram.left = left;
  10841. bigram.right = right;
  10842. bigram.text = left_token + right_token;
  10843. bigram.size = left_token.size() + right_token.size();
  10844. bigram.rank = rank_found;
  10845. work_queue.push(bigram);
  10846. }
  10847. const llama_vocab & vocab;
  10848. std::vector<llm_symbol> symbols;
  10849. std::vector<llm_symbol> symbols_final;
  10850. llm_bigram_bpe::queue work_queue;
  10851. };
  10852. struct llm_tokenizer_wpm {
  10853. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  10854. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10855. const auto & token_map = vocab.token_to_id;
  10856. // normalize and split by whitespace
  10857. std::vector<std::string> words = preprocess(text);
  10858. // bos token prepended already
  10859. // find the longest tokens that form the words
  10860. for (const std::string &word : words) {
  10861. // skip empty words
  10862. if (word.size() == 0) {
  10863. continue;
  10864. }
  10865. // prepend phantom space
  10866. const std::string word1 = "\xe2\x96\x81" + word;
  10867. const int n = word1.size();
  10868. const size_t current_tokens = output.size();
  10869. // we're at the start of a new word
  10870. // move through character position in word
  10871. for (int i = 0; i < n; ++i) {
  10872. // loop through possible match length
  10873. bool match = false;
  10874. for (int j = n; j > i; j--) {
  10875. auto it = token_map.find(word1.substr(i, j - i));
  10876. if (it != token_map.end()) {
  10877. output.push_back(it->second);
  10878. match = true;
  10879. i = j - 1;
  10880. break;
  10881. }
  10882. }
  10883. if (!match) { // discard all
  10884. output.resize(current_tokens);
  10885. break; // and discard next tokens
  10886. }
  10887. }
  10888. // we didn't find any matches for this word
  10889. if (current_tokens == output.size()) {
  10890. output.push_back(vocab.special_unk_id);
  10891. }
  10892. }
  10893. }
  10894. std::vector<std::string> preprocess(const std::string & text) {
  10895. const std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  10896. std::vector<std::string> words(1, "");
  10897. for (const char32_t cpt : cpts_nfd) {
  10898. const auto flags = unicode_cpt_flags(cpt);
  10899. if (flags.is_whitespace) {
  10900. if (words.back().size()) { // finish previous word if any
  10901. words.emplace_back();
  10902. }
  10903. continue;
  10904. }
  10905. assert (!flags.is_separator);
  10906. if (cpt == 0 || cpt == 0xFFFD || flags.is_control) {
  10907. continue;
  10908. }
  10909. const std::string s = unicode_cpt_to_utf8(unicode_tolower(cpt));
  10910. if (flags.is_punctuation || ( cpt < 0x7F && flags.is_symbol ) || is_chinese_char(cpt)) {
  10911. if (words.back().size()) { // finish previous word if any
  10912. words.emplace_back();
  10913. }
  10914. words.back() = s; // single char word
  10915. words.emplace_back(); // start a new word
  10916. } else {
  10917. words.back() += s; // append char to word
  10918. }
  10919. }
  10920. if (!words.back().size()) {
  10921. words.pop_back();
  10922. }
  10923. return words;
  10924. }
  10925. static bool is_chinese_char(uint32_t cpt) {
  10926. return
  10927. (cpt >= 0x04E00 && cpt <= 0x09FFF) ||
  10928. (cpt >= 0x03400 && cpt <= 0x04DBF) ||
  10929. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  10930. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  10931. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  10932. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  10933. (cpt >= 0x0F900 && cpt <= 0x0FAFF) ||
  10934. (cpt >= 0x2F800 && cpt <= 0x2FA1F);
  10935. //(cpt >= 0x3000 && cpt <= 0x303F) ||
  10936. //(cpt >= 0xFF00 && cpt <= 0xFFEF);
  10937. }
  10938. const llama_vocab & vocab;
  10939. };
  10940. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  10941. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  10942. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  10943. } FRAGMENT_BUFFER_VARIANT_TYPE;
  10944. struct fragment_buffer_variant {
  10945. fragment_buffer_variant(llama_vocab::id _token)
  10946. :
  10947. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  10948. token(_token),
  10949. raw_text(_dummy),
  10950. offset(0),
  10951. length(0) {}
  10952. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  10953. :
  10954. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  10955. token((llama_vocab::id) - 1),
  10956. raw_text(_raw_text),
  10957. offset(_offset),
  10958. length(_length){
  10959. GGML_ASSERT(_offset >= 0);
  10960. GGML_ASSERT(_length >= 1);
  10961. GGML_ASSERT(offset + length <= raw_text.length());
  10962. }
  10963. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  10964. const llama_vocab::id token;
  10965. const std::string _dummy;
  10966. const std::string & raw_text;
  10967. const uint64_t offset;
  10968. const uint64_t length;
  10969. };
  10970. // #define PRETOKENIZERDEBUG
  10971. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  10972. // for each special token
  10973. for (const llama_vocab::id special_id : vocab.cache_special_tokens) {
  10974. const auto & special_token = vocab.id_to_token[special_id].text;
  10975. // for each text fragment
  10976. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  10977. while (it != buffer.end()) {
  10978. auto & fragment = (*it);
  10979. // if a fragment is text ( not yet processed )
  10980. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  10981. auto & raw_text = fragment.raw_text;
  10982. auto raw_text_base_offset = fragment.offset;
  10983. auto raw_text_base_length = fragment.length;
  10984. // loop over the text
  10985. while (true) {
  10986. // find the first occurrence of a given special token in this fragment
  10987. // passing offset argument only limit the "search area" but match coordinates
  10988. // are still relative to the source full raw_text
  10989. auto match = raw_text.find(special_token, raw_text_base_offset);
  10990. // no occurrences found, stop processing this fragment for a given special token
  10991. if (match == std::string::npos) break;
  10992. // check if match is within bounds of offset <-> length
  10993. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  10994. #ifdef PRETOKENIZERDEBUG
  10995. LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  10996. #endif
  10997. auto source = std::distance(buffer.begin(), it);
  10998. // if match is further than base offset
  10999. // then we have some text to the left of it
  11000. if (match > raw_text_base_offset) {
  11001. // left
  11002. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  11003. const int64_t left_reminder_length = match - raw_text_base_offset;
  11004. buffer.emplace_after(it, raw_text, left_reminder_offset, left_reminder_length);
  11005. #ifdef PRETOKENIZERDEBUG
  11006. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  11007. #endif
  11008. it++;
  11009. }
  11010. // special token
  11011. buffer.emplace_after(it, special_id);
  11012. it++;
  11013. // right
  11014. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  11015. const int64_t right_reminder_offset = match + special_token.length();
  11016. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  11017. buffer.emplace_after(it, raw_text, right_reminder_offset, right_reminder_length);
  11018. #ifdef PRETOKENIZERDEBUG
  11019. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  11020. #endif
  11021. it++;
  11022. if (source == 0) {
  11023. buffer.erase_after(buffer.before_begin());
  11024. } else {
  11025. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  11026. }
  11027. // repeat for the right side
  11028. raw_text_base_offset = right_reminder_offset;
  11029. raw_text_base_length = right_reminder_length;
  11030. #ifdef PRETOKENIZERDEBUG
  11031. LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  11032. #endif
  11033. } else {
  11034. if (source == 0) {
  11035. buffer.erase_after(buffer.before_begin());
  11036. } else {
  11037. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  11038. }
  11039. break;
  11040. }
  11041. }
  11042. }
  11043. it++;
  11044. }
  11045. }
  11046. }
  11047. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special) {
  11048. std::vector<llama_vocab::id> output;
  11049. std::forward_list<fragment_buffer_variant> fragment_buffer;
  11050. if (!raw_text.empty()) {
  11051. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  11052. if (parse_special) tokenizer_st_partition(vocab, fragment_buffer);
  11053. }
  11054. switch (vocab.type) {
  11055. case LLAMA_VOCAB_TYPE_SPM:
  11056. {
  11057. // OG tokenizer behavior:
  11058. //
  11059. // tokenizer.encode('', add_special_tokens=True) returns [1]
  11060. // tokenizer.encode('', add_special_tokens=False) returns []
  11061. static const bool rtrim = true; //TODO: as param
  11062. bool is_prev_special = false;
  11063. bool special_token_rtrim = false;
  11064. if (add_special && vocab.special_add_bos != 0) {
  11065. GGML_ASSERT(vocab.special_bos_id != -1);
  11066. output.push_back(vocab.special_bos_id);
  11067. is_prev_special = true;
  11068. }
  11069. for (const auto & fragment : fragment_buffer) {
  11070. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  11071. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  11072. // TODO: It's likely possible to get rid of this string copy entirely
  11073. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  11074. // and passing 'add space prefix' as bool argument
  11075. //
  11076. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  11077. if (special_token_rtrim) {
  11078. size_t num_whitespaces = 0;
  11079. while (isspace(raw_text[num_whitespaces])) {
  11080. num_whitespaces++;
  11081. }
  11082. if (num_whitespaces == raw_text.size()) {
  11083. continue; // skip if all whitespaces
  11084. }
  11085. raw_text = raw_text.substr(num_whitespaces);
  11086. }
  11087. if (vocab.add_space_prefix) {
  11088. if (!output.size() || is_prev_special) { // prefix with space if first token
  11089. raw_text = " " + raw_text;
  11090. }
  11091. }
  11092. #ifdef PRETOKENIZERDEBUG
  11093. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  11094. #endif
  11095. llm_tokenizer_spm tokenizer(vocab);
  11096. llama_escape_whitespace(raw_text);
  11097. tokenizer.tokenize(raw_text, output);
  11098. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  11099. output.push_back(fragment.token);
  11100. is_prev_special = true;
  11101. // phi-3 special tokens without rtrim, works fine for llama-spm too
  11102. special_token_rtrim = rtrim
  11103. && fragment.token != vocab.special_bos_id
  11104. && fragment.token != vocab.special_unk_id
  11105. && fragment.token != vocab.special_eos_id;
  11106. }
  11107. }
  11108. if (add_special && vocab.special_add_bos != 0 && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  11109. LLAMA_LOG_WARN(
  11110. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  11111. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  11112. "Are you sure this is what you want?\n", __FUNCTION__);
  11113. }
  11114. if (add_special && vocab.special_add_eos == 1) {
  11115. GGML_ASSERT(vocab.special_eos_id != -1);
  11116. output.push_back(vocab.special_eos_id);
  11117. }
  11118. } break;
  11119. case LLAMA_VOCAB_TYPE_BPE:
  11120. {
  11121. if (add_special && vocab.special_add_bos != 0) {
  11122. GGML_ASSERT(vocab.special_bos_id != -1);
  11123. output.push_back(vocab.special_bos_id);
  11124. }
  11125. for (const auto & fragment : fragment_buffer) {
  11126. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  11127. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  11128. #ifdef PRETOKENIZERDEBUG
  11129. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  11130. #endif
  11131. llm_tokenizer_bpe tokenizer(vocab);
  11132. tokenizer.tokenize(raw_text, output);
  11133. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  11134. output.push_back(fragment.token);
  11135. }
  11136. }
  11137. if (add_special && vocab.special_add_bos != 0 && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  11138. LLAMA_LOG_WARN(
  11139. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  11140. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  11141. "Are you sure this is what you want?\n", __FUNCTION__);
  11142. }
  11143. if (add_special && vocab.special_add_eos == 1) {
  11144. GGML_ASSERT(vocab.special_add_eos != -1);
  11145. output.push_back(vocab.special_eos_id);
  11146. }
  11147. } break;
  11148. case LLAMA_VOCAB_TYPE_WPM:
  11149. {
  11150. if (add_special) {
  11151. GGML_ASSERT(vocab.special_cls_id != -1);
  11152. output.push_back(vocab.special_cls_id);
  11153. }
  11154. for (const auto & fragment : fragment_buffer) {
  11155. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  11156. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  11157. #ifdef PRETOKENIZERDEBUG
  11158. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  11159. #endif
  11160. llm_tokenizer_wpm tokenizer(vocab);
  11161. tokenizer.tokenize(raw_text, output);
  11162. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  11163. output.push_back(fragment.token);
  11164. }
  11165. }
  11166. if (add_special) {
  11167. GGML_ASSERT(vocab.special_sep_id != -1);
  11168. output.push_back(vocab.special_sep_id);
  11169. }
  11170. } break;
  11171. case LLAMA_VOCAB_TYPE_NONE:
  11172. GGML_ASSERT(false);
  11173. }
  11174. return output;
  11175. }
  11176. //
  11177. // grammar - internal
  11178. //
  11179. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  11180. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  11181. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  11182. const std::string & src,
  11183. llama_partial_utf8 partial_start) {
  11184. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  11185. const char * pos = src.c_str();
  11186. std::vector<uint32_t> code_points;
  11187. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  11188. code_points.reserve(src.size() + 1);
  11189. uint32_t value = partial_start.value;
  11190. int n_remain = partial_start.n_remain;
  11191. // continue previous decode, if applicable
  11192. while (*pos != 0 && n_remain > 0) {
  11193. uint8_t next_byte = static_cast<uint8_t>(*pos);
  11194. if ((next_byte >> 6) != 2) {
  11195. // invalid sequence, abort
  11196. code_points.push_back(0);
  11197. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  11198. }
  11199. value = (value << 6) + (next_byte & 0x3F);
  11200. ++pos;
  11201. --n_remain;
  11202. }
  11203. if (partial_start.n_remain > 0 && n_remain == 0) {
  11204. code_points.push_back(value);
  11205. }
  11206. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  11207. while (*pos != 0) {
  11208. uint8_t first_byte = static_cast<uint8_t>(*pos);
  11209. uint8_t highbits = first_byte >> 4;
  11210. n_remain = lookup[highbits] - 1;
  11211. if (n_remain < 0) {
  11212. // invalid sequence, abort
  11213. code_points.clear();
  11214. code_points.push_back(0);
  11215. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  11216. }
  11217. uint8_t mask = (1 << (7 - n_remain)) - 1;
  11218. value = first_byte & mask;
  11219. ++pos;
  11220. while (*pos != 0 && n_remain > 0) {
  11221. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  11222. ++pos;
  11223. --n_remain;
  11224. }
  11225. if (n_remain == 0) {
  11226. code_points.push_back(value);
  11227. }
  11228. }
  11229. code_points.push_back(0);
  11230. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  11231. }
  11232. // returns true iff pos points to the end of one of the definitions of a rule
  11233. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  11234. switch (pos->type) {
  11235. case LLAMA_GRETYPE_END: return true; // NOLINT
  11236. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  11237. default: return false;
  11238. }
  11239. }
  11240. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  11241. // asserts that pos is pointing to a char range element
  11242. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  11243. const llama_grammar_element * pos,
  11244. const uint32_t chr) {
  11245. bool found = false;
  11246. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  11247. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  11248. do {
  11249. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  11250. // inclusive range, e.g. [a-z]
  11251. found = found || (pos->value <= chr && chr <= pos[1].value);
  11252. pos += 2;
  11253. } else {
  11254. // exact char match, e.g. [a] or "a"
  11255. found = found || pos->value == chr;
  11256. pos += 1;
  11257. }
  11258. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  11259. return std::make_pair(found == is_positive_char, pos);
  11260. }
  11261. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  11262. // range at pos (regular or inverse range)
  11263. // asserts that pos is pointing to a char range element
  11264. static bool llama_grammar_match_partial_char(
  11265. const llama_grammar_element * pos,
  11266. const llama_partial_utf8 partial_utf8) {
  11267. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  11268. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  11269. uint32_t partial_value = partial_utf8.value;
  11270. int n_remain = partial_utf8.n_remain;
  11271. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  11272. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  11273. return false;
  11274. }
  11275. // range of possible code points this partial UTF-8 sequence could complete to
  11276. uint32_t low = partial_value << (n_remain * 6);
  11277. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  11278. if (low == 0) {
  11279. if (n_remain == 2) {
  11280. low = 1 << 11;
  11281. } else if (n_remain == 3) {
  11282. low = 1 << 16;
  11283. }
  11284. }
  11285. do {
  11286. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  11287. // inclusive range, e.g. [a-z]
  11288. if (pos->value <= high && low <= pos[1].value) {
  11289. return is_positive_char;
  11290. }
  11291. pos += 2;
  11292. } else {
  11293. // exact char match, e.g. [a] or "a"
  11294. if (low <= pos->value && pos->value <= high) {
  11295. return is_positive_char;
  11296. }
  11297. pos += 1;
  11298. }
  11299. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  11300. return !is_positive_char;
  11301. }
  11302. // transforms a grammar pushdown stack into N possible stacks, all ending
  11303. // at a character range (terminal element)
  11304. static void llama_grammar_advance_stack(
  11305. const std::vector<std::vector<llama_grammar_element>> & rules,
  11306. const std::vector<const llama_grammar_element *> & stack,
  11307. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  11308. if (stack.empty()) {
  11309. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  11310. new_stacks.emplace_back(stack);
  11311. }
  11312. return;
  11313. }
  11314. const llama_grammar_element * pos = stack.back();
  11315. switch (pos->type) {
  11316. case LLAMA_GRETYPE_RULE_REF: {
  11317. const size_t rule_id = static_cast<size_t>(pos->value);
  11318. const llama_grammar_element * subpos = rules[rule_id].data();
  11319. do {
  11320. // init new stack without the top (pos)
  11321. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  11322. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  11323. // if this rule ref is followed by another element, add that to stack
  11324. new_stack.push_back(pos + 1);
  11325. }
  11326. if (!llama_grammar_is_end_of_sequence(subpos)) {
  11327. // if alternate is nonempty, add to stack
  11328. new_stack.push_back(subpos);
  11329. }
  11330. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  11331. while (!llama_grammar_is_end_of_sequence(subpos)) {
  11332. // scan to end of alternate def
  11333. subpos++;
  11334. }
  11335. if (subpos->type == LLAMA_GRETYPE_ALT) {
  11336. // there's another alternate def of this rule to process
  11337. subpos++;
  11338. } else {
  11339. break;
  11340. }
  11341. } while (true);
  11342. break;
  11343. }
  11344. case LLAMA_GRETYPE_CHAR:
  11345. case LLAMA_GRETYPE_CHAR_NOT:
  11346. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  11347. // only add the stack if it's not a duplicate of one we already have
  11348. new_stacks.emplace_back(stack);
  11349. }
  11350. break;
  11351. default:
  11352. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  11353. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  11354. // those
  11355. GGML_ASSERT(false);
  11356. }
  11357. }
  11358. // takes a set of possible pushdown stacks on a grammar, which are required to
  11359. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  11360. // produces the N possible stacks if the given char is accepted at those
  11361. // positions
  11362. void llama_grammar_accept(
  11363. const std::vector<std::vector<llama_grammar_element>> & rules,
  11364. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  11365. const uint32_t chr,
  11366. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  11367. new_stacks.clear();
  11368. for (const auto & stack : stacks) {
  11369. if (stack.empty()) {
  11370. continue;
  11371. }
  11372. auto match = llama_grammar_match_char(stack.back(), chr);
  11373. if (match.first) {
  11374. const llama_grammar_element * pos = match.second;
  11375. // update top of stack to next element, if any
  11376. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  11377. if (!llama_grammar_is_end_of_sequence(pos)) {
  11378. new_stack.push_back(pos);
  11379. }
  11380. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  11381. }
  11382. }
  11383. }
  11384. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  11385. const std::vector<std::vector<llama_grammar_element>> & rules,
  11386. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  11387. const std::vector<llama_grammar_candidate> & candidates);
  11388. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  11389. const std::vector<std::vector<llama_grammar_element>> & rules,
  11390. const std::vector<const llama_grammar_element *> & stack,
  11391. const std::vector<llama_grammar_candidate> & candidates) {
  11392. std::vector<llama_grammar_candidate> rejects;
  11393. rejects.reserve(candidates.size());
  11394. if (stack.empty()) {
  11395. for (const auto & tok : candidates) {
  11396. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  11397. rejects.push_back(tok);
  11398. }
  11399. }
  11400. return rejects;
  11401. }
  11402. const llama_grammar_element * stack_pos = stack.back();
  11403. std::vector<llama_grammar_candidate> next_candidates;
  11404. next_candidates.reserve(candidates.size());
  11405. for (const auto & tok : candidates) {
  11406. if (*tok.code_points == 0) {
  11407. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  11408. // that cannot satisfy this position in grammar
  11409. if (tok.partial_utf8.n_remain != 0 &&
  11410. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  11411. rejects.push_back(tok);
  11412. }
  11413. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  11414. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  11415. } else {
  11416. rejects.push_back(tok);
  11417. }
  11418. }
  11419. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  11420. // update top of stack to next element, if any
  11421. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  11422. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  11423. stack_after.push_back(stack_pos_after);
  11424. }
  11425. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  11426. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  11427. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  11428. for (const auto & tok : next_rejects) {
  11429. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  11430. }
  11431. return rejects;
  11432. }
  11433. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  11434. const std::vector<std::vector<llama_grammar_element>> & rules,
  11435. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  11436. const std::vector<llama_grammar_candidate> & candidates) {
  11437. GGML_ASSERT(!stacks.empty()); // REVIEW
  11438. if (candidates.empty()) {
  11439. return std::vector<llama_grammar_candidate>();
  11440. }
  11441. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  11442. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  11443. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  11444. }
  11445. return rejects;
  11446. }
  11447. static bool llama_grammar_detect_left_recursion(
  11448. const std::vector<std::vector<llama_grammar_element>> & rules,
  11449. size_t rule_index,
  11450. std::vector<bool> * rules_visited,
  11451. std::vector<bool> * rules_in_progress,
  11452. std::vector<bool> * rules_may_be_empty) {
  11453. if ((*rules_in_progress)[rule_index]) {
  11454. return true;
  11455. }
  11456. (*rules_in_progress)[rule_index] = true;
  11457. const std::vector<llama_grammar_element> & rule = rules[rule_index];
  11458. // First check if the rule might produce the empty string. This could be done combined with the second
  11459. // step but it's more readable as two steps.
  11460. bool at_rule_start = true;
  11461. for (size_t i = 0; i < rule.size(); i++) {
  11462. if (llama_grammar_is_end_of_sequence(&rule[i])) {
  11463. if (at_rule_start) {
  11464. (*rules_may_be_empty)[rule_index] = true;
  11465. break;
  11466. }
  11467. at_rule_start = true;
  11468. } else {
  11469. at_rule_start = false;
  11470. }
  11471. }
  11472. // Second, recurse into leftmost nonterminals (or next-leftmost as long as the previous nonterminal may
  11473. // be empty)
  11474. bool recurse_into_nonterminal = true;
  11475. for (size_t i = 0; i < rule.size(); i++) {
  11476. if (rule[i].type == LLAMA_GRETYPE_RULE_REF && recurse_into_nonterminal) {
  11477. if (llama_grammar_detect_left_recursion(rules, (size_t)rule[i].value, rules_visited, rules_in_progress, rules_may_be_empty)) {
  11478. return true;
  11479. }
  11480. if (!((*rules_may_be_empty)[(size_t)rule[i].value])) {
  11481. recurse_into_nonterminal = false;
  11482. }
  11483. } else if (llama_grammar_is_end_of_sequence(&rule[i])) {
  11484. recurse_into_nonterminal = true;
  11485. } else {
  11486. recurse_into_nonterminal = false;
  11487. }
  11488. }
  11489. (*rules_in_progress)[rule_index] = false;
  11490. (*rules_visited)[rule_index] = true;
  11491. return false;
  11492. }
  11493. //
  11494. // grammar - external
  11495. //
  11496. struct llama_grammar * llama_grammar_init(
  11497. const llama_grammar_element ** rules,
  11498. size_t n_rules,
  11499. size_t start_rule_index) {
  11500. const llama_grammar_element * pos;
  11501. // copy rule definitions into vectors
  11502. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  11503. for (size_t i = 0; i < n_rules; i++) {
  11504. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  11505. vec_rules[i].push_back(*pos);
  11506. }
  11507. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  11508. }
  11509. // Check for left recursion
  11510. std::vector<bool> rules_visited(n_rules);
  11511. std::vector<bool> rules_in_progress(n_rules);
  11512. std::vector<bool> rules_may_be_empty(n_rules);
  11513. for (size_t i = 0; i < n_rules; i++) {
  11514. if (rules_visited[i]) {
  11515. continue;
  11516. }
  11517. if (llama_grammar_detect_left_recursion(vec_rules, i, &rules_visited, &rules_in_progress, &rules_may_be_empty)) {
  11518. throw std::runtime_error(format("unsupported grammar, left recursion detected for nonterminal at index %zu", i));
  11519. }
  11520. }
  11521. // loop over alternates of start rule to build initial stacks
  11522. std::vector<std::vector<const llama_grammar_element *>> stacks;
  11523. pos = vec_rules[start_rule_index].data();
  11524. do {
  11525. std::vector<const llama_grammar_element *> stack;
  11526. if (!llama_grammar_is_end_of_sequence(pos)) {
  11527. // if alternate is nonempty, add to stack
  11528. stack.push_back(pos);
  11529. }
  11530. llama_grammar_advance_stack(vec_rules, stack, stacks);
  11531. while (!llama_grammar_is_end_of_sequence(pos)) {
  11532. // scan to end of alternate def
  11533. pos++;
  11534. }
  11535. if (pos->type == LLAMA_GRETYPE_ALT) {
  11536. // there's another alternate def of this rule to process
  11537. pos++;
  11538. } else {
  11539. break;
  11540. }
  11541. } while (true);
  11542. // Important: vec_rules has to be moved here, not copied, because stacks contains
  11543. // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar
  11544. // then the pointers would be invalidated when the local vec_rules goes out of scope.
  11545. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  11546. }
  11547. void llama_grammar_free(struct llama_grammar * grammar) {
  11548. delete grammar;
  11549. }
  11550. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  11551. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  11552. // redirect elements in stacks to point to new rules
  11553. for (size_t is = 0; is < result->stacks.size(); is++) {
  11554. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  11555. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  11556. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  11557. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  11558. result->stacks[is][ie] = &result->rules[ir0][ir1];
  11559. }
  11560. }
  11561. }
  11562. }
  11563. }
  11564. return result;
  11565. }
  11566. //
  11567. // sampling
  11568. //
  11569. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  11570. if (seed == LLAMA_DEFAULT_SEED) {
  11571. seed = time(NULL);
  11572. }
  11573. ctx->rng.seed(seed);
  11574. }
  11575. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  11576. GGML_ASSERT(candidates->size > 0);
  11577. const int64_t t_start_sample_us = ggml_time_us();
  11578. // Sort the logits in descending order
  11579. if (!candidates->sorted) {
  11580. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  11581. return a.logit > b.logit;
  11582. });
  11583. candidates->sorted = true;
  11584. }
  11585. float max_l = candidates->data[0].logit;
  11586. float cum_sum = 0.0f;
  11587. for (size_t i = 0; i < candidates->size; ++i) {
  11588. float p = expf(candidates->data[i].logit - max_l);
  11589. candidates->data[i].p = p;
  11590. cum_sum += p;
  11591. }
  11592. for (size_t i = 0; i < candidates->size; ++i) {
  11593. candidates->data[i].p /= cum_sum;
  11594. }
  11595. if (ctx) {
  11596. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11597. }
  11598. }
  11599. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  11600. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  11601. // if (k >= (int32_t)candidates->size) {
  11602. // return;
  11603. // }
  11604. const int64_t t_start_sample_us = ggml_time_us();
  11605. if (k <= 0) {
  11606. k = candidates->size;
  11607. }
  11608. k = std::max(k, (int) min_keep);
  11609. k = std::min(k, (int) candidates->size);
  11610. // Sort scores in descending order
  11611. if (!candidates->sorted) {
  11612. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  11613. return a.logit > b.logit;
  11614. };
  11615. if (k <= 128) {
  11616. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  11617. } else {
  11618. constexpr int nbuckets = 128;
  11619. constexpr float bucket_low = -10.0f;
  11620. constexpr float bucket_high = 10.0f;
  11621. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  11622. constexpr float bucker_inter = -bucket_low * bucket_scale;
  11623. std::vector<int> bucket_idx(candidates->size);
  11624. std::vector<int> histo(nbuckets, 0);
  11625. for (int i = 0; i < (int)candidates->size; ++i) {
  11626. const float val = candidates->data[i].logit;
  11627. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  11628. ib = std::max(0, std::min(nbuckets-1, ib));
  11629. bucket_idx[i] = ib;
  11630. ++histo[ib];
  11631. }
  11632. int nhave = 0;
  11633. int ib = nbuckets - 1;
  11634. for ( ; ib >= 0; --ib) {
  11635. nhave += histo[ib];
  11636. if (nhave >= k) break;
  11637. }
  11638. std::vector<llama_token_data> tmp_tokens(nhave);
  11639. auto ptr = tmp_tokens.data();
  11640. std::vector<llama_token_data*> bucket_ptrs;
  11641. bucket_ptrs.reserve(nbuckets - ib);
  11642. for (int j = nbuckets - 1; j >= ib; --j) {
  11643. bucket_ptrs.push_back(ptr);
  11644. ptr += histo[j];
  11645. }
  11646. for (int i = 0; i < (int)candidates->size; ++i) {
  11647. int j = bucket_idx[i];
  11648. if (j >= ib) {
  11649. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  11650. }
  11651. }
  11652. ptr = tmp_tokens.data();
  11653. int ndone = 0;
  11654. for (int j = nbuckets-1; j > ib; --j) {
  11655. std::sort(ptr, ptr + histo[j], comp);
  11656. ptr += histo[j];
  11657. ndone += histo[j];
  11658. }
  11659. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  11660. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  11661. }
  11662. candidates->sorted = true;
  11663. }
  11664. candidates->size = k;
  11665. if (ctx) {
  11666. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11667. }
  11668. }
  11669. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11670. if (p >= 1.0f) {
  11671. return;
  11672. }
  11673. llama_sample_softmax(ctx, candidates);
  11674. const int64_t t_start_sample_us = ggml_time_us();
  11675. // Compute the cumulative probabilities
  11676. float cum_sum = 0.0f;
  11677. size_t last_idx = candidates->size;
  11678. for (size_t i = 0; i < candidates->size; ++i) {
  11679. cum_sum += candidates->data[i].p;
  11680. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  11681. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  11682. if (cum_sum >= p && i + 1 >= min_keep) {
  11683. last_idx = i + 1;
  11684. break;
  11685. }
  11686. }
  11687. // Resize the output vector to keep only the top-p tokens
  11688. candidates->size = last_idx;
  11689. if (ctx) {
  11690. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11691. }
  11692. }
  11693. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11694. if (p <= 0.0f || !candidates->size) {
  11695. return;
  11696. }
  11697. const int64_t t_start_sample_us = ggml_time_us();
  11698. bool min_p_applied = false;
  11699. // if the candidates aren't sorted, try the unsorted implementation first
  11700. if (!candidates->sorted) {
  11701. std::vector<llama_token_data> filtered_tokens;
  11702. float max_logit = -FLT_MAX;
  11703. for (size_t i = 0; i < candidates->size; ++i) {
  11704. max_logit = std::max(max_logit, candidates->data[i].logit);
  11705. }
  11706. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  11707. for (size_t i = 0; i < candidates->size; ++i) {
  11708. if (candidates->data[i].logit >= min_logit) {
  11709. filtered_tokens.push_back(candidates->data[i]);
  11710. }
  11711. }
  11712. // if we have enough values the operation was a success
  11713. if (filtered_tokens.size() >= min_keep) {
  11714. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  11715. candidates->size = filtered_tokens.size();
  11716. min_p_applied = true;
  11717. }
  11718. }
  11719. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  11720. if (!min_p_applied) {
  11721. // Sort the logits in descending order
  11722. if (!candidates->sorted) {
  11723. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  11724. return a.logit > b.logit;
  11725. });
  11726. candidates->sorted = true;
  11727. }
  11728. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  11729. size_t i = 1; // first token always matches
  11730. for (; i < candidates->size; ++i) {
  11731. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  11732. break; // prob too small
  11733. }
  11734. }
  11735. // Resize the output vector to keep only the matching tokens
  11736. candidates->size = i;
  11737. }
  11738. if (ctx) {
  11739. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11740. }
  11741. }
  11742. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  11743. if (z >= 1.0f || candidates->size <= 2) {
  11744. return;
  11745. }
  11746. llama_sample_softmax(nullptr, candidates);
  11747. const int64_t t_start_sample_us = ggml_time_us();
  11748. // Compute the first and second derivatives
  11749. std::vector<float> first_derivatives(candidates->size - 1);
  11750. std::vector<float> second_derivatives(candidates->size - 2);
  11751. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  11752. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  11753. }
  11754. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11755. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  11756. }
  11757. // Calculate absolute value of second derivatives
  11758. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11759. second_derivatives[i] = std::abs(second_derivatives[i]);
  11760. }
  11761. // Normalize the second derivatives
  11762. {
  11763. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  11764. if (second_derivatives_sum > 1e-6f) {
  11765. for (float & value : second_derivatives) {
  11766. value /= second_derivatives_sum;
  11767. }
  11768. } else {
  11769. for (float & value : second_derivatives) {
  11770. value = 1.0f / second_derivatives.size();
  11771. }
  11772. }
  11773. }
  11774. float cum_sum = 0.0f;
  11775. size_t last_idx = candidates->size;
  11776. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11777. cum_sum += second_derivatives[i];
  11778. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  11779. if (cum_sum > z && i >= min_keep) {
  11780. last_idx = i;
  11781. break;
  11782. }
  11783. }
  11784. // Resize the output vector to keep only the tokens above the tail location
  11785. candidates->size = last_idx;
  11786. if (ctx) {
  11787. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11788. }
  11789. }
  11790. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11791. // Reference implementation:
  11792. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  11793. if (p >= 1.0f) {
  11794. return;
  11795. }
  11796. // Compute the softmax of logits and calculate entropy
  11797. llama_sample_softmax(nullptr, candidates);
  11798. const int64_t t_start_sample_us = ggml_time_us();
  11799. float entropy = 0.0f;
  11800. for (size_t i = 0; i < candidates->size; ++i) {
  11801. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  11802. }
  11803. // Compute the absolute difference between negative log probability and entropy for each candidate
  11804. std::vector<float> shifted_scores;
  11805. for (size_t i = 0; i < candidates->size; ++i) {
  11806. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  11807. shifted_scores.push_back(shifted_score);
  11808. }
  11809. // Sort tokens based on the shifted_scores and their corresponding indices
  11810. std::vector<size_t> indices(candidates->size);
  11811. std::iota(indices.begin(), indices.end(), 0);
  11812. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  11813. return shifted_scores[a] < shifted_scores[b];
  11814. });
  11815. // Compute the cumulative probabilities
  11816. float cum_sum = 0.0f;
  11817. size_t last_idx = indices.size();
  11818. for (size_t i = 0; i < indices.size(); ++i) {
  11819. size_t idx = indices[i];
  11820. cum_sum += candidates->data[idx].p;
  11821. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  11822. if (cum_sum > p && i >= min_keep - 1) {
  11823. last_idx = i + 1;
  11824. break;
  11825. }
  11826. }
  11827. // Resize the output vector to keep only the locally typical tokens
  11828. std::vector<llama_token_data> new_candidates;
  11829. for (size_t i = 0; i < last_idx; ++i) {
  11830. size_t idx = indices[i];
  11831. new_candidates.push_back(candidates->data[idx]);
  11832. }
  11833. // Replace the data in candidates with the new_candidates data
  11834. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  11835. candidates->size = new_candidates.size();
  11836. candidates->sorted = false;
  11837. if (ctx) {
  11838. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11839. }
  11840. }
  11841. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  11842. const int64_t t_start_sample_us = ggml_time_us();
  11843. // no need to do anything if there is only one (or zero) candidates
  11844. if(candidates_p->size <= 1) {
  11845. return;
  11846. }
  11847. // Calculate maximum possible entropy
  11848. float max_entropy = -logf(1.0f / candidates_p->size);
  11849. llama_sample_softmax(nullptr, candidates_p);
  11850. // Calculate entropy of the softmax probabilities
  11851. float entropy = 0.0f;
  11852. for (size_t i = 0; i < candidates_p->size; ++i) {
  11853. float prob = candidates_p->data[i].p;
  11854. if (prob > 0.0f) { // Ensure no log(0)
  11855. entropy -= prob * logf(prob);
  11856. }
  11857. }
  11858. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  11859. float normalized_entropy = entropy / max_entropy;
  11860. // Map the normalized entropy to the desired temperature range using the power function
  11861. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  11862. #ifdef DEBUG
  11863. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  11864. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  11865. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  11866. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  11867. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  11868. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  11869. #endif
  11870. // Apply the dynamically calculated temperature scaling
  11871. for (size_t i = 0; i < candidates_p->size; ++i) {
  11872. candidates_p->data[i].logit /= dyn_temp;
  11873. }
  11874. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  11875. double max_l_double = candidates_p->data[0].logit;
  11876. double cum_sum_double = 0.0;
  11877. for (size_t i = 0; i < candidates_p->size; ++i) {
  11878. double p = exp(candidates_p->data[i].logit - max_l_double);
  11879. candidates_p->data[i].p = p; // Store the scaled probability
  11880. cum_sum_double += p;
  11881. }
  11882. for (size_t i = 0; i < candidates_p->size; ++i) {
  11883. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  11884. }
  11885. #ifdef DEBUG
  11886. // Print the updated top 25 probabilities after temperature scaling
  11887. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  11888. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  11889. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  11890. }
  11891. #endif
  11892. if (ctx) {
  11893. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11894. }
  11895. }
  11896. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  11897. const int64_t t_start_sample_us = ggml_time_us();
  11898. for (size_t i = 0; i < candidates_p->size; ++i) {
  11899. candidates_p->data[i].logit /= temp;
  11900. }
  11901. if (ctx) {
  11902. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11903. }
  11904. }
  11905. void llama_sample_repetition_penalties(
  11906. struct llama_context * ctx,
  11907. llama_token_data_array * candidates,
  11908. const llama_token * last_tokens,
  11909. size_t penalty_last_n,
  11910. float penalty_repeat,
  11911. float penalty_freq,
  11912. float penalty_present) {
  11913. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  11914. return;
  11915. }
  11916. const int64_t t_start_sample_us = ggml_time_us();
  11917. // Create a frequency map to count occurrences of each token in last_tokens
  11918. std::unordered_map<llama_token, int> token_count;
  11919. for (size_t i = 0; i < penalty_last_n; ++i) {
  11920. token_count[last_tokens[i]]++;
  11921. }
  11922. // Apply frequency and presence penalties to the candidates
  11923. for (size_t i = 0; i < candidates->size; ++i) {
  11924. const auto token_iter = token_count.find(candidates->data[i].id);
  11925. if (token_iter == token_count.end()) {
  11926. continue;
  11927. }
  11928. const int count = token_iter->second;
  11929. // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
  11930. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  11931. if (candidates->data[i].logit <= 0) {
  11932. candidates->data[i].logit *= penalty_repeat;
  11933. } else {
  11934. candidates->data[i].logit /= penalty_repeat;
  11935. }
  11936. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  11937. }
  11938. candidates->sorted = false;
  11939. if (ctx) {
  11940. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11941. }
  11942. }
  11943. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  11944. GGML_ASSERT(ctx);
  11945. int64_t t_start_sample_us = ggml_time_us();
  11946. bool allow_eog = false;
  11947. for (const auto & stack : grammar->stacks) {
  11948. if (stack.empty()) {
  11949. allow_eog = true;
  11950. break;
  11951. }
  11952. }
  11953. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  11954. candidates_decoded.reserve(candidates->size);
  11955. std::vector<llama_grammar_candidate> candidates_grammar;
  11956. candidates_grammar.reserve(candidates->size);
  11957. for (size_t i = 0; i < candidates->size; ++i) {
  11958. const llama_token id = candidates->data[i].id;
  11959. const std::string & piece = ctx->model.vocab.cache_token_to_piece.at(id);
  11960. if (llama_token_is_eog(&ctx->model, id)) {
  11961. if (!allow_eog) {
  11962. candidates->data[i].logit = -INFINITY;
  11963. }
  11964. } else if (piece.empty() || piece[0] == 0) {
  11965. candidates->data[i].logit = -INFINITY;
  11966. } else {
  11967. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  11968. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  11969. }
  11970. }
  11971. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  11972. for (const auto & reject : rejects) {
  11973. candidates->data[reject.index].logit = -INFINITY;
  11974. }
  11975. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11976. }
  11977. static void llama_log_softmax(float * array, size_t size) {
  11978. float max_l = *std::max_element(array, array + size);
  11979. float sum = 0.f;
  11980. for (size_t i = 0; i < size; ++i) {
  11981. float p = expf(array[i] - max_l);
  11982. sum += p;
  11983. array[i] = p;
  11984. }
  11985. for (size_t i = 0; i < size; ++i) {
  11986. array[i] = logf(array[i] / sum);
  11987. }
  11988. }
  11989. void llama_sample_apply_guidance(
  11990. struct llama_context * ctx,
  11991. float * logits,
  11992. float * logits_guidance,
  11993. float scale) {
  11994. GGML_ASSERT(ctx);
  11995. const auto t_start_sample_us = ggml_time_us();
  11996. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  11997. llama_log_softmax(logits, n_vocab);
  11998. llama_log_softmax(logits_guidance, n_vocab);
  11999. for (int i = 0; i < n_vocab; ++i) {
  12000. auto & l = logits[i];
  12001. const auto & g = logits_guidance[i];
  12002. l = scale * (l - g) + g;
  12003. }
  12004. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12005. }
  12006. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  12007. GGML_ASSERT(ctx);
  12008. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  12009. int64_t t_start_sample_us;
  12010. t_start_sample_us = ggml_time_us();
  12011. llama_sample_softmax(nullptr, candidates);
  12012. // Estimate s_hat using the most probable m tokens
  12013. float s_hat = 0.0;
  12014. float sum_ti_bi = 0.0;
  12015. float sum_ti_sq = 0.0;
  12016. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  12017. float t_i = logf(float(i + 2) / float(i + 1));
  12018. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  12019. sum_ti_bi += t_i * b_i;
  12020. sum_ti_sq += t_i * t_i;
  12021. }
  12022. s_hat = sum_ti_bi / sum_ti_sq;
  12023. // Compute k from the estimated s_hat and target surprise value
  12024. float epsilon_hat = s_hat - 1;
  12025. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  12026. // Sample the next word X using top-k sampling
  12027. llama_sample_top_k(nullptr, candidates, int(k), 1);
  12028. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12029. llama_token X = llama_sample_token(ctx, candidates);
  12030. t_start_sample_us = ggml_time_us();
  12031. // Compute error as the difference between observed surprise and target surprise value
  12032. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  12033. return candidate.id == X;
  12034. }));
  12035. float observed_surprise = -log2f(candidates->data[X_idx].p);
  12036. float e = observed_surprise - tau;
  12037. // Update mu using the learning rate and error
  12038. *mu = *mu - eta * e;
  12039. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12040. return X;
  12041. }
  12042. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  12043. int64_t t_start_sample_us;
  12044. t_start_sample_us = ggml_time_us();
  12045. llama_sample_softmax(ctx, candidates);
  12046. // Truncate the words with surprise values greater than mu
  12047. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  12048. return -log2f(candidate.p) > *mu;
  12049. }));
  12050. if (candidates->size == 0) {
  12051. candidates->size = 1;
  12052. }
  12053. if (ctx) {
  12054. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12055. }
  12056. // Normalize the probabilities of the remaining words
  12057. llama_sample_softmax(ctx, candidates);
  12058. // Sample the next word X from the remaining words
  12059. llama_token X = llama_sample_token(ctx, candidates);
  12060. t_start_sample_us = ggml_time_us();
  12061. // Compute error as the difference between observed surprise and target surprise value
  12062. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  12063. return candidate.id == X;
  12064. }));
  12065. float observed_surprise = -log2f(candidates->data[X_idx].p);
  12066. float e = observed_surprise - tau;
  12067. // Update mu using the learning rate and error
  12068. *mu = *mu - eta * e;
  12069. if (ctx) {
  12070. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12071. }
  12072. return X;
  12073. }
  12074. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  12075. const int64_t t_start_sample_us = ggml_time_us();
  12076. // Find max element
  12077. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  12078. return a.logit < b.logit;
  12079. });
  12080. llama_token result = max_iter->id;
  12081. if (ctx) {
  12082. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12083. ctx->n_sample++;
  12084. }
  12085. return result;
  12086. }
  12087. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  12088. GGML_ASSERT(ctx);
  12089. const int64_t t_start_sample_us = ggml_time_us();
  12090. llama_sample_softmax(nullptr, candidates);
  12091. std::vector<float> probs;
  12092. probs.reserve(candidates->size);
  12093. for (size_t i = 0; i < candidates->size; ++i) {
  12094. probs.push_back(candidates->data[i].p);
  12095. }
  12096. std::discrete_distribution<> dist(probs.begin(), probs.end());
  12097. int idx = dist(rng);
  12098. llama_token result = candidates->data[idx].id;
  12099. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12100. ctx->n_sample++;
  12101. return result;
  12102. }
  12103. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  12104. return llama_sample_token_with_rng(ctx, candidates, ctx->rng);
  12105. }
  12106. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  12107. const int64_t t_start_sample_us = ggml_time_us();
  12108. if (llama_token_is_eog(&ctx->model, token)) {
  12109. for (const auto & stack : grammar->stacks) {
  12110. if (stack.empty()) {
  12111. return;
  12112. }
  12113. }
  12114. GGML_ASSERT(false);
  12115. }
  12116. const std::string & piece = ctx->model.vocab.cache_token_to_piece.at(token);
  12117. // Note terminating 0 in decoded string
  12118. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  12119. const auto & code_points = decoded.first;
  12120. std::vector<std::vector<const llama_grammar_element *>> tmp_new_stacks;
  12121. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  12122. llama_grammar_accept(grammar->rules, grammar->stacks, *it, tmp_new_stacks);
  12123. grammar->stacks = tmp_new_stacks;
  12124. }
  12125. grammar->partial_utf8 = decoded.second;
  12126. GGML_ASSERT(!grammar->stacks.empty());
  12127. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12128. }
  12129. //
  12130. // Beam search
  12131. //
  12132. struct llama_beam {
  12133. std::vector<llama_token> tokens;
  12134. float p; // Cumulative beam probability (renormalized relative to all beams)
  12135. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  12136. // Sort beams by probability. In case of ties, prefer beams at eob.
  12137. bool operator<(const llama_beam & rhs) const {
  12138. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  12139. }
  12140. // Shift off first n tokens and discard them.
  12141. void shift_tokens(const size_t n) {
  12142. if (n) {
  12143. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  12144. tokens.resize(tokens.size() - n);
  12145. }
  12146. }
  12147. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  12148. };
  12149. // A struct for calculating logit-related info.
  12150. struct llama_logit_info {
  12151. const float * const logits;
  12152. const int n_vocab;
  12153. const float max_l;
  12154. const float normalizer;
  12155. struct sum_exp {
  12156. float max_l;
  12157. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  12158. };
  12159. llama_logit_info(llama_context * ctx)
  12160. : logits(llama_get_logits(ctx))
  12161. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  12162. , max_l(*std::max_element(logits, logits + n_vocab))
  12163. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  12164. { }
  12165. llama_token_data get_token_data(const llama_token token_id) const {
  12166. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  12167. return {token_id, logits[token_id], p};
  12168. }
  12169. // Return top k token_data by logit.
  12170. std::vector<llama_token_data> top_k(size_t k) {
  12171. std::vector<llama_token_data> min_heap; // min-heap by logit
  12172. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  12173. min_heap.reserve(k_min);
  12174. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  12175. min_heap.push_back(get_token_data(token_id));
  12176. }
  12177. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  12178. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  12179. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  12180. if (min_heap.front().logit < logits[token_id]) {
  12181. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  12182. min_heap.back().id = token_id;
  12183. min_heap.back().logit = logits[token_id];
  12184. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  12185. }
  12186. }
  12187. return min_heap;
  12188. }
  12189. float probability_from_logit(float logit) const {
  12190. return normalizer * std::exp(logit - max_l);
  12191. }
  12192. };
  12193. struct llama_beam_search_data {
  12194. llama_context * ctx;
  12195. size_t n_beams;
  12196. int n_past;
  12197. int n_predict;
  12198. std::vector<llama_beam> beams;
  12199. std::vector<llama_beam> next_beams;
  12200. // Re-calculated on each loop iteration
  12201. size_t common_prefix_length;
  12202. // Used to communicate to/from callback on beams state.
  12203. std::vector<llama_beam_view> beam_views;
  12204. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  12205. : ctx(ctx)
  12206. , n_beams(n_beams)
  12207. , n_past(n_past)
  12208. , n_predict(n_predict)
  12209. , beam_views(n_beams) {
  12210. beams.reserve(n_beams);
  12211. next_beams.reserve(n_beams);
  12212. }
  12213. // Collapse beams to a single beam given by index.
  12214. void collapse_beams(const size_t beam_idx) {
  12215. if (0u < beam_idx) {
  12216. std::swap(beams[0], beams[beam_idx]);
  12217. }
  12218. beams.resize(1);
  12219. }
  12220. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  12221. // The repetitive patterns below reflect the 2 stages of heaps:
  12222. // * Gather elements until the vector is full, then call std::make_heap() on it.
  12223. // * If the heap is full and a new element is found that should be included, pop the
  12224. // least element to the back(), replace it with the new, then push it into the heap.
  12225. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  12226. // Min-heaps use a greater-than comparator.
  12227. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  12228. if (beam.eob) {
  12229. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  12230. if (next_beams.size() < n_beams) {
  12231. next_beams.push_back(std::move(beam));
  12232. if (next_beams.size() == n_beams) {
  12233. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  12234. }
  12235. } else if (next_beams.front().p < beam.p) {
  12236. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  12237. next_beams.back() = std::move(beam);
  12238. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  12239. }
  12240. } else {
  12241. // beam is not at end-of-sentence, so branch with next top_k tokens.
  12242. if (!beam.tokens.empty()) {
  12243. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  12244. }
  12245. llama_logit_info logit_info(ctx);
  12246. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  12247. // Clear the kv slot so that other beams may try different tokens at this position. The llama_decode()
  12248. // call in loop() will conclusively fill in the kv slot once the beams converge at this position.
  12249. llama_kv_cache_seq_rm(ctx, 0, n_past, -1);
  12250. size_t i=0;
  12251. if (next_beams.size() < n_beams) {
  12252. for (; next_beams.size() < n_beams ; ++i) {
  12253. llama_beam next_beam = beam;
  12254. next_beam.tokens.push_back(next_tokens[i].id);
  12255. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  12256. next_beams.push_back(std::move(next_beam));
  12257. }
  12258. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  12259. } else {
  12260. for (; next_beams.front().p == 0.0f ; ++i) {
  12261. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  12262. next_beams.back() = beam;
  12263. next_beams.back().tokens.push_back(next_tokens[i].id);
  12264. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  12265. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  12266. }
  12267. }
  12268. for (; i < n_beams ; ++i) {
  12269. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  12270. if (next_beams.front().p < next_p) {
  12271. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  12272. next_beams.back() = beam;
  12273. next_beams.back().tokens.push_back(next_tokens[i].id);
  12274. next_beams.back().p = next_p;
  12275. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  12276. }
  12277. }
  12278. }
  12279. }
  12280. // Find common_prefix_length based on beams.
  12281. // Requires beams is not empty.
  12282. size_t find_common_prefix_length() {
  12283. size_t common_prefix_length = beams[0].tokens.size();
  12284. for (size_t i = 1 ; i < beams.size() ; ++i) {
  12285. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  12286. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  12287. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  12288. common_prefix_length = j;
  12289. break;
  12290. }
  12291. }
  12292. }
  12293. return common_prefix_length;
  12294. }
  12295. // Construct beams_state to send back to caller via the callback function.
  12296. // Side effect: set common_prefix_length = find_common_prefix_length();
  12297. llama_beams_state get_beams_state(const bool last_call) {
  12298. for (size_t i = 0 ; i < beams.size() ; ++i) {
  12299. beam_views[i] = beams[i].view();
  12300. }
  12301. common_prefix_length = find_common_prefix_length();
  12302. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  12303. }
  12304. // Loop:
  12305. // * while i < n_predict, AND
  12306. // * any of the beams have not yet reached end-of-beam (eob), AND
  12307. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  12308. // (since all other beam probabilities can only decrease)
  12309. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  12310. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  12311. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  12312. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  12313. !beams[top_beam_index()].eob ; ++i) {
  12314. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  12315. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  12316. if (common_prefix_length) {
  12317. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  12318. n_past += common_prefix_length;
  12319. }
  12320. // Zero-out next_beam probabilities to place them last in following min-heap.
  12321. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  12322. for (llama_beam & beam : beams) {
  12323. beam.shift_tokens(common_prefix_length);
  12324. fill_next_beams_by_top_probabilities(beam);
  12325. }
  12326. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  12327. beams.swap(next_beams);
  12328. renormalize_beam_probabilities(beams);
  12329. }
  12330. collapse_beams(top_beam_index());
  12331. callback(callback_data, get_beams_state(true));
  12332. }
  12333. // As beams grow, the cumulative probabilities decrease.
  12334. // Renormalize them to avoid floating point underflow.
  12335. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  12336. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  12337. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  12338. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  12339. }
  12340. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  12341. size_t top_beam_index() {
  12342. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  12343. }
  12344. // Copy (p,eob) for each beam which may have been changed by the callback.
  12345. void update_beams_from_beam_views() {
  12346. for (size_t i = 0 ; i < beams.size() ; ++i) {
  12347. beams[i].p = beam_views[i].p;
  12348. beams[i].eob = beam_views[i].eob;
  12349. }
  12350. }
  12351. };
  12352. void llama_beam_search(llama_context * ctx,
  12353. llama_beam_search_callback_fn_t callback, void * callback_data,
  12354. size_t n_beams, int n_past, int n_predict) {
  12355. assert(ctx);
  12356. const int64_t t_start_sample_us = ggml_time_us();
  12357. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  12358. beam_search_data.loop(callback, callback_data);
  12359. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  12360. ctx->n_sample++;
  12361. }
  12362. //
  12363. // quantization
  12364. //
  12365. struct quantize_state_internal {
  12366. const llama_model & model;
  12367. const llama_model_quantize_params * params;
  12368. int n_attention_wv = 0;
  12369. int n_ffn_down = 0;
  12370. int n_ffn_gate = 0;
  12371. int n_ffn_up = 0;
  12372. int i_attention_wv = 0;
  12373. int i_ffn_down = 0;
  12374. int i_ffn_gate = 0;
  12375. int i_ffn_up = 0;
  12376. int n_k_quantized = 0;
  12377. int n_fallback = 0;
  12378. bool has_imatrix = false;
  12379. // used to figure out if a model shares tok_embd with the output weight
  12380. bool has_output = false;
  12381. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  12382. : model(model)
  12383. , params(params)
  12384. {}
  12385. };
  12386. static void llama_tensor_dequantize_internal(
  12387. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  12388. const size_t nelements, const int nthread
  12389. ) {
  12390. if (output.size() < nelements) {
  12391. output.resize(nelements);
  12392. }
  12393. float * f32_output = (float *) output.data();
  12394. ggml_type_traits_t qtype;
  12395. if (ggml_is_quantized(tensor->type)) {
  12396. qtype = ggml_internal_get_type_traits(tensor->type);
  12397. if (qtype.to_float == NULL) {
  12398. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  12399. }
  12400. } else if (tensor->type != GGML_TYPE_F16 &&
  12401. tensor->type != GGML_TYPE_BF16) {
  12402. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  12403. }
  12404. if (nthread < 2) {
  12405. if (tensor->type == GGML_TYPE_F16) {
  12406. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  12407. } else if (tensor->type == GGML_TYPE_BF16) {
  12408. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  12409. } else if (ggml_is_quantized(tensor->type)) {
  12410. qtype.to_float(tensor->data, f32_output, nelements);
  12411. } else {
  12412. GGML_ASSERT(false); // unreachable
  12413. }
  12414. return;
  12415. }
  12416. size_t block_size;
  12417. if (tensor->type == GGML_TYPE_F16 ||
  12418. tensor->type == GGML_TYPE_BF16) {
  12419. block_size = 1;
  12420. } else {
  12421. block_size = (size_t)ggml_blck_size(tensor->type);
  12422. }
  12423. size_t block_size_bytes = ggml_type_size(tensor->type);
  12424. GGML_ASSERT(nelements % block_size == 0);
  12425. size_t nblocks = nelements / block_size;
  12426. size_t blocks_per_thread = nblocks / nthread;
  12427. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  12428. size_t in_buff_offs = 0;
  12429. size_t out_buff_offs = 0;
  12430. for (int tnum = 0; tnum < nthread; tnum++) {
  12431. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  12432. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  12433. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  12434. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  12435. if (typ == GGML_TYPE_F16) {
  12436. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  12437. } else if (typ == GGML_TYPE_BF16) {
  12438. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  12439. } else {
  12440. qtype.to_float(inbuf, outbuf, nels);
  12441. }
  12442. };
  12443. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  12444. in_buff_offs += thr_block_bytes;
  12445. out_buff_offs += thr_elems;
  12446. }
  12447. for (auto & w : workers) { w.join(); }
  12448. workers.clear();
  12449. }
  12450. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  12451. const std::string name = ggml_get_name(tensor);
  12452. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12453. const llm_arch arch = qs.model.arch;
  12454. const auto tn = LLM_TN(arch);
  12455. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  12456. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  12457. };
  12458. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  12459. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  12460. if (n_expert > 1) {
  12461. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  12462. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  12463. // for getting the current layer as I initially thought, and we need to resort to parsing the
  12464. // tensor name.
  12465. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  12466. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  12467. }
  12468. if (i_layer < 0 || i_layer >= n_layer) {
  12469. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  12470. }
  12471. }
  12472. return std::make_pair(i_layer, n_layer);
  12473. };
  12474. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  12475. // with the quantization of the output tensor
  12476. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  12477. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  12478. new_type = qs.params->output_tensor_type;
  12479. } else {
  12480. int nx = tensor->ne[0];
  12481. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  12482. new_type = GGML_TYPE_Q8_0;
  12483. }
  12484. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12485. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  12486. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12487. new_type = GGML_TYPE_Q5_K;
  12488. }
  12489. else if (new_type != GGML_TYPE_Q8_0) {
  12490. new_type = GGML_TYPE_Q6_K;
  12491. }
  12492. }
  12493. } else if (name == "token_embd.weight") {
  12494. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  12495. new_type = qs.params->token_embedding_type;
  12496. } else {
  12497. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  12498. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12499. new_type = GGML_TYPE_Q2_K;
  12500. }
  12501. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  12502. new_type = GGML_TYPE_IQ3_S;
  12503. }
  12504. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12505. new_type = GGML_TYPE_IQ3_S;
  12506. }
  12507. }
  12508. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  12509. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12510. if (name.find("attn_v.weight") != std::string::npos) {
  12511. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  12512. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12513. ++qs.i_attention_wv;
  12514. }
  12515. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  12516. new_type = GGML_TYPE_Q4_K;
  12517. }
  12518. else if (name.find("ffn_down") != std::string::npos) {
  12519. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  12520. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12521. }
  12522. ++qs.i_ffn_down;
  12523. }
  12524. else if (name.find("attn_output.weight") != std::string::npos) {
  12525. if (qs.model.hparams.n_expert == 8) {
  12526. new_type = GGML_TYPE_Q5_K;
  12527. } else {
  12528. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  12529. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  12530. }
  12531. }
  12532. } else if (name.find("attn_v.weight") != std::string::npos) {
  12533. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  12534. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12535. }
  12536. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  12537. new_type = GGML_TYPE_Q4_K;
  12538. }
  12539. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12540. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  12541. }
  12542. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  12543. new_type = GGML_TYPE_Q4_K;
  12544. }
  12545. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12546. new_type = GGML_TYPE_Q4_K;
  12547. }
  12548. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12549. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12550. }
  12551. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  12552. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  12553. new_type = GGML_TYPE_Q5_K;
  12554. }
  12555. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  12556. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  12557. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  12558. if (qs.model.type == MODEL_70B) {
  12559. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  12560. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  12561. // nearly negligible increase in model size by quantizing this tensor with more bits:
  12562. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  12563. }
  12564. if (qs.model.hparams.n_expert == 8) {
  12565. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12566. // TODO: explore better strategies
  12567. new_type = GGML_TYPE_Q8_0;
  12568. }
  12569. ++qs.i_attention_wv;
  12570. } else if (name.find("attn_k.weight") != std::string::npos) {
  12571. if (qs.model.hparams.n_expert == 8) {
  12572. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12573. // TODO: explore better strategies
  12574. new_type = GGML_TYPE_Q8_0;
  12575. }
  12576. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12577. new_type = GGML_TYPE_IQ3_XXS;
  12578. }
  12579. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12580. new_type = GGML_TYPE_IQ2_S;
  12581. }
  12582. } else if (name.find("attn_q.weight") != std::string::npos) {
  12583. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12584. new_type = GGML_TYPE_IQ3_XXS;
  12585. }
  12586. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12587. new_type = GGML_TYPE_IQ2_S;
  12588. }
  12589. } else if (name.find("ffn_down") != std::string::npos) {
  12590. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  12591. int i_layer = info.first, n_layer = info.second;
  12592. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12593. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  12594. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  12595. }
  12596. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  12597. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12598. }
  12599. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12600. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  12601. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  12602. : GGML_TYPE_Q3_K;
  12603. }
  12604. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  12605. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  12606. new_type = GGML_TYPE_Q4_K;
  12607. }
  12608. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  12609. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  12610. }
  12611. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  12612. if (arch == LLM_ARCH_FALCON) {
  12613. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  12614. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12615. } else {
  12616. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12617. }
  12618. }
  12619. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  12620. new_type = GGML_TYPE_Q5_K;
  12621. }
  12622. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12623. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  12624. new_type = GGML_TYPE_Q5_K;
  12625. }
  12626. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  12627. && qs.has_imatrix && i_layer < n_layer/8) {
  12628. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  12629. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  12630. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  12631. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  12632. }
  12633. ++qs.i_ffn_down;
  12634. } else if (name.find("attn_output.weight") != std::string::npos) {
  12635. if (arch != LLM_ARCH_FALCON) {
  12636. if (qs.model.hparams.n_expert == 8) {
  12637. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12638. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  12639. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  12640. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  12641. new_type = GGML_TYPE_Q5_K;
  12642. }
  12643. } else {
  12644. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  12645. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  12646. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  12647. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  12648. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  12649. }
  12650. } else {
  12651. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  12652. }
  12653. }
  12654. else if (name.find("attn_qkv.weight") != std::string::npos) {
  12655. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12656. new_type = GGML_TYPE_Q4_K;
  12657. }
  12658. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  12659. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  12660. }
  12661. else if (name.find("ffn_gate") != std::string::npos) {
  12662. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  12663. int i_layer = info.first, n_layer = info.second;
  12664. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12665. new_type = GGML_TYPE_IQ3_XXS;
  12666. }
  12667. ++qs.i_ffn_gate;
  12668. }
  12669. else if (name.find("ffn_up") != std::string::npos) {
  12670. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  12671. int i_layer = info.first, n_layer = info.second;
  12672. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12673. new_type = GGML_TYPE_IQ3_XXS;
  12674. }
  12675. ++qs.i_ffn_up;
  12676. }
  12677. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12678. //}
  12679. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  12680. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  12681. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12682. //}
  12683. // This can be used to reduce the size of the Q5_K_S model.
  12684. // The associated PPL increase is fully in line with the size reduction
  12685. //else {
  12686. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  12687. //}
  12688. bool convert_incompatible_tensor = false;
  12689. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  12690. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  12691. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  12692. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  12693. new_type == GGML_TYPE_IQ1_M) {
  12694. int nx = tensor->ne[0];
  12695. int ny = tensor->ne[1];
  12696. if (nx % QK_K != 0) {
  12697. 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));
  12698. convert_incompatible_tensor = true;
  12699. } else {
  12700. ++qs.n_k_quantized;
  12701. }
  12702. }
  12703. if (convert_incompatible_tensor) {
  12704. switch (new_type) {
  12705. case GGML_TYPE_IQ2_XXS:
  12706. case GGML_TYPE_IQ2_XS:
  12707. case GGML_TYPE_IQ2_S:
  12708. case GGML_TYPE_IQ3_XXS:
  12709. case GGML_TYPE_IQ3_S:
  12710. case GGML_TYPE_IQ1_S:
  12711. case GGML_TYPE_IQ1_M:
  12712. case GGML_TYPE_Q2_K:
  12713. case GGML_TYPE_Q3_K:
  12714. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  12715. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  12716. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  12717. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  12718. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  12719. }
  12720. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  12721. ++qs.n_fallback;
  12722. }
  12723. return new_type;
  12724. }
  12725. 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) {
  12726. if (nthread < 2) {
  12727. // single-thread
  12728. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  12729. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  12730. throw std::runtime_error("quantized data validation failed");
  12731. }
  12732. return new_size;
  12733. }
  12734. std::mutex mutex;
  12735. int64_t counter = 0;
  12736. size_t new_size = 0;
  12737. bool valid = true;
  12738. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  12739. nrows, n_per_row, imatrix]() {
  12740. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  12741. size_t local_size = 0;
  12742. while (true) {
  12743. std::unique_lock<std::mutex> lock(mutex);
  12744. int64_t first_row = counter; counter += nrows_per_chunk;
  12745. if (first_row >= nrows) {
  12746. if (local_size > 0) {
  12747. new_size += local_size;
  12748. }
  12749. break;
  12750. }
  12751. lock.unlock();
  12752. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  12753. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  12754. local_size += this_size;
  12755. // validate the quantized data
  12756. const size_t row_size = ggml_row_size(new_type, n_per_row);
  12757. void * this_data = (char *) new_data + first_row * row_size;
  12758. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  12759. std::unique_lock<std::mutex> lock(mutex);
  12760. valid = false;
  12761. break;
  12762. }
  12763. }
  12764. };
  12765. for (int it = 0; it < nthread - 1; ++it) {
  12766. workers.emplace_back(compute);
  12767. }
  12768. compute();
  12769. for (auto & w : workers) { w.join(); }
  12770. workers.clear();
  12771. if (!valid) {
  12772. throw std::runtime_error("quantized data validation failed");
  12773. }
  12774. return new_size;
  12775. }
  12776. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  12777. ggml_type default_type;
  12778. llama_ftype ftype = params->ftype;
  12779. switch (params->ftype) {
  12780. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  12781. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  12782. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  12783. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  12784. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  12785. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  12786. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  12787. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  12788. // K-quants
  12789. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  12790. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  12791. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  12792. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  12793. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  12794. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  12795. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  12796. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  12797. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  12798. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  12799. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  12800. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  12801. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  12802. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  12803. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  12804. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  12805. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  12806. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  12807. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  12808. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  12809. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  12810. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  12811. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  12812. }
  12813. int nthread = params->nthread;
  12814. if (nthread <= 0) {
  12815. nthread = std::thread::hardware_concurrency();
  12816. }
  12817. // mmap consistently increases speed Linux, and also increases speed on Windows with
  12818. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  12819. #if defined(__linux__) || defined(_WIN32)
  12820. constexpr bool use_mmap = true;
  12821. #else
  12822. constexpr bool use_mmap = false;
  12823. #endif
  12824. llama_model_kv_override * kv_overrides = nullptr;
  12825. if (params->kv_overrides) {
  12826. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  12827. kv_overrides = v->data();
  12828. }
  12829. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  12830. ml.init_mappings(false); // no prefetching
  12831. llama_model model;
  12832. llm_load_arch(ml, model);
  12833. llm_load_hparams(ml, model);
  12834. struct quantize_state_internal qs(model, params);
  12835. if (params->only_copy) {
  12836. ftype = model.ftype;
  12837. }
  12838. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  12839. if (params->imatrix) {
  12840. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  12841. if (imatrix_data) {
  12842. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  12843. qs.has_imatrix = true;
  12844. }
  12845. }
  12846. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  12847. struct gguf_context * ctx_out = gguf_init_empty();
  12848. // copy the KV pairs from the input file
  12849. gguf_set_kv (ctx_out, ml.meta);
  12850. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  12851. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  12852. // Remove split metadata
  12853. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  12854. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  12855. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  12856. if (params->kv_overrides) {
  12857. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  12858. for (auto & o : overrides) {
  12859. if (o.key[0] == 0) break;
  12860. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  12861. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  12862. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  12863. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  12864. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  12865. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  12866. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  12867. gguf_set_val_str(ctx_out, o.key, o.val_str);
  12868. } else {
  12869. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  12870. }
  12871. }
  12872. }
  12873. for (int i = 0; i < ml.n_tensors; ++i) {
  12874. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  12875. const std::string name = ggml_get_name(meta);
  12876. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12877. if (name.find("attn_v.weight") != std::string::npos ||
  12878. name.find("attn_qkv.weight") != std::string::npos) {
  12879. ++qs.n_attention_wv;
  12880. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  12881. qs.has_output = true;
  12882. }
  12883. }
  12884. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  12885. // sanity checks
  12886. //
  12887. // - qs.n_attention_wv == 0 for Mamba models
  12888. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  12889. //
  12890. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  12891. size_t total_size_org = 0;
  12892. size_t total_size_new = 0;
  12893. std::vector<std::thread> workers;
  12894. workers.reserve(nthread);
  12895. int idx = 0;
  12896. std::vector<no_init<uint8_t>> read_data;
  12897. std::vector<no_init<uint8_t>> work;
  12898. std::vector<no_init<float>> f32_conv_buf;
  12899. uint16_t n_split = 1;
  12900. // Assume split index is continuous
  12901. if (params->keep_split) {
  12902. for (int i = 0; i < ml.n_tensors; ++i) {
  12903. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  12904. }
  12905. }
  12906. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  12907. ctx_outs[0] = ctx_out;
  12908. // populate the original tensors so we get an initial meta data
  12909. for (int i = 0; i < ml.n_tensors; ++i) {
  12910. auto weight = ml.get_weight(i);
  12911. uint16_t i_split = params->keep_split ? weight->idx : 0;
  12912. struct ggml_tensor * tensor = weight->tensor;
  12913. if (ctx_outs[i_split] == NULL) {
  12914. ctx_outs[i_split] = gguf_init_empty();
  12915. }
  12916. gguf_add_tensor(ctx_outs[i_split], tensor);
  12917. }
  12918. // Set split info if needed
  12919. if (n_split > 1) {
  12920. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  12921. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  12922. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  12923. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  12924. }
  12925. }
  12926. int cur_split = -1;
  12927. std::ofstream fout;
  12928. auto close_ofstream = [&]() {
  12929. // Write metadata and close file handler
  12930. if (fout.is_open()) {
  12931. fout.seekp(0);
  12932. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  12933. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  12934. fout.write((const char *) data.data(), data.size());
  12935. fout.close();
  12936. }
  12937. };
  12938. auto new_ofstream = [&](int index) {
  12939. cur_split = index;
  12940. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  12941. std::string fname = fname_out;
  12942. if (params->keep_split) {
  12943. char split_path[PATH_MAX] = {0};
  12944. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  12945. fname = std::string(split_path);
  12946. }
  12947. fout = std::ofstream(fname, std::ios::binary);
  12948. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  12949. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  12950. // placeholder for the meta data
  12951. ::zeros(fout, meta_size);
  12952. };
  12953. const auto tn = LLM_TN(model.arch);
  12954. new_ofstream(0);
  12955. for (int i = 0; i < ml.n_tensors; ++i) {
  12956. auto weight = ml.get_weight(i);
  12957. struct ggml_tensor * tensor = weight->tensor;
  12958. if (weight->idx != cur_split && params->keep_split) {
  12959. close_ofstream();
  12960. new_ofstream(weight->idx);
  12961. }
  12962. const std::string name = ggml_get_name(tensor);
  12963. if (!ml.use_mmap) {
  12964. if (read_data.size() < ggml_nbytes(tensor)) {
  12965. read_data.resize(ggml_nbytes(tensor));
  12966. }
  12967. tensor->data = read_data.data();
  12968. }
  12969. ml.load_data_for(tensor);
  12970. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  12971. ++idx, ml.n_tensors,
  12972. ggml_get_name(tensor),
  12973. llama_format_tensor_shape(tensor).c_str(),
  12974. ggml_type_name(tensor->type));
  12975. // This used to be a regex, but <regex> has an extreme cost to compile times.
  12976. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  12977. // quantize only 2D and 3D tensors (experts)
  12978. quantize &= (ggml_n_dims(tensor) >= 2);
  12979. // do not quantize norm tensors
  12980. quantize &= name.find("_norm.weight") == std::string::npos;
  12981. quantize &= params->quantize_output_tensor || name != "output.weight";
  12982. quantize &= !params->only_copy;
  12983. // do not quantize expert gating tensors
  12984. // NOTE: can't use LLM_TN here because the layer number is not known
  12985. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  12986. // do not quantize positional embeddings and token types (BERT)
  12987. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  12988. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  12989. // do not quantize Mamba's small yet 2D weights
  12990. // NOTE: can't use LLM_TN here because the layer number is not known
  12991. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  12992. quantize &= name.find("ssm_x.weight") == std::string::npos;
  12993. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  12994. enum ggml_type new_type;
  12995. void * new_data;
  12996. size_t new_size;
  12997. if (quantize) {
  12998. new_type = default_type;
  12999. // get more optimal quantization type based on the tensor shape, layer, etc.
  13000. if (!params->pure && ggml_is_quantized(default_type)) {
  13001. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  13002. }
  13003. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  13004. new_type = params->token_embedding_type;
  13005. }
  13006. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  13007. new_type = params->output_tensor_type;
  13008. }
  13009. // If we've decided to quantize to the same type the tensor is already
  13010. // in then there's nothing to do.
  13011. quantize = tensor->type != new_type;
  13012. }
  13013. if (!quantize) {
  13014. new_type = tensor->type;
  13015. new_data = tensor->data;
  13016. new_size = ggml_nbytes(tensor);
  13017. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  13018. } else {
  13019. const int64_t nelements = ggml_nelements(tensor);
  13020. const float * imatrix = nullptr;
  13021. if (imatrix_data) {
  13022. auto it = imatrix_data->find(tensor->name);
  13023. if (it == imatrix_data->end()) {
  13024. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  13025. } else {
  13026. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  13027. imatrix = it->second.data();
  13028. } else {
  13029. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  13030. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  13031. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  13032. // this is a significant error and it may be good idea to abort the process if this happens,
  13033. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  13034. // tok_embd should be ignored in this case, since it always causes this warning
  13035. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  13036. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  13037. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  13038. }
  13039. }
  13040. }
  13041. }
  13042. if ((new_type == GGML_TYPE_IQ2_XXS ||
  13043. new_type == GGML_TYPE_IQ2_XS ||
  13044. new_type == GGML_TYPE_IQ2_S ||
  13045. new_type == GGML_TYPE_IQ1_S ||
  13046. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  13047. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  13048. LLAMA_LOG_ERROR("\n\n============================================================\n");
  13049. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  13050. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  13051. LLAMA_LOG_ERROR("============================================================\n\n");
  13052. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  13053. }
  13054. float * f32_data;
  13055. if (tensor->type == GGML_TYPE_F32) {
  13056. f32_data = (float *) tensor->data;
  13057. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  13058. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  13059. } else {
  13060. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  13061. f32_data = (float *) f32_conv_buf.data();
  13062. }
  13063. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  13064. fflush(stdout);
  13065. if (work.size() < (size_t)nelements * 4) {
  13066. work.resize(nelements * 4); // upper bound on size
  13067. }
  13068. new_data = work.data();
  13069. const int64_t n_per_row = tensor->ne[0];
  13070. const int64_t nrows = tensor->ne[1];
  13071. static const int64_t min_chunk_size = 32 * 512;
  13072. 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);
  13073. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  13074. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  13075. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  13076. // quantize each expert separately since they have different importance matrices
  13077. new_size = 0;
  13078. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  13079. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  13080. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  13081. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  13082. 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);
  13083. }
  13084. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  13085. }
  13086. total_size_org += ggml_nbytes(tensor);
  13087. total_size_new += new_size;
  13088. // update the gguf meta data as we go
  13089. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  13090. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  13091. // write tensor data + padding
  13092. fout.write((const char *) new_data, new_size);
  13093. zeros(fout, GGML_PAD(new_size, align) - new_size);
  13094. }
  13095. close_ofstream();
  13096. for (auto & c:ctx_outs) {
  13097. gguf_free(c);
  13098. }
  13099. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  13100. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  13101. if (qs.n_fallback > 0) {
  13102. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  13103. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  13104. }
  13105. }
  13106. static int llama_apply_lora_from_file_internal(
  13107. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  13108. ) {
  13109. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  13110. const int64_t t_start_lora_us = ggml_time_us();
  13111. llama_file fin(path_lora, "rb");
  13112. // verify magic and version
  13113. {
  13114. uint32_t magic = fin.read_u32();
  13115. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  13116. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  13117. return 1;
  13118. }
  13119. uint32_t format_version = fin.read_u32();
  13120. if (format_version != 1) {
  13121. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  13122. return 1;
  13123. }
  13124. }
  13125. int32_t lora_r = fin.read_u32();
  13126. int32_t lora_alpha = fin.read_u32();
  13127. float scaling = scale * (float)lora_alpha / (float)lora_r;
  13128. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  13129. // load base model
  13130. std::unique_ptr<llama_model_loader> ml;
  13131. if (path_base_model) {
  13132. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  13133. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*check_tensors*/ false, /*kv_overrides*/ nullptr));
  13134. ml->init_mappings(/*prefetch*/ false); // no prefetching
  13135. }
  13136. struct tensor_meta {
  13137. std::string name;
  13138. ggml_type type;
  13139. int32_t ne[2];
  13140. size_t offset;
  13141. };
  13142. std::map<std::string, tensor_meta> tensor_meta_map;
  13143. // load all tensor meta
  13144. while (true) {
  13145. if (fin.tell() == fin.size) {
  13146. // eof
  13147. break;
  13148. }
  13149. int32_t n_dims;
  13150. int32_t name_len;
  13151. int32_t ftype;
  13152. fin.read_raw(&n_dims, sizeof(n_dims));
  13153. fin.read_raw(&name_len, sizeof(name_len));
  13154. fin.read_raw(&ftype, sizeof(ftype));
  13155. if (n_dims != 1 && n_dims != 2) {
  13156. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  13157. return 1;
  13158. }
  13159. int32_t ne[2] = { 1, 1 };
  13160. for (int i = 0; i < n_dims; ++i) {
  13161. fin.read_raw(&ne[i], sizeof(ne[i]));
  13162. }
  13163. std::string name;
  13164. {
  13165. GGML_ASSERT(name_len < GGML_MAX_NAME);
  13166. char buf[GGML_MAX_NAME];
  13167. fin.read_raw(buf, name_len);
  13168. name = std::string(buf, name_len);
  13169. }
  13170. // check for lora suffix
  13171. std::string lora_suffix;
  13172. if (name.length() > 6) {
  13173. lora_suffix = name.substr(name.length() - 6);
  13174. }
  13175. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  13176. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  13177. return 1;
  13178. }
  13179. // tensor type
  13180. ggml_type wtype;
  13181. switch (ftype) {
  13182. case 0: wtype = GGML_TYPE_F32; break;
  13183. case 1: wtype = GGML_TYPE_F16; break;
  13184. default:
  13185. {
  13186. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  13187. __func__, ftype);
  13188. return 1;
  13189. }
  13190. }
  13191. // data offset
  13192. size_t offset = fin.tell();
  13193. offset = (offset + 31) & -32;
  13194. // skip tensor data
  13195. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  13196. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  13197. }
  13198. bool warned = false;
  13199. int n_tensors = 0;
  13200. // apply
  13201. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  13202. if (backend_cpu == nullptr) {
  13203. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  13204. return 1;
  13205. }
  13206. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  13207. std::vector<no_init<uint8_t>> read_buf;
  13208. for (const auto & it : model.tensors_by_name) {
  13209. const std::string & base_name = it.first;
  13210. ggml_tensor * model_t = it.second;
  13211. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  13212. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  13213. continue;
  13214. }
  13215. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  13216. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  13217. ggml_init_params lora_init_params = {
  13218. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  13219. /* .mem_buffer */ nullptr,
  13220. /* .no_alloc */ true,
  13221. };
  13222. ggml_context * lora_ctx = ggml_init(lora_init_params);
  13223. if (lora_ctx == nullptr) {
  13224. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  13225. ggml_backend_free(backend_cpu);
  13226. return 1;
  13227. }
  13228. // create tensors
  13229. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  13230. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  13231. ggml_set_name(loraA, metaA.name.c_str());
  13232. ggml_set_name(loraB, metaB.name.c_str());
  13233. ggml_tensor * base_t;
  13234. if (ml) {
  13235. if (!ml->get_tensor_meta(base_name.c_str())) {
  13236. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  13237. return 1;
  13238. }
  13239. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  13240. } else {
  13241. base_t = ggml_dup_tensor(lora_ctx, model_t);
  13242. }
  13243. ggml_set_name(base_t, base_name.c_str());
  13244. // allocate in backend buffer
  13245. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  13246. if (lora_buf == nullptr) {
  13247. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  13248. return 1;
  13249. }
  13250. // load tensor data
  13251. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  13252. read_buf.resize(ggml_nbytes(tensor));
  13253. fin.seek(tensor_meta.offset, SEEK_SET);
  13254. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  13255. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  13256. };
  13257. load_tensor(metaA, loraA);
  13258. load_tensor(metaB, loraB);
  13259. // load base model tensor data
  13260. if (ml) {
  13261. ml->load_data_for(base_t);
  13262. } else {
  13263. ggml_backend_tensor_copy(model_t, base_t);
  13264. }
  13265. if (ggml_is_quantized(base_t->type) && !warned) {
  13266. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  13267. "use a f16 or f32 base model with --lora-base\n", __func__);
  13268. warned = true;
  13269. }
  13270. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  13271. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  13272. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  13273. ggml_free(lora_ctx);
  13274. ggml_backend_buffer_free(lora_buf);
  13275. ggml_backend_free(backend_cpu);
  13276. return 1;
  13277. }
  13278. auto build_lora_graph = [&]() {
  13279. // w = w + BA*s
  13280. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  13281. ggml_set_name(BA, "BA");
  13282. if (scaling != 1.0f) {
  13283. BA = ggml_scale(lora_ctx, BA, scaling);
  13284. ggml_set_name(BA, "BA_scaled");
  13285. }
  13286. ggml_tensor * r;
  13287. r = ggml_add_inplace(lora_ctx, base_t, BA);
  13288. ggml_set_name(r, "r_add");
  13289. if (base_t->type != model_t->type) {
  13290. // convert the result to the model type
  13291. r = ggml_cast(lora_ctx, r, model_t->type);
  13292. ggml_set_name(r, "r_cast");
  13293. }
  13294. return r;
  13295. };
  13296. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  13297. ggml_tensor * r = build_lora_graph();
  13298. ggml_build_forward_expand(gf, r);
  13299. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  13300. if (graph_buf == nullptr) {
  13301. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  13302. ggml_free(lora_ctx);
  13303. ggml_backend_buffer_free(lora_buf);
  13304. ggml_backend_free(backend_cpu);
  13305. return 1;
  13306. }
  13307. ggml_backend_graph_compute(backend_cpu, gf);
  13308. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  13309. #if 0
  13310. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  13311. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  13312. // sched compute
  13313. ggml_build_forward_expand(gf, build_graph());
  13314. ggml_backend_sched_init_measure(sched, gf);
  13315. // create the graph again, since the previous one was destroyed by the measure
  13316. ggml_graph_clear(gf);
  13317. ggml_build_forward_expand(gf, build_graph());
  13318. ggml_backend_sched_graph_compute(sched, gf);
  13319. ggml_backend_sched_free(sched);
  13320. #endif
  13321. ggml_backend_buffer_free(lora_buf);
  13322. ggml_backend_buffer_free(graph_buf);
  13323. ggml_free(lora_ctx);
  13324. n_tensors++;
  13325. if (n_tensors % 4 == 0) {
  13326. LLAMA_LOG_INFO(".");
  13327. }
  13328. }
  13329. ggml_backend_free(backend_cpu);
  13330. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  13331. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  13332. return 0;
  13333. }
  13334. //
  13335. // interface implementation
  13336. //
  13337. struct llama_model_params llama_model_default_params() {
  13338. struct llama_model_params result = {
  13339. /*.n_gpu_layers =*/ 0,
  13340. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  13341. /*.main_gpu =*/ 0,
  13342. /*.tensor_split =*/ nullptr,
  13343. /*.rpc_servers =*/ nullptr,
  13344. /*.progress_callback =*/ nullptr,
  13345. /*.progress_callback_user_data =*/ nullptr,
  13346. /*.kv_overrides =*/ nullptr,
  13347. /*.vocab_only =*/ false,
  13348. /*.use_mmap =*/ true,
  13349. /*.use_mlock =*/ false,
  13350. /*.check_tensors =*/ false,
  13351. };
  13352. #ifdef GGML_USE_METAL
  13353. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  13354. result.n_gpu_layers = 999;
  13355. #endif
  13356. return result;
  13357. }
  13358. struct llama_context_params llama_context_default_params() {
  13359. struct llama_context_params result = {
  13360. /*.seed =*/ LLAMA_DEFAULT_SEED,
  13361. /*.n_ctx =*/ 512,
  13362. /*.n_batch =*/ 2048,
  13363. /*.n_ubatch =*/ 512,
  13364. /*.n_seq_max =*/ 1,
  13365. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  13366. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  13367. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  13368. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  13369. /*.rope_freq_base =*/ 0.0f,
  13370. /*.rope_freq_scale =*/ 0.0f,
  13371. /*.yarn_ext_factor =*/ -1.0f,
  13372. /*.yarn_attn_factor =*/ 1.0f,
  13373. /*.yarn_beta_fast =*/ 32.0f,
  13374. /*.yarn_beta_slow =*/ 1.0f,
  13375. /*.yarn_orig_ctx =*/ 0,
  13376. /*.defrag_thold =*/ -1.0f,
  13377. /*.cb_eval =*/ nullptr,
  13378. /*.cb_eval_user_data =*/ nullptr,
  13379. /*.type_k =*/ GGML_TYPE_F16,
  13380. /*.type_v =*/ GGML_TYPE_F16,
  13381. /*.logits_all =*/ false,
  13382. /*.embeddings =*/ false,
  13383. /*.offload_kqv =*/ true,
  13384. /*.flash_attn =*/ false,
  13385. /*.abort_callback =*/ nullptr,
  13386. /*.abort_callback_data =*/ nullptr,
  13387. };
  13388. return result;
  13389. }
  13390. struct llama_model_quantize_params llama_model_quantize_default_params() {
  13391. struct llama_model_quantize_params result = {
  13392. /*.nthread =*/ 0,
  13393. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  13394. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  13395. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  13396. /*.allow_requantize =*/ false,
  13397. /*.quantize_output_tensor =*/ true,
  13398. /*.only_copy =*/ false,
  13399. /*.pure =*/ false,
  13400. /*.keep_split =*/ false,
  13401. /*.imatrix =*/ nullptr,
  13402. /*.kv_overrides =*/ nullptr,
  13403. };
  13404. return result;
  13405. }
  13406. size_t llama_max_devices(void) {
  13407. #if defined(GGML_USE_RPC)
  13408. return GGML_RPC_MAX_SERVERS;
  13409. #elif defined(GGML_USE_METAL)
  13410. return 1;
  13411. #elif defined(GGML_USE_CUDA)
  13412. return GGML_CUDA_MAX_DEVICES;
  13413. #elif defined(GGML_USE_SYCL)
  13414. return GGML_SYCL_MAX_DEVICES;
  13415. #elif defined(GGML_USE_VULKAN)
  13416. return GGML_VK_MAX_DEVICES;
  13417. #else
  13418. return 1;
  13419. #endif
  13420. }
  13421. bool llama_supports_mmap(void) {
  13422. return llama_mmap::SUPPORTED;
  13423. }
  13424. bool llama_supports_mlock(void) {
  13425. return llama_mlock::SUPPORTED;
  13426. }
  13427. bool llama_supports_gpu_offload(void) {
  13428. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  13429. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  13430. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  13431. return true;
  13432. #else
  13433. return false;
  13434. #endif
  13435. }
  13436. void llama_backend_init(void) {
  13437. ggml_time_init();
  13438. // needed to initialize f16 tables
  13439. {
  13440. struct ggml_init_params params = { 0, NULL, false };
  13441. struct ggml_context * ctx = ggml_init(params);
  13442. ggml_free(ctx);
  13443. }
  13444. }
  13445. void llama_numa_init(enum ggml_numa_strategy numa) {
  13446. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  13447. ggml_numa_init(numa);
  13448. }
  13449. }
  13450. void llama_backend_free(void) {
  13451. ggml_quantize_free();
  13452. }
  13453. int64_t llama_time_us(void) {
  13454. return ggml_time_us();
  13455. }
  13456. struct llama_model * llama_load_model_from_file(
  13457. const char * path_model,
  13458. struct llama_model_params params) {
  13459. ggml_time_init();
  13460. llama_model * model = new llama_model;
  13461. unsigned cur_percentage = 0;
  13462. if (params.progress_callback == NULL) {
  13463. params.progress_callback_user_data = &cur_percentage;
  13464. params.progress_callback = [](float progress, void * ctx) {
  13465. unsigned * cur_percentage_p = (unsigned *) ctx;
  13466. unsigned percentage = (unsigned) (100 * progress);
  13467. while (percentage > *cur_percentage_p) {
  13468. *cur_percentage_p = percentage;
  13469. LLAMA_LOG_INFO(".");
  13470. if (percentage >= 100) {
  13471. LLAMA_LOG_INFO("\n");
  13472. }
  13473. }
  13474. return true;
  13475. };
  13476. }
  13477. if (params.rpc_servers != nullptr) {
  13478. // split the servers set them into model->rpc_servers
  13479. std::string servers(params.rpc_servers);
  13480. size_t pos = 0;
  13481. while ((pos = servers.find(",")) != std::string::npos) {
  13482. std::string server = servers.substr(0, pos);
  13483. model->rpc_servers.push_back(server);
  13484. servers.erase(0, pos + 1);
  13485. }
  13486. model->rpc_servers.push_back(servers);
  13487. }
  13488. int status = llama_model_load(path_model, *model, params);
  13489. GGML_ASSERT(status <= 0);
  13490. if (status < 0) {
  13491. if (status == -1) {
  13492. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  13493. } else if (status == -2) {
  13494. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  13495. }
  13496. delete model;
  13497. return nullptr;
  13498. }
  13499. return model;
  13500. }
  13501. void llama_free_model(struct llama_model * model) {
  13502. delete model;
  13503. }
  13504. struct llama_context * llama_new_context_with_model(
  13505. struct llama_model * model,
  13506. struct llama_context_params params) {
  13507. if (!model) {
  13508. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  13509. return nullptr;
  13510. }
  13511. if (params.n_batch == 0 && params.n_ubatch == 0) {
  13512. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  13513. return nullptr;
  13514. }
  13515. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  13516. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  13517. return nullptr;
  13518. }
  13519. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  13520. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  13521. params.flash_attn = false;
  13522. }
  13523. llama_context * ctx = new llama_context(*model);
  13524. const auto & hparams = model->hparams;
  13525. auto & cparams = ctx->cparams;
  13526. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  13527. cparams.n_threads = params.n_threads;
  13528. cparams.n_threads_batch = params.n_threads_batch;
  13529. cparams.yarn_ext_factor = params.yarn_ext_factor;
  13530. cparams.yarn_attn_factor = params.yarn_attn_factor;
  13531. cparams.yarn_beta_fast = params.yarn_beta_fast;
  13532. cparams.yarn_beta_slow = params.yarn_beta_slow;
  13533. cparams.defrag_thold = params.defrag_thold;
  13534. cparams.embeddings = params.embeddings;
  13535. cparams.offload_kqv = params.offload_kqv;
  13536. cparams.flash_attn = params.flash_attn;
  13537. cparams.pooling_type = params.pooling_type;
  13538. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  13539. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  13540. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  13541. // this is necessary due to kv_self.n being padded later during inference
  13542. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  13543. // with causal attention, the batch size is limited by the context size
  13544. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  13545. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  13546. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  13547. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  13548. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  13549. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  13550. cparams.n_batch = GGML_KQ_MASK_PAD;
  13551. }
  13552. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  13553. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  13554. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  13555. hparams.n_ctx_train;
  13556. cparams.cb_eval = params.cb_eval;
  13557. cparams.cb_eval_user_data = params.cb_eval_user_data;
  13558. auto rope_scaling_type = params.rope_scaling_type;
  13559. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  13560. rope_scaling_type = hparams.rope_scaling_type_train;
  13561. }
  13562. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  13563. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  13564. }
  13565. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  13566. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  13567. }
  13568. cparams.yarn_attn_factor *= hparams.rope_attn_factor;
  13569. cparams.causal_attn = hparams.causal_attn;
  13570. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13571. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13572. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  13573. } else {
  13574. cparams.pooling_type = hparams.pooling_type;
  13575. }
  13576. }
  13577. if (params.seed == LLAMA_DEFAULT_SEED) {
  13578. params.seed = time(NULL);
  13579. }
  13580. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  13581. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  13582. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  13583. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  13584. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  13585. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  13586. ctx->abort_callback = params.abort_callback;
  13587. ctx->abort_callback_data = params.abort_callback_data;
  13588. ctx->rng = std::mt19937(params.seed);
  13589. ctx->logits_all = params.logits_all;
  13590. uint32_t kv_size = cparams.n_ctx;
  13591. ggml_type type_k = params.type_k;
  13592. ggml_type type_v = params.type_v;
  13593. // Mamba only needs a constant number of KV cache cells per sequence
  13594. if (model->arch == LLM_ARCH_MAMBA) {
  13595. // Mamba needs at least as many KV cells as there are sequences kept at any time
  13596. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  13597. // it's probably best to keep as much precision as possible for the states
  13598. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  13599. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  13600. }
  13601. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  13602. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  13603. if (!hparams.vocab_only) {
  13604. // initialize backends
  13605. #if defined(GGML_USE_RPC)
  13606. for (auto & server : model->rpc_servers) {
  13607. ggml_backend_t backend = ggml_backend_rpc_init(server.c_str());
  13608. if (backend == nullptr) {
  13609. LLAMA_LOG_ERROR("%s: failed to connect RPC backend to %s\n", __func__, server.c_str());
  13610. llama_free(ctx);
  13611. return nullptr;
  13612. }
  13613. ctx->backends.push_back(backend);
  13614. }
  13615. #elif defined(GGML_USE_METAL)
  13616. if (model->n_gpu_layers > 0) {
  13617. ctx->backend_metal = ggml_backend_metal_init();
  13618. if (ctx->backend_metal == nullptr) {
  13619. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  13620. llama_free(ctx);
  13621. return nullptr;
  13622. }
  13623. ctx->backends.push_back(ctx->backend_metal);
  13624. }
  13625. #elif defined(GGML_USE_CUDA)
  13626. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13627. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13628. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  13629. if (backend == nullptr) {
  13630. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  13631. llama_free(ctx);
  13632. return nullptr;
  13633. }
  13634. ctx->backends.push_back(backend);
  13635. } else {
  13636. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13637. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  13638. ggml_backend_t backend = ggml_backend_cuda_init(device);
  13639. if (backend == nullptr) {
  13640. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  13641. llama_free(ctx);
  13642. return nullptr;
  13643. }
  13644. ctx->backends.push_back(backend);
  13645. }
  13646. }
  13647. #elif defined(GGML_USE_VULKAN)
  13648. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13649. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  13650. llama_free(ctx);
  13651. return nullptr;
  13652. }
  13653. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  13654. ggml_backend_t backend = ggml_backend_vk_init(0);
  13655. if (backend == nullptr) {
  13656. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  13657. llama_free(ctx);
  13658. return nullptr;
  13659. }
  13660. ctx->backends.push_back(backend);
  13661. } else {
  13662. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  13663. ggml_backend_t backend = ggml_backend_vk_init(device);
  13664. if (backend == nullptr) {
  13665. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  13666. llama_free(ctx);
  13667. return nullptr;
  13668. }
  13669. ctx->backends.push_back(backend);
  13670. }
  13671. }
  13672. #elif defined(GGML_USE_SYCL)
  13673. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13674. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13675. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  13676. if (backend == nullptr) {
  13677. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  13678. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  13679. llama_free(ctx);
  13680. return nullptr;
  13681. }
  13682. ctx->backends.push_back(backend);
  13683. } else {
  13684. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  13685. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  13686. ggml_backend_t backend = ggml_backend_sycl_init(i);
  13687. if (backend == nullptr) {
  13688. int id_list[GGML_SYCL_MAX_DEVICES];
  13689. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  13690. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  13691. llama_free(ctx);
  13692. return nullptr;
  13693. }
  13694. ctx->backends.push_back(backend);
  13695. }
  13696. }
  13697. #elif defined(GGML_USE_KOMPUTE)
  13698. if (model->n_gpu_layers > 0) {
  13699. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  13700. if (backend == nullptr) {
  13701. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  13702. llama_free(ctx);
  13703. return nullptr;
  13704. }
  13705. ctx->backends.push_back(backend);
  13706. }
  13707. #endif
  13708. ctx->backend_cpu = ggml_backend_cpu_init();
  13709. if (ctx->backend_cpu == nullptr) {
  13710. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  13711. llama_free(ctx);
  13712. return nullptr;
  13713. }
  13714. ctx->backends.push_back(ctx->backend_cpu);
  13715. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  13716. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  13717. llama_free(ctx);
  13718. return nullptr;
  13719. }
  13720. {
  13721. size_t memory_size_k = 0;
  13722. size_t memory_size_v = 0;
  13723. for (auto & k : ctx->kv_self.k_l) {
  13724. memory_size_k += ggml_nbytes(k);
  13725. }
  13726. for (auto & v : ctx->kv_self.v_l) {
  13727. memory_size_v += ggml_nbytes(v);
  13728. }
  13729. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  13730. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  13731. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  13732. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  13733. }
  13734. // graph outputs buffer
  13735. {
  13736. // resized during inference when a batch uses more outputs
  13737. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  13738. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  13739. llama_free(ctx);
  13740. return nullptr;
  13741. }
  13742. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  13743. ggml_backend_buffer_name(ctx->buf_output),
  13744. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  13745. }
  13746. // scheduler and compute buffers
  13747. {
  13748. // buffer types used for the compute buffer of each backend
  13749. std::vector<ggml_backend_buffer_type_t> backend_buft;
  13750. for (auto * backend : ctx->backends) {
  13751. if (ggml_backend_is_cpu(backend)) {
  13752. // use host buffers for the CPU backend compute buffer
  13753. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  13754. } else {
  13755. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  13756. }
  13757. }
  13758. // buffer used to store the computation graph and the tensor meta data
  13759. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  13760. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  13761. bool pipeline_parallel =
  13762. llama_get_device_count(*model) > 1 &&
  13763. model->n_gpu_layers > (int)model->hparams.n_layer &&
  13764. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  13765. params.offload_kqv;
  13766. #ifndef GGML_USE_CUDA
  13767. // pipeline parallelism requires support for async compute and events
  13768. // currently this is only implemented in the CUDA backend
  13769. pipeline_parallel = false;
  13770. #endif
  13771. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  13772. if (pipeline_parallel) {
  13773. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  13774. }
  13775. // build worst-case graph
  13776. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  13777. int n_past = cparams.n_ctx - n_tokens;
  13778. 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
  13779. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  13780. // initialize scheduler with the worst-case graph
  13781. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  13782. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  13783. llama_free(ctx);
  13784. return nullptr;
  13785. }
  13786. for (size_t i = 0; i < ctx->backends.size(); i++) {
  13787. ggml_backend_t backend = ctx->backends[i];
  13788. ggml_backend_buffer_type_t buft = backend_buft[i];
  13789. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  13790. if (size > 1) {
  13791. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  13792. ggml_backend_buft_name(buft),
  13793. size / 1024.0 / 1024.0);
  13794. }
  13795. }
  13796. // note: the number of splits during measure is higher than during inference due to the kv shift
  13797. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  13798. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  13799. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  13800. }
  13801. }
  13802. return ctx;
  13803. }
  13804. void llama_free(struct llama_context * ctx) {
  13805. delete ctx;
  13806. }
  13807. const llama_model * llama_get_model(const struct llama_context * ctx) {
  13808. return &ctx->model;
  13809. }
  13810. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  13811. return ctx->cparams.n_ctx;
  13812. }
  13813. uint32_t llama_n_batch(const struct llama_context * ctx) {
  13814. return ctx->cparams.n_batch;
  13815. }
  13816. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  13817. return ctx->cparams.n_ubatch;
  13818. }
  13819. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  13820. return ctx->kv_self.size;
  13821. }
  13822. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  13823. return model->vocab.type;
  13824. }
  13825. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  13826. switch (model->arch) {
  13827. // these models do not use RoPE
  13828. case LLM_ARCH_GPT2:
  13829. case LLM_ARCH_GPTJ:
  13830. case LLM_ARCH_MPT:
  13831. case LLM_ARCH_REFACT:
  13832. case LLM_ARCH_BLOOM:
  13833. case LLM_ARCH_MAMBA:
  13834. case LLM_ARCH_JINA_BERT_V2:
  13835. return LLAMA_ROPE_TYPE_NONE;
  13836. // use what we call a normal RoPE, operating on pairs of consecutive head values
  13837. case LLM_ARCH_LLAMA:
  13838. case LLM_ARCH_BAICHUAN:
  13839. case LLM_ARCH_STARCODER:
  13840. case LLM_ARCH_PLAMO:
  13841. case LLM_ARCH_CODESHELL:
  13842. case LLM_ARCH_ORION:
  13843. case LLM_ARCH_INTERNLM2:
  13844. case LLM_ARCH_MINICPM:
  13845. case LLM_ARCH_XVERSE:
  13846. case LLM_ARCH_COMMAND_R:
  13847. case LLM_ARCH_OLMO:
  13848. case LLM_ARCH_ARCTIC:
  13849. case LLM_ARCH_DEEPSEEK2:
  13850. return LLAMA_ROPE_TYPE_NORM;
  13851. // the pairs of head values are offset by n_rot/2
  13852. case LLM_ARCH_FALCON:
  13853. case LLM_ARCH_GROK:
  13854. case LLM_ARCH_DBRX:
  13855. case LLM_ARCH_BERT:
  13856. case LLM_ARCH_NOMIC_BERT:
  13857. case LLM_ARCH_STABLELM:
  13858. case LLM_ARCH_QWEN:
  13859. case LLM_ARCH_QWEN2:
  13860. case LLM_ARCH_QWEN2MOE:
  13861. case LLM_ARCH_PHI2:
  13862. case LLM_ARCH_PHI3:
  13863. case LLM_ARCH_GEMMA:
  13864. case LLM_ARCH_STARCODER2:
  13865. case LLM_ARCH_GPTNEOX:
  13866. return LLAMA_ROPE_TYPE_NEOX;
  13867. // all model arches should be listed explicitly here
  13868. case LLM_ARCH_UNKNOWN:
  13869. GGML_ASSERT(false && "unknown architecture");
  13870. break;
  13871. }
  13872. return LLAMA_ROPE_TYPE_NONE;
  13873. }
  13874. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  13875. return ctx->cparams.pooling_type;
  13876. }
  13877. int32_t llama_n_vocab(const struct llama_model * model) {
  13878. return model->hparams.n_vocab;
  13879. }
  13880. int32_t llama_n_ctx_train(const struct llama_model * model) {
  13881. return model->hparams.n_ctx_train;
  13882. }
  13883. int32_t llama_n_embd(const struct llama_model * model) {
  13884. return model->hparams.n_embd;
  13885. }
  13886. int32_t llama_n_layer(const struct llama_model * model) {
  13887. return model->hparams.n_layer;
  13888. }
  13889. float llama_rope_freq_scale_train(const struct llama_model * model) {
  13890. return model->hparams.rope_freq_scale_train;
  13891. }
  13892. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  13893. const auto & it = model->gguf_kv.find(key);
  13894. if (it == model->gguf_kv.end()) {
  13895. if (buf_size > 0) {
  13896. buf[0] = '\0';
  13897. }
  13898. return -1;
  13899. }
  13900. return snprintf(buf, buf_size, "%s", it->second.c_str());
  13901. }
  13902. int32_t llama_model_meta_count(const struct llama_model * model) {
  13903. return (int)model->gguf_kv.size();
  13904. }
  13905. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  13906. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  13907. if (buf_size > 0) {
  13908. buf[0] = '\0';
  13909. }
  13910. return -1;
  13911. }
  13912. auto it = model->gguf_kv.begin();
  13913. std::advance(it, i);
  13914. return snprintf(buf, buf_size, "%s", it->first.c_str());
  13915. }
  13916. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  13917. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  13918. if (buf_size > 0) {
  13919. buf[0] = '\0';
  13920. }
  13921. return -1;
  13922. }
  13923. auto it = model->gguf_kv.begin();
  13924. std::advance(it, i);
  13925. return snprintf(buf, buf_size, "%s", it->second.c_str());
  13926. }
  13927. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  13928. return snprintf(buf, buf_size, "%s %s %s",
  13929. llama_model_arch_name(model->arch),
  13930. llama_model_type_name(model->type),
  13931. llama_model_ftype_name(model->ftype).c_str());
  13932. }
  13933. uint64_t llama_model_size(const struct llama_model * model) {
  13934. uint64_t size = 0;
  13935. for (const auto & it : model->tensors_by_name) {
  13936. size += ggml_nbytes(it.second);
  13937. }
  13938. return size;
  13939. }
  13940. uint64_t llama_model_n_params(const struct llama_model * model) {
  13941. uint64_t nparams = 0;
  13942. for (const auto & it : model->tensors_by_name) {
  13943. nparams += ggml_nelements(it.second);
  13944. }
  13945. return nparams;
  13946. }
  13947. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  13948. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  13949. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  13950. return it.first == name;
  13951. });
  13952. if (it == model->tensors_by_name.end()) {
  13953. return nullptr;
  13954. }
  13955. return it->second;
  13956. }
  13957. uint32_t llama_model_quantize(
  13958. const char * fname_inp,
  13959. const char * fname_out,
  13960. const llama_model_quantize_params * params) {
  13961. try {
  13962. llama_model_quantize_internal(fname_inp, fname_out, params);
  13963. return 0;
  13964. } catch (const std::exception & err) {
  13965. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  13966. return 1;
  13967. }
  13968. }
  13969. 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) {
  13970. try {
  13971. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  13972. } catch (const std::exception & err) {
  13973. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  13974. return 1;
  13975. }
  13976. }
  13977. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  13978. GGML_ASSERT(cvec.tensors.empty());
  13979. GGML_ASSERT(cvec.ctxs.empty());
  13980. GGML_ASSERT(cvec.bufs.empty());
  13981. // count layer buffer types
  13982. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  13983. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  13984. buft_layer_count[model.buft_layer[i].buft]++;
  13985. }
  13986. // allocate contexts
  13987. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  13988. for (auto & it : buft_layer_count) {
  13989. int n_layers = it.second;
  13990. struct ggml_init_params params = {
  13991. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  13992. /*.mem_buffer =*/ NULL,
  13993. /*.no_alloc =*/ true,
  13994. };
  13995. ggml_context * ctx = ggml_init(params);
  13996. if (!ctx) {
  13997. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  13998. return 1;
  13999. }
  14000. ctx_map[it.first] = ctx;
  14001. }
  14002. // make tensors
  14003. cvec.tensors.reserve(model.hparams.n_layer);
  14004. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  14005. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14006. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  14007. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  14008. cvec.tensors.push_back(tensor);
  14009. }
  14010. // allocate tensors / buffers and zero
  14011. cvec.ctxs.reserve(ctx_map.size());
  14012. cvec.bufs.reserve(ctx_map.size());
  14013. for (auto it : ctx_map) {
  14014. ggml_backend_buffer_type_t buft = it.first;
  14015. ggml_context * ctx = it.second;
  14016. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  14017. if (!buf) {
  14018. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  14019. return false;
  14020. }
  14021. ggml_backend_buffer_clear(buf, 0);
  14022. cvec.ctxs.push_back(ctx);
  14023. cvec.bufs.push_back(buf);
  14024. }
  14025. return true;
  14026. }
  14027. 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) {
  14028. const llama_model & model = lctx->model;
  14029. llama_control_vector & cvec = lctx->cvec;
  14030. if (data == nullptr) {
  14031. // disable the current control vector (but leave allocated for later)
  14032. cvec.layer_start = -1;
  14033. cvec.layer_end = -1;
  14034. return 0;
  14035. }
  14036. if (n_embd != (int) model.hparams.n_embd) {
  14037. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  14038. return 1;
  14039. }
  14040. if (cvec.tensors.empty()) {
  14041. if (!llama_control_vector_init(cvec, model)) {
  14042. return 1;
  14043. }
  14044. }
  14045. cvec.layer_start = il_start;
  14046. cvec.layer_end = il_end;
  14047. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  14048. assert(cvec.tensors[il] != nullptr);
  14049. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  14050. if (off + n_embd <= len) {
  14051. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  14052. }
  14053. }
  14054. return 0;
  14055. }
  14056. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  14057. struct llama_kv_cache_view result = {
  14058. /*.n_cells = */ 0,
  14059. /*.n_seq_max = */ n_seq_max,
  14060. /*.token_count = */ 0,
  14061. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  14062. /*.max_contiguous = */ 0,
  14063. /*.max_contiguous_idx = */ -1,
  14064. /*.cells = */ nullptr,
  14065. /*.cells_sequences = */ nullptr,
  14066. };
  14067. return result;
  14068. }
  14069. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  14070. if (view->cells != nullptr) {
  14071. free(view->cells);
  14072. view->cells = nullptr;
  14073. }
  14074. if (view->cells_sequences != nullptr) {
  14075. free(view->cells_sequences);
  14076. view->cells_sequences = nullptr;
  14077. }
  14078. }
  14079. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  14080. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  14081. view->n_cells = int32_t(ctx->kv_self.size);
  14082. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  14083. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  14084. view->cells = (struct llama_kv_cache_view_cell *)p;
  14085. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  14086. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  14087. view->cells_sequences = (llama_seq_id *)p;
  14088. }
  14089. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  14090. llama_kv_cache_view_cell * c_curr = view->cells;
  14091. llama_seq_id * cs_curr = view->cells_sequences;
  14092. int32_t used_cells = 0;
  14093. int32_t token_count = 0;
  14094. int32_t curr_contig_idx = -1;
  14095. uint32_t max_contig = 0;
  14096. int32_t max_contig_idx = -1;
  14097. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  14098. const size_t curr_size = kv_cells[i].seq_id.size();
  14099. token_count += curr_size;
  14100. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  14101. if (curr_size > 0) {
  14102. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  14103. max_contig = i - curr_contig_idx;
  14104. max_contig_idx = curr_contig_idx;
  14105. }
  14106. curr_contig_idx = -1;
  14107. } else if (curr_contig_idx < 0) {
  14108. curr_contig_idx = i;
  14109. }
  14110. int seq_idx = 0;
  14111. for (const llama_seq_id it : kv_cells[i].seq_id) {
  14112. if (seq_idx >= view->n_seq_max) {
  14113. break;
  14114. }
  14115. cs_curr[seq_idx] = it;
  14116. seq_idx++;
  14117. }
  14118. if (seq_idx != 0) {
  14119. used_cells++;
  14120. }
  14121. for (; seq_idx < view->n_seq_max; seq_idx++) {
  14122. cs_curr[seq_idx] = -1;
  14123. }
  14124. }
  14125. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  14126. max_contig_idx = curr_contig_idx;
  14127. max_contig = kv_cells.size() - curr_contig_idx;
  14128. }
  14129. view->max_contiguous = max_contig;
  14130. view->max_contiguous_idx = max_contig_idx;
  14131. view->token_count = token_count;
  14132. view->used_cells = used_cells;
  14133. if (uint32_t(used_cells) != ctx->kv_self.used) {
  14134. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  14135. __func__, ctx->kv_self.used, used_cells);
  14136. }
  14137. }
  14138. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  14139. int result = 0;
  14140. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  14141. result += ctx->kv_self.cells[i].seq_id.size();
  14142. }
  14143. return result;
  14144. }
  14145. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  14146. return ctx->kv_self.used;
  14147. }
  14148. void llama_kv_cache_clear(struct llama_context * ctx) {
  14149. llama_kv_cache_clear(ctx->kv_self);
  14150. }
  14151. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  14152. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  14153. }
  14154. 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) {
  14155. if (seq_id_src == seq_id_dst) {
  14156. return;
  14157. }
  14158. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  14159. }
  14160. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  14161. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  14162. }
  14163. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  14164. if (delta == 0) {
  14165. return;
  14166. }
  14167. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  14168. }
  14169. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  14170. if (d == 1) {
  14171. return;
  14172. }
  14173. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  14174. }
  14175. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  14176. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  14177. }
  14178. void llama_kv_cache_defrag(struct llama_context * ctx) {
  14179. llama_kv_cache_defrag(ctx->kv_self);
  14180. }
  14181. void llama_kv_cache_update(struct llama_context * ctx) {
  14182. llama_kv_cache_update_internal(*ctx);
  14183. }
  14184. // deprecated
  14185. size_t llama_get_state_size(const struct llama_context * ctx) {
  14186. return llama_state_get_size(ctx);
  14187. }
  14188. // deprecated
  14189. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  14190. return llama_state_get_data(ctx, dst);
  14191. }
  14192. // deprecated
  14193. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  14194. return llama_state_set_data(ctx, src);
  14195. }
  14196. // deprecated
  14197. 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) {
  14198. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14199. }
  14200. // deprecated
  14201. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14202. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  14203. }
  14204. // Returns the *maximum* size of the state
  14205. size_t llama_state_get_size(const struct llama_context * ctx) {
  14206. const auto & cparams = ctx->cparams;
  14207. const auto & hparams = ctx->model.hparams;
  14208. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  14209. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  14210. const size_t s_rng_size = sizeof(size_t);
  14211. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  14212. const size_t s_n_outputs = sizeof(size_t);
  14213. // assume worst case for outputs although only currently set ones are serialized
  14214. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  14215. const size_t s_logits_size = sizeof(size_t);
  14216. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  14217. const size_t s_embedding_size = sizeof(size_t);
  14218. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  14219. const size_t s_kv_buf_size = sizeof(size_t);
  14220. const size_t s_kv_head = sizeof(uint32_t);
  14221. const size_t s_kv_size = sizeof(uint32_t);
  14222. const size_t s_kv_used = sizeof(uint32_t);
  14223. const size_t s_v_trans = sizeof(uint32_t);
  14224. const size_t s_kv = ctx->kv_self.total_size();
  14225. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  14226. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  14227. const size_t s_total = (
  14228. + s_rng_size
  14229. + s_rng
  14230. + s_n_outputs
  14231. + s_output_pos
  14232. + s_logits_size
  14233. + s_logits
  14234. + s_embedding_size
  14235. + s_embedding
  14236. + s_kv_buf_size
  14237. + s_kv_head
  14238. + s_kv_size
  14239. + s_kv_used
  14240. + s_v_trans
  14241. + s_kv
  14242. + s_kv_cells
  14243. );
  14244. // on session change it is very likely that the state size has changed - so we need to update this function
  14245. static_assert(LLAMA_SESSION_VERSION == 6, "So you just bumped the session version - good. But did you remember to update llama_state_get_size?");
  14246. return s_total;
  14247. }
  14248. // llama_context_data
  14249. struct llama_data_context {
  14250. virtual void write(const void * src, size_t size) = 0;
  14251. virtual size_t get_size_written() = 0;
  14252. virtual ~llama_data_context() = default;
  14253. };
  14254. struct llama_data_buffer_context : llama_data_context {
  14255. uint8_t * ptr;
  14256. size_t size_written = 0;
  14257. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  14258. void write(const void * src, size_t size) override {
  14259. memcpy(ptr, src, size);
  14260. ptr += size;
  14261. size_written += size;
  14262. }
  14263. size_t get_size_written() override {
  14264. return size_written;
  14265. }
  14266. };
  14267. struct llama_data_file_context : llama_data_context {
  14268. llama_file * file;
  14269. size_t size_written = 0;
  14270. llama_data_file_context(llama_file * f) : file(f) {}
  14271. void write(const void * src, size_t size) override {
  14272. file->write_raw(src, size);
  14273. size_written += size;
  14274. }
  14275. size_t get_size_written() override {
  14276. return size_written;
  14277. }
  14278. };
  14279. /** copy state data into either a buffer or file depending on the passed in context
  14280. *
  14281. * file context:
  14282. * llama_file file("/path", "wb");
  14283. * llama_data_file_context data_ctx(&file);
  14284. * llama_state_get_data(ctx, &data_ctx);
  14285. *
  14286. * buffer context:
  14287. * std::vector<uint8_t> buf(max_size, 0);
  14288. * llama_data_buffer_context data_ctx(&buf.data());
  14289. * llama_state_get_data(ctx, &data_ctx);
  14290. *
  14291. */
  14292. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  14293. llama_synchronize(ctx);
  14294. // copy rng
  14295. {
  14296. std::ostringstream rng_ss;
  14297. rng_ss << ctx->rng;
  14298. const std::string & rng_str = rng_ss.str();
  14299. const size_t rng_size = rng_str.size();
  14300. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  14301. data_ctx->write(&rng_size, sizeof(rng_size));
  14302. data_ctx->write(rng_str.data(), rng_size);
  14303. }
  14304. // copy outputs
  14305. {
  14306. // Can't use ctx->n_outputs because it's not for the
  14307. // entire last batch when n_ubatch is smaller than n_batch
  14308. size_t n_outputs = 0;
  14309. // copy output ids
  14310. {
  14311. std::vector<int32_t> output_pos;
  14312. const size_t n_batch = ctx->cparams.n_batch;
  14313. const auto & output_ids = ctx->output_ids;
  14314. output_pos.resize(ctx->output_size);
  14315. // build a more compact representation of the output ids
  14316. for (size_t i = 0; i < n_batch; ++i) {
  14317. // map an output id to a position in the batch
  14318. int32_t pos = output_ids[i];
  14319. if (pos >= 0) {
  14320. if ((size_t) pos >= n_outputs) {
  14321. n_outputs = pos + 1;
  14322. }
  14323. GGML_ASSERT((size_t) pos < ctx->output_size);
  14324. output_pos[pos] = i;
  14325. }
  14326. }
  14327. data_ctx->write(&n_outputs, sizeof(n_outputs));
  14328. if (n_outputs) {
  14329. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  14330. }
  14331. }
  14332. // copy logits
  14333. {
  14334. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  14335. data_ctx->write(&logits_size, sizeof(logits_size));
  14336. if (logits_size) {
  14337. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  14338. }
  14339. }
  14340. // copy embeddings
  14341. {
  14342. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  14343. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  14344. if (embeddings_size) {
  14345. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  14346. }
  14347. }
  14348. }
  14349. // copy kv cache
  14350. {
  14351. const auto & kv_self = ctx->kv_self;
  14352. const auto & hparams = ctx->model.hparams;
  14353. const uint32_t n_layer = hparams.n_layer;
  14354. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14355. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14356. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  14357. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  14358. const uint32_t kv_size = kv_self.size;
  14359. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  14360. const uint32_t kv_used = kv_self.used;
  14361. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  14362. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  14363. data_ctx->write(&kv_head, sizeof(kv_head));
  14364. data_ctx->write(&kv_size, sizeof(kv_size));
  14365. data_ctx->write(&kv_used, sizeof(kv_used));
  14366. data_ctx->write(&v_trans, sizeof(v_trans));
  14367. if (kv_buf_size) {
  14368. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  14369. std::vector<uint8_t> tmp_buf;
  14370. for (int il = 0; il < (int) n_layer; ++il) {
  14371. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  14372. tmp_buf.resize(k_size);
  14373. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  14374. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  14375. if (kv_self.recurrent || !kv_self.v_trans) {
  14376. // v is contiguous for recurrent models
  14377. // TODO: use other tensors for state models than k and v
  14378. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  14379. tmp_buf.resize(v_size);
  14380. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  14381. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  14382. continue;
  14383. }
  14384. // v is not contiguous, copy row by row
  14385. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  14386. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  14387. tmp_buf.resize(v_row_size);
  14388. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  14389. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  14390. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  14391. }
  14392. }
  14393. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  14394. }
  14395. for (uint32_t i = 0; i < kv_head; ++i) {
  14396. const auto & cell = kv_self.cells[i];
  14397. const llama_pos pos = cell.pos;
  14398. const size_t seq_id_size = cell.seq_id.size();
  14399. data_ctx->write(&pos, sizeof(pos));
  14400. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  14401. for (auto seq_id : cell.seq_id) {
  14402. data_ctx->write(&seq_id, sizeof(seq_id));
  14403. }
  14404. }
  14405. }
  14406. }
  14407. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  14408. llama_data_buffer_context data_ctx(dst);
  14409. llama_state_get_data_internal(ctx, &data_ctx);
  14410. return data_ctx.get_size_written();
  14411. }
  14412. // Sets the state reading from the specified source address
  14413. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  14414. llama_synchronize(ctx);
  14415. const uint8_t * inp = src;
  14416. // set rng
  14417. {
  14418. size_t rng_size;
  14419. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  14420. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  14421. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  14422. std::istringstream rng_ss(rng_str);
  14423. rng_ss >> ctx->rng;
  14424. GGML_ASSERT(!rng_ss.fail());
  14425. }
  14426. // set output ids
  14427. {
  14428. size_t n_outputs;
  14429. std::vector<int32_t> output_pos;
  14430. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  14431. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  14432. if (n_outputs) {
  14433. output_pos.resize(n_outputs);
  14434. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  14435. inp += n_outputs * sizeof(int32_t);
  14436. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  14437. int32_t id = output_pos[i];
  14438. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  14439. ctx->output_ids[id] = i;
  14440. }
  14441. ctx->n_outputs = n_outputs;
  14442. }
  14443. }
  14444. // set logits
  14445. {
  14446. size_t logits_size;
  14447. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  14448. GGML_ASSERT(ctx->logits_size >= logits_size);
  14449. if (logits_size) {
  14450. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  14451. inp += logits_size * sizeof(float);
  14452. }
  14453. }
  14454. // set embeddings
  14455. {
  14456. size_t embeddings_size;
  14457. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  14458. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  14459. if (embeddings_size) {
  14460. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  14461. inp += embeddings_size * sizeof(float);
  14462. }
  14463. }
  14464. // set kv cache
  14465. {
  14466. const auto & kv_self = ctx->kv_self;
  14467. const auto & hparams = ctx->model.hparams;
  14468. const uint32_t n_layer = hparams.n_layer;
  14469. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14470. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14471. size_t kv_buf_size;
  14472. uint32_t kv_head;
  14473. uint32_t kv_size;
  14474. uint32_t kv_used;
  14475. uint32_t v_trans;
  14476. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  14477. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  14478. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  14479. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  14480. memcpy(&v_trans, inp, sizeof(v_trans)); inp += sizeof(v_trans);
  14481. GGML_ASSERT(kv_self.v_trans == (bool) v_trans); // incompatible V transposition
  14482. if (kv_self.size != kv_size) {
  14483. // the KV cache needs to be big enough to load all the KV cells from the saved state
  14484. GGML_ASSERT(kv_self.size >= kv_head);
  14485. LLAMA_LOG_INFO("%s: state contains %d KV cells, was saved with kv_size=%d, but is loaded with kv_size=%d (fine, but different)\n",
  14486. __func__, kv_head, kv_size, kv_self.size);
  14487. }
  14488. llama_kv_cache_clear(ctx);
  14489. if (kv_buf_size) {
  14490. const size_t pre_kv_buf_size = inp - src;
  14491. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  14492. for (int il = 0; il < (int) n_layer; ++il) {
  14493. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  14494. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  14495. inp += k_size;
  14496. if (kv_self.recurrent || !kv_self.v_trans) {
  14497. // v is contiguous for recurrent models
  14498. // TODO: use other tensors for state models than k and v
  14499. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  14500. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  14501. inp += v_size;
  14502. continue;
  14503. }
  14504. // v is not contiguous, copy row by row
  14505. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  14506. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  14507. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  14508. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  14509. inp += v_row_size;
  14510. }
  14511. }
  14512. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  14513. }
  14514. ctx->kv_self.head = kv_head;
  14515. ctx->kv_self.used = kv_used;
  14516. for (uint32_t i = 0; i < kv_head; ++i) {
  14517. llama_pos pos;
  14518. size_t seq_id_size;
  14519. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  14520. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  14521. ctx->kv_self.cells[i].pos = pos;
  14522. llama_seq_id seq_id;
  14523. for (size_t j = 0; j < seq_id_size; ++j) {
  14524. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  14525. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  14526. }
  14527. }
  14528. }
  14529. const size_t nread = inp - src;
  14530. const size_t max_size = llama_state_get_size(ctx);
  14531. GGML_ASSERT(nread <= max_size);
  14532. return nread;
  14533. }
  14534. 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) {
  14535. llama_file file(path_session, "rb");
  14536. // sanity checks
  14537. {
  14538. const uint32_t magic = file.read_u32();
  14539. const uint32_t version = file.read_u32();
  14540. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  14541. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  14542. return false;
  14543. }
  14544. llama_hparams session_hparams;
  14545. file.read_raw(&session_hparams, sizeof(llama_hparams));
  14546. if (session_hparams != ctx->model.hparams) {
  14547. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  14548. return false;
  14549. }
  14550. }
  14551. // load the prompt
  14552. {
  14553. const uint32_t n_token_count = file.read_u32();
  14554. if (n_token_count > n_token_capacity) {
  14555. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  14556. return false;
  14557. }
  14558. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  14559. *n_token_count_out = n_token_count;
  14560. }
  14561. // restore the context state
  14562. {
  14563. const size_t n_state_size_cur = file.size - file.tell();
  14564. const size_t n_state_size_max = llama_state_get_size(ctx);
  14565. if (n_state_size_cur > n_state_size_max) {
  14566. LLAMA_LOG_ERROR("%s : the state size in session file is too big! max %zu, got %zu\n", __func__, n_state_size_max, n_state_size_cur);
  14567. return false;
  14568. }
  14569. std::vector<uint8_t> state_data(n_state_size_max);
  14570. file.read_raw(state_data.data(), n_state_size_cur);
  14571. llama_state_set_data(ctx, state_data.data());
  14572. }
  14573. return true;
  14574. }
  14575. 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) {
  14576. try {
  14577. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14578. } catch (const std::exception & err) {
  14579. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  14580. return false;
  14581. }
  14582. }
  14583. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14584. llama_file file(path_session, "wb");
  14585. file.write_u32(LLAMA_SESSION_MAGIC);
  14586. file.write_u32(LLAMA_SESSION_VERSION);
  14587. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  14588. // save the prompt
  14589. file.write_u32((uint32_t) n_token_count);
  14590. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  14591. // save the context state using stream saving
  14592. llama_data_file_context data_ctx(&file);
  14593. llama_state_get_data_internal(ctx, &data_ctx);
  14594. return true;
  14595. }
  14596. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14597. try {
  14598. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  14599. } catch (const std::exception & err) {
  14600. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  14601. return false;
  14602. }
  14603. }
  14604. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  14605. // save the size of size_t as a uint32_t for safety check
  14606. const size_t size_t_size_size = sizeof(uint32_t);
  14607. // other values
  14608. const size_t s_cell_count_size = sizeof(uint32_t);
  14609. const size_t s_layer_count_size = sizeof(uint32_t);
  14610. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  14611. size_t s_cell_count = 0;
  14612. size_t s_cell_data_size = 0;
  14613. const auto & kv_self = ctx->kv_self;
  14614. const auto & hparams = ctx->model.hparams;
  14615. const uint32_t n_layer = hparams.n_layer;
  14616. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14617. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14618. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14619. const auto & cell = kv_self.cells[i];
  14620. if (cell.seq_id.count(seq_id) > 0) {
  14621. ++s_cell_count;
  14622. s_cell_data_size += sizeof(llama_pos);
  14623. }
  14624. }
  14625. for (int il = 0; il < (int)n_layer; ++il) {
  14626. // types of keys and values
  14627. s_cell_data_size += sizeof(int32_t) * 2;
  14628. // k_size_row and v_size_el values of layer
  14629. s_cell_data_size += sizeof(size_t) * 2;
  14630. // keys
  14631. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14632. s_cell_data_size += k_size_row * s_cell_count;
  14633. // values (transposed)
  14634. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14635. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  14636. }
  14637. const size_t s_total = (
  14638. size_t_size_size +
  14639. s_cell_count_size +
  14640. s_layer_count_size +
  14641. n_embd_v_gqa_size +
  14642. s_cell_data_size
  14643. );
  14644. return s_total;
  14645. }
  14646. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  14647. llama_synchronize(ctx);
  14648. const auto & kv_self = ctx->kv_self;
  14649. GGML_ASSERT(!kv_self.recurrent); // not implemented
  14650. // Save the size of size_t as a uint32_t for safety check
  14651. const uint32_t size_t_size = sizeof(size_t);
  14652. data_ctx.write(&size_t_size, sizeof(size_t_size));
  14653. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  14654. uint32_t cell_count = 0;
  14655. // Count the number of cells with the specified seq_id
  14656. // Find all the ranges of cells with this seq id
  14657. {
  14658. uint32_t cell_range_begin = kv_self.size;
  14659. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14660. const auto & cell = kv_self.cells[i];
  14661. if (cell.has_seq_id(seq_id)) {
  14662. ++cell_count;
  14663. if (cell_range_begin == kv_self.size) {
  14664. cell_range_begin = i;
  14665. }
  14666. }
  14667. else {
  14668. if (cell_range_begin != kv_self.size) {
  14669. cell_ranges.emplace_back(cell_range_begin, i);
  14670. cell_range_begin = kv_self.size;
  14671. }
  14672. }
  14673. }
  14674. if (cell_range_begin != kv_self.size) {
  14675. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  14676. }
  14677. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  14678. uint32_t cell_count_check = 0;
  14679. for (const auto & range : cell_ranges) {
  14680. cell_count_check += range.second - range.first;
  14681. }
  14682. GGML_ASSERT(cell_count == cell_count_check);
  14683. }
  14684. // Write the cell count
  14685. data_ctx.write(&cell_count, sizeof(cell_count));
  14686. const auto & hparams = ctx->model.hparams;
  14687. const uint32_t n_layer = hparams.n_layer;
  14688. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14689. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14690. // Write the layer count
  14691. data_ctx.write(&n_layer, sizeof(n_layer));
  14692. // Write n_embd_v_gqa
  14693. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  14694. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  14695. for (const auto & range : cell_ranges) {
  14696. for (uint32_t i = range.first; i < range.second; ++i) {
  14697. const auto & cell = kv_self.cells[i];
  14698. data_ctx.write(&cell.pos, sizeof(cell.pos));
  14699. }
  14700. }
  14701. // Iterate and write all the keys first, each row is a cell
  14702. // Get whole range at a time
  14703. std::vector<uint8_t> tmp_buf;
  14704. for (int il = 0; il < (int)n_layer; ++il) {
  14705. // Write key type
  14706. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14707. data_ctx.write(&k_type_i, sizeof(k_type_i));
  14708. // Write row size of key
  14709. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14710. data_ctx.write(&k_size_row, sizeof(k_size_row));
  14711. // Read each range of cells of k_size length each into tmp_buf and write out
  14712. for (const auto & range : cell_ranges) {
  14713. const size_t range_size = range.second - range.first;
  14714. tmp_buf.resize(range_size * k_size_row);
  14715. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  14716. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14717. }
  14718. }
  14719. // TODO: simplify, reduce copy-paste
  14720. if (!kv_self.v_trans) {
  14721. for (int il = 0; il < (int)n_layer; ++il) {
  14722. // Write value type
  14723. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14724. data_ctx.write(&v_type_i, sizeof(v_type_i));
  14725. // Write row size of value
  14726. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14727. data_ctx.write(&v_size_row, sizeof(v_size_row));
  14728. // Read each range of cells of v_size length each into tmp_buf and write out
  14729. for (const auto & range : cell_ranges) {
  14730. const size_t range_size = range.second - range.first;
  14731. tmp_buf.resize(range_size * v_size_row);
  14732. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), range.first * v_size_row, range_size * v_size_row);
  14733. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14734. }
  14735. }
  14736. } else {
  14737. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  14738. const uint32_t kv_size = kv_self.size;
  14739. for (int il = 0; il < (int)n_layer; ++il) {
  14740. // Write value type
  14741. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14742. data_ctx.write(&v_type_i, sizeof(v_type_i));
  14743. // Write element size
  14744. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14745. data_ctx.write(&v_size_el, sizeof(v_size_el));
  14746. // For each row, we get the element values of each cell
  14747. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14748. // Read each range of cells of v_size_el length each into tmp_buf and write out
  14749. for (const auto & range : cell_ranges) {
  14750. const size_t range_size = range.second - range.first;
  14751. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  14752. tmp_buf.resize(range_size * v_size_el);
  14753. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  14754. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14755. }
  14756. }
  14757. }
  14758. }
  14759. return data_ctx.get_size_written();
  14760. }
  14761. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  14762. llama_data_buffer_context data_ctx(dst);
  14763. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  14764. }
  14765. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  14766. llama_synchronize(ctx);
  14767. auto & kv_self = ctx->kv_self;
  14768. GGML_ASSERT(!kv_self.recurrent); // not implemented
  14769. // Wipe the slot
  14770. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14771. const uint8_t * inp = src;
  14772. // Read size of size_t
  14773. uint32_t size_t_size;
  14774. memcpy(&size_t_size, inp, sizeof(size_t_size));
  14775. inp += sizeof(size_t_size);
  14776. if (size_t_size != sizeof(size_t)) {
  14777. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  14778. return 0;
  14779. }
  14780. // Read the cell count
  14781. uint32_t cell_count;
  14782. memcpy(&cell_count, inp, sizeof(cell_count));
  14783. inp += sizeof(cell_count);
  14784. // Read the layer count
  14785. uint32_t n_layer_ref;
  14786. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  14787. inp += sizeof(n_layer_ref);
  14788. // Read n_embd_v_gqa
  14789. uint32_t n_embd_v_gqa_ref;
  14790. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  14791. inp += sizeof(n_embd_v_gqa_ref);
  14792. // Sanity check model compatibility
  14793. const auto & hparams = ctx->model.hparams;
  14794. const uint32_t n_layer = hparams.n_layer;
  14795. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14796. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14797. if (n_layer != n_layer_ref) {
  14798. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  14799. return 0;
  14800. }
  14801. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  14802. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  14803. return 0;
  14804. }
  14805. // Allocate the new cells for the slot
  14806. if (cell_count) {
  14807. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  14808. batch.n_tokens = cell_count;
  14809. for (uint32_t i = 0; i < cell_count; ++i) {
  14810. llama_pos pos;
  14811. memcpy(&pos, inp, sizeof(pos));
  14812. inp += sizeof(pos);
  14813. batch.pos[i] = pos;
  14814. batch.n_seq_id[i] = 1;
  14815. batch.seq_id[i][0] = dest_seq_id;
  14816. }
  14817. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  14818. llama_batch_free(batch);
  14819. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  14820. return 0;
  14821. }
  14822. // 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)
  14823. // Assume that this is one contiguous block of cells
  14824. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  14825. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  14826. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  14827. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  14828. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  14829. // Cleanup
  14830. llama_batch_free(batch);
  14831. }
  14832. const uint32_t kv_size = kv_self.size;
  14833. const uint32_t kv_head = kv_self.head;
  14834. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  14835. for (int il = 0; il < (int)n_layer; ++il) {
  14836. // Read type of key
  14837. int32_t k_type_i_ref;
  14838. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  14839. inp += sizeof(k_type_i_ref);
  14840. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14841. if (k_type_i != k_type_i_ref) {
  14842. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14843. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  14844. return 0;
  14845. }
  14846. // Read row size of key
  14847. size_t k_size_row_ref;
  14848. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  14849. inp += sizeof(k_size_row_ref);
  14850. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14851. if (k_size_row != k_size_row_ref) {
  14852. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14853. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  14854. return 0;
  14855. }
  14856. if (cell_count) {
  14857. // Read and set the keys for the whole cell range
  14858. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  14859. inp += cell_count * k_size_row;
  14860. }
  14861. }
  14862. // TODO: simplify, reduce copy-paste
  14863. if (!kv_self.v_trans) {
  14864. for (int il = 0; il < (int)n_layer; ++il) {
  14865. // Read type of value
  14866. int32_t v_type_i_ref;
  14867. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  14868. inp += sizeof(v_type_i_ref);
  14869. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14870. if (v_type_i != v_type_i_ref) {
  14871. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14872. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14873. return 0;
  14874. }
  14875. // Read row size of value
  14876. size_t v_size_row_ref;
  14877. memcpy(&v_size_row_ref, inp, sizeof(v_size_row_ref));
  14878. inp += sizeof(v_size_row_ref);
  14879. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14880. if (v_size_row != v_size_row_ref) {
  14881. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14882. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, v_size_row_ref, il);
  14883. return 0;
  14884. }
  14885. if (cell_count) {
  14886. // Read and set the values for the whole cell range
  14887. ggml_backend_tensor_set(kv_self.v_l[il], inp, kv_head * v_size_row, cell_count * v_size_row);
  14888. inp += cell_count * v_size_row;
  14889. }
  14890. }
  14891. } else {
  14892. // For each layer, read the values for each cell (transposed)
  14893. for (int il = 0; il < (int)n_layer; ++il) {
  14894. // Read type of value
  14895. int32_t v_type_i_ref;
  14896. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  14897. inp += sizeof(v_type_i_ref);
  14898. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14899. if (v_type_i != v_type_i_ref) {
  14900. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14901. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14902. return 0;
  14903. }
  14904. // Read element size of value
  14905. size_t v_size_el_ref;
  14906. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  14907. inp += sizeof(v_size_el_ref);
  14908. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14909. if (v_size_el != v_size_el_ref) {
  14910. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14911. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  14912. return 0;
  14913. }
  14914. if (cell_count) {
  14915. // For each row in the transposed matrix, read the values for the whole cell range
  14916. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14917. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  14918. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  14919. inp += cell_count * v_size_el;
  14920. }
  14921. }
  14922. }
  14923. }
  14924. const size_t nread = inp - src;
  14925. return nread;
  14926. }
  14927. 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) {
  14928. llama_file file(filepath, "wb");
  14929. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  14930. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  14931. // save the prompt
  14932. file.write_u32((uint32_t)n_token_count);
  14933. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  14934. // save the context state using stream saving
  14935. llama_data_file_context data_ctx(&file);
  14936. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  14937. const size_t res = file.tell();
  14938. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  14939. return res;
  14940. }
  14941. 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) {
  14942. llama_file file(filepath, "rb");
  14943. // version checks
  14944. {
  14945. const uint32_t magic = file.read_u32();
  14946. const uint32_t version = file.read_u32();
  14947. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  14948. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  14949. return 0;
  14950. }
  14951. }
  14952. // load the prompt
  14953. {
  14954. const uint32_t n_token_count = file.read_u32();
  14955. if (n_token_count > n_token_capacity) {
  14956. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  14957. return 0;
  14958. }
  14959. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  14960. *n_token_count_out = n_token_count;
  14961. }
  14962. // restore the context state
  14963. {
  14964. const size_t state_size = file.size - file.tell();
  14965. std::vector<uint8_t> state_data(state_size);
  14966. file.read_raw(state_data.data(), state_size);
  14967. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  14968. if (!nread) {
  14969. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  14970. return 0;
  14971. }
  14972. GGML_ASSERT(nread <= state_size);
  14973. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  14974. }
  14975. return file.tell();
  14976. }
  14977. 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) {
  14978. try {
  14979. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  14980. } catch (const std::exception & err) {
  14981. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  14982. return 0;
  14983. }
  14984. }
  14985. 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) {
  14986. try {
  14987. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  14988. } catch (const std::exception & err) {
  14989. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  14990. return 0;
  14991. }
  14992. }
  14993. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  14994. ctx->cparams.n_threads = n_threads;
  14995. ctx->cparams.n_threads_batch = n_threads_batch;
  14996. }
  14997. uint32_t llama_n_threads(struct llama_context * ctx) {
  14998. return ctx->cparams.n_threads;
  14999. }
  15000. uint32_t llama_n_threads_batch(struct llama_context * ctx) {
  15001. return ctx->cparams.n_threads_batch;
  15002. }
  15003. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  15004. ctx->abort_callback = abort_callback;
  15005. ctx->abort_callback_data = abort_callback_data;
  15006. }
  15007. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  15008. ctx->cparams.causal_attn = causal_attn;
  15009. }
  15010. struct llama_batch llama_batch_get_one(
  15011. llama_token * tokens,
  15012. int32_t n_tokens,
  15013. llama_pos pos_0,
  15014. llama_seq_id seq_id) {
  15015. return {
  15016. /*n_tokens =*/ n_tokens,
  15017. /*tokens =*/ tokens,
  15018. /*embd =*/ nullptr,
  15019. /*pos =*/ nullptr,
  15020. /*n_seq_id =*/ nullptr,
  15021. /*seq_id =*/ nullptr,
  15022. /*logits =*/ nullptr,
  15023. /*all_pos_0 =*/ pos_0,
  15024. /*all_pos_1 =*/ 1,
  15025. /*all_seq_id =*/ seq_id,
  15026. };
  15027. }
  15028. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  15029. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  15030. if (embd) {
  15031. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  15032. } else {
  15033. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  15034. }
  15035. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  15036. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  15037. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  15038. for (int i = 0; i < n_tokens_alloc; ++i) {
  15039. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  15040. }
  15041. batch.seq_id[n_tokens_alloc] = nullptr;
  15042. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  15043. return batch;
  15044. }
  15045. void llama_batch_free(struct llama_batch batch) {
  15046. if (batch.token) free(batch.token);
  15047. if (batch.embd) free(batch.embd);
  15048. if (batch.pos) free(batch.pos);
  15049. if (batch.n_seq_id) free(batch.n_seq_id);
  15050. if (batch.seq_id) {
  15051. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  15052. free(batch.seq_id[i]);
  15053. }
  15054. free(batch.seq_id);
  15055. }
  15056. if (batch.logits) free(batch.logits);
  15057. }
  15058. int32_t llama_decode(
  15059. struct llama_context * ctx,
  15060. struct llama_batch batch) {
  15061. const int ret = llama_decode_internal(*ctx, batch);
  15062. if (ret < 0) {
  15063. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  15064. }
  15065. return ret;
  15066. }
  15067. void llama_synchronize(struct llama_context * ctx) {
  15068. ggml_backend_sched_synchronize(ctx->sched);
  15069. // FIXME: if multiple single tokens are evaluated without a synchronization,
  15070. // the stats will be added to the prompt evaluation stats
  15071. // this should only happen when using batch size 1 to evaluate a batch
  15072. // add the evaluation to the stats
  15073. if (ctx->n_queued_tokens == 1) {
  15074. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15075. ctx->n_eval++;
  15076. } else if (ctx->n_queued_tokens > 1) {
  15077. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  15078. ctx->n_p_eval += ctx->n_queued_tokens;
  15079. }
  15080. // get a more accurate load time, upon first eval
  15081. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  15082. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  15083. ctx->has_evaluated_once = true;
  15084. }
  15085. ctx->n_queued_tokens = 0;
  15086. ctx->t_compute_start_us = 0;
  15087. }
  15088. float * llama_get_logits(struct llama_context * ctx) {
  15089. llama_synchronize(ctx);
  15090. return ctx->logits;
  15091. }
  15092. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  15093. int32_t j = -1;
  15094. llama_synchronize(ctx);
  15095. try {
  15096. if (ctx->logits == nullptr) {
  15097. throw std::runtime_error("no logits");
  15098. }
  15099. if (i < 0) {
  15100. j = ctx->n_outputs + i;
  15101. if (j < 0) {
  15102. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15103. }
  15104. } else if ((size_t) i >= ctx->output_ids.size()) {
  15105. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15106. } else {
  15107. j = ctx->output_ids[i];
  15108. }
  15109. if (j < 0) {
  15110. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15111. }
  15112. if (j >= ctx->n_outputs) {
  15113. // This should not happen
  15114. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15115. }
  15116. return ctx->logits + j*ctx->model.hparams.n_vocab;
  15117. } catch (const std::exception & err) {
  15118. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  15119. #ifndef NDEBUG
  15120. GGML_ASSERT(false);
  15121. #endif
  15122. return nullptr;
  15123. }
  15124. }
  15125. float * llama_get_embeddings(struct llama_context * ctx) {
  15126. llama_synchronize(ctx);
  15127. return ctx->embd;
  15128. }
  15129. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  15130. int32_t j = -1;
  15131. llama_synchronize(ctx);
  15132. try {
  15133. if (ctx->embd == nullptr) {
  15134. throw std::runtime_error("no embeddings");
  15135. }
  15136. if (i < 0) {
  15137. j = ctx->n_outputs + i;
  15138. if (j < 0) {
  15139. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  15140. }
  15141. } else if ((size_t) i >= ctx->output_ids.size()) {
  15142. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  15143. } else {
  15144. j = ctx->output_ids[i];
  15145. }
  15146. if (j < 0) {
  15147. throw std::runtime_error(format("batch.logits[%d] != true", i));
  15148. }
  15149. if (j >= ctx->n_outputs) {
  15150. // This should not happen
  15151. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  15152. }
  15153. return ctx->embd + j*ctx->model.hparams.n_embd;
  15154. } catch (const std::exception & err) {
  15155. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  15156. #ifndef NDEBUG
  15157. GGML_ASSERT(false);
  15158. #endif
  15159. return nullptr;
  15160. }
  15161. }
  15162. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  15163. llama_synchronize(ctx);
  15164. auto it = ctx->embd_seq.find(seq_id);
  15165. if (it == ctx->embd_seq.end()) {
  15166. return nullptr;
  15167. }
  15168. return it->second.data();
  15169. }
  15170. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  15171. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  15172. return model->vocab.id_to_token[token].text.c_str();
  15173. }
  15174. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  15175. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  15176. return model->vocab.id_to_token[token].score;
  15177. }
  15178. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  15179. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  15180. return model->vocab.id_to_token[token].type;
  15181. }
  15182. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  15183. return token != -1 && (
  15184. token == llama_token_eos(model) ||
  15185. token == llama_token_eot(model)
  15186. );
  15187. }
  15188. bool llama_token_is_control(const struct llama_model * model, llama_token token) {
  15189. return llama_is_control_token(model->vocab, token);
  15190. }
  15191. llama_token llama_token_bos(const struct llama_model * model) {
  15192. return model->vocab.special_bos_id;
  15193. }
  15194. llama_token llama_token_eos(const struct llama_model * model) {
  15195. return model->vocab.special_eos_id;
  15196. }
  15197. llama_token llama_token_cls(const struct llama_model * model) {
  15198. return model->vocab.special_cls_id;
  15199. }
  15200. llama_token llama_token_sep(const struct llama_model * model) {
  15201. return model->vocab.special_sep_id;
  15202. }
  15203. llama_token llama_token_nl(const struct llama_model * model) {
  15204. return model->vocab.linefeed_id;
  15205. }
  15206. int32_t llama_add_bos_token(const struct llama_model * model) {
  15207. return model->vocab.special_add_bos;
  15208. }
  15209. int32_t llama_add_eos_token(const struct llama_model * model) {
  15210. return model->vocab.special_add_eos;
  15211. }
  15212. llama_token llama_token_prefix(const struct llama_model * model) {
  15213. return model->vocab.special_prefix_id;
  15214. }
  15215. llama_token llama_token_middle(const struct llama_model * model) {
  15216. return model->vocab.special_middle_id;
  15217. }
  15218. llama_token llama_token_suffix(const struct llama_model * model) {
  15219. return model->vocab.special_suffix_id;
  15220. }
  15221. llama_token llama_token_eot(const struct llama_model * model) {
  15222. return model->vocab.special_eot_id;
  15223. }
  15224. int32_t llama_tokenize(
  15225. const struct llama_model * model,
  15226. const char * text,
  15227. int32_t text_len,
  15228. llama_token * tokens,
  15229. int32_t n_tokens_max,
  15230. bool add_special,
  15231. bool parse_special) {
  15232. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_special, parse_special);
  15233. if (n_tokens_max < (int) res.size()) {
  15234. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  15235. return -((int) res.size());
  15236. }
  15237. for (size_t i = 0; i < res.size(); i++) {
  15238. tokens[i] = res[i];
  15239. }
  15240. return res.size();
  15241. }
  15242. static std::string llama_decode_text(const std::string & text) {
  15243. std::string decoded_text;
  15244. const auto cpts = unicode_cpts_from_utf8(text);
  15245. for (const auto cpt : cpts) {
  15246. const auto utf8 = unicode_cpt_to_utf8(cpt);
  15247. try {
  15248. decoded_text += unicode_utf8_to_byte(utf8);
  15249. } catch (const std::out_of_range & e) {
  15250. decoded_text += "[UNK_BYTE_0x";
  15251. for (const auto c : utf8) {
  15252. decoded_text += format("%02x", (uint8_t) c);
  15253. }
  15254. decoded_text += text + "]";
  15255. }
  15256. }
  15257. return decoded_text;
  15258. }
  15259. // does not write null-terminator to buf
  15260. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length, bool special) {
  15261. // if we have a cache - use it
  15262. {
  15263. const auto & cache = special ? model->vocab.cache_token_to_piece_special : model->vocab.cache_token_to_piece;
  15264. if (!cache.empty()) {
  15265. const auto & res = cache.at(token);
  15266. if (length < (int) res.size()) {
  15267. return -(int) res.size();
  15268. }
  15269. memcpy(buf, res.c_str(), res.size());
  15270. return res.size();
  15271. }
  15272. }
  15273. if (0 <= token && token < llama_n_vocab(model)) {
  15274. switch (llama_vocab_get_type(model->vocab)) {
  15275. case LLAMA_VOCAB_TYPE_WPM:
  15276. case LLAMA_VOCAB_TYPE_SPM: {
  15277. // NOTE: we accept all unsupported token types,
  15278. // suppressing them like CONTROL tokens.
  15279. if (llama_is_normal_token(model->vocab, token)) {
  15280. std::string result = model->vocab.id_to_token[token].text;
  15281. llama_unescape_whitespace(result);
  15282. if (length < (int) result.length()) {
  15283. return -(int) result.length();
  15284. }
  15285. memcpy(buf, result.c_str(), result.length());
  15286. return result.length();
  15287. } else if (
  15288. (llama_is_user_defined_token(model->vocab, token)) ||
  15289. (llama_is_control_token (model->vocab, token) && special)) {
  15290. std::string result = model->vocab.id_to_token[token].text;
  15291. if (length < (int) result.length()) {
  15292. return -(int) result.length();
  15293. }
  15294. memcpy(buf, result.c_str(), result.length());
  15295. return result.length();
  15296. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  15297. if (length < 3) {
  15298. return -3;
  15299. }
  15300. memcpy(buf, "\xe2\x96\x85", 3);
  15301. return 3;
  15302. } else if (llama_is_byte_token(model->vocab, token)) {
  15303. if (length < 1) {
  15304. return -1;
  15305. }
  15306. buf[0] = llama_token_to_byte(model->vocab, token);
  15307. return 1;
  15308. }
  15309. break;
  15310. }
  15311. case LLAMA_VOCAB_TYPE_BPE: {
  15312. // NOTE: we accept all unsupported token types,
  15313. // suppressing them like CONTROL tokens.
  15314. if (llama_is_normal_token(model->vocab, token)) {
  15315. std::string result = model->vocab.id_to_token[token].text;
  15316. result = llama_decode_text(result);
  15317. if (length < (int) result.length()) {
  15318. return -(int) result.length();
  15319. }
  15320. memcpy(buf, result.c_str(), result.length());
  15321. return result.length();
  15322. } else if (
  15323. (llama_is_user_defined_token(model->vocab, token)) ||
  15324. (llama_is_control_token (model->vocab, token) && special)) {
  15325. std::string result = model->vocab.id_to_token[token].text;
  15326. if (length < (int) result.length()) {
  15327. return -(int) result.length();
  15328. }
  15329. memcpy(buf, result.c_str(), result.length());
  15330. return result.length();
  15331. }
  15332. break;
  15333. }
  15334. default:
  15335. GGML_ASSERT(false);
  15336. }
  15337. }
  15338. return 0;
  15339. }
  15340. // trim whitespace from the beginning and end of a string
  15341. static std::string trim(const std::string & str) {
  15342. size_t start = 0;
  15343. size_t end = str.size();
  15344. while (start < end && isspace(str[start])) {
  15345. start += 1;
  15346. }
  15347. while (end > start && isspace(str[end - 1])) {
  15348. end -= 1;
  15349. }
  15350. return str.substr(start, end - start);
  15351. }
  15352. // Simple version of "llama_apply_chat_template" that only works with strings
  15353. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  15354. static int32_t llama_chat_apply_template_internal(
  15355. const std::string & tmpl,
  15356. const std::vector<const llama_chat_message *> & chat,
  15357. std::string & dest, bool add_ass) {
  15358. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  15359. std::stringstream ss;
  15360. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  15361. // chatml template
  15362. for (auto message : chat) {
  15363. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  15364. }
  15365. if (add_ass) {
  15366. ss << "<|im_start|>assistant\n";
  15367. }
  15368. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  15369. // llama2 template and its variants
  15370. // [variant] support system message
  15371. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  15372. // [variant] space before + after response
  15373. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  15374. // [variant] add BOS inside history
  15375. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  15376. // [variant] trim spaces from the input message
  15377. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  15378. // construct the prompt
  15379. bool is_inside_turn = true; // skip BOS at the beginning
  15380. ss << "[INST] ";
  15381. for (auto message : chat) {
  15382. std::string content = strip_message ? trim(message->content) : message->content;
  15383. std::string role(message->role);
  15384. if (!is_inside_turn) {
  15385. is_inside_turn = true;
  15386. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  15387. }
  15388. if (role == "system") {
  15389. if (support_system_message) {
  15390. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  15391. } else {
  15392. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  15393. ss << content << "\n";
  15394. }
  15395. } else if (role == "user") {
  15396. ss << content << " [/INST]";
  15397. } else {
  15398. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  15399. is_inside_turn = false;
  15400. }
  15401. }
  15402. // llama2 templates seem to not care about "add_generation_prompt"
  15403. } else if (tmpl == "phi3" || (tmpl.find("<|assistant|>") != std::string::npos && tmpl.find("<|end|>") != std::string::npos)) {
  15404. // Phi 3
  15405. for (auto message : chat) {
  15406. std::string role(message->role);
  15407. ss << "<|" << role << "|>\n" << message->content << "<|end|>\n";
  15408. }
  15409. if (add_ass) {
  15410. ss << "<|assistant|>\n";
  15411. }
  15412. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  15413. // zephyr template
  15414. for (auto message : chat) {
  15415. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  15416. }
  15417. if (add_ass) {
  15418. ss << "<|assistant|>\n";
  15419. }
  15420. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  15421. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  15422. for (auto message : chat) {
  15423. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  15424. ss << bos << message->role << "\n" << message->content << "</s>\n";
  15425. }
  15426. if (add_ass) {
  15427. ss << "<s>assistant\n";
  15428. }
  15429. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  15430. // google/gemma-7b-it
  15431. std::string system_prompt = "";
  15432. for (auto message : chat) {
  15433. std::string role(message->role);
  15434. if (role == "system") {
  15435. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  15436. system_prompt = trim(message->content);
  15437. continue;
  15438. }
  15439. // in gemma, "assistant" is "model"
  15440. role = role == "assistant" ? "model" : message->role;
  15441. ss << "<start_of_turn>" << role << "\n";
  15442. if (!system_prompt.empty() && role != "model") {
  15443. ss << system_prompt << "\n\n";
  15444. system_prompt = "";
  15445. }
  15446. ss << trim(message->content) << "<end_of_turn>\n";
  15447. }
  15448. if (add_ass) {
  15449. ss << "<start_of_turn>model\n";
  15450. }
  15451. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  15452. // OrionStarAI/Orion-14B-Chat
  15453. std::string system_prompt = "";
  15454. for (auto message : chat) {
  15455. std::string role(message->role);
  15456. if (role == "system") {
  15457. // there is no system message support, we will merge it with user prompt
  15458. system_prompt = message->content;
  15459. continue;
  15460. } else if (role == "user") {
  15461. ss << "Human: ";
  15462. if (!system_prompt.empty()) {
  15463. ss << system_prompt << "\n\n";
  15464. system_prompt = "";
  15465. }
  15466. ss << message->content << "\n\nAssistant: </s>";
  15467. } else {
  15468. ss << message->content << "</s>";
  15469. }
  15470. }
  15471. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  15472. // openchat/openchat-3.5-0106,
  15473. for (auto message : chat) {
  15474. std::string role(message->role);
  15475. if (role == "system") {
  15476. ss << message->content << "<|end_of_turn|>";
  15477. } else {
  15478. role[0] = toupper(role[0]);
  15479. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  15480. }
  15481. }
  15482. if (add_ass) {
  15483. ss << "GPT4 Correct Assistant:";
  15484. }
  15485. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  15486. // eachadea/vicuna-13b-1.1 (and Orca variant)
  15487. for (auto message : chat) {
  15488. std::string role(message->role);
  15489. if (role == "system") {
  15490. // Orca-Vicuna variant uses a system prefix
  15491. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  15492. ss << "SYSTEM: " << message->content << "\n";
  15493. } else {
  15494. ss << message->content << "\n\n";
  15495. }
  15496. } else if (role == "user") {
  15497. ss << "USER: " << message->content << "\n";
  15498. } else if (role == "assistant") {
  15499. ss << "ASSISTANT: " << message->content << "</s>\n";
  15500. }
  15501. }
  15502. if (add_ass) {
  15503. ss << "ASSISTANT:";
  15504. }
  15505. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  15506. // deepseek-ai/deepseek-coder-33b-instruct
  15507. for (auto message : chat) {
  15508. std::string role(message->role);
  15509. if (role == "system") {
  15510. ss << message->content;
  15511. } else if (role == "user") {
  15512. ss << "### Instruction:\n" << message->content << "\n";
  15513. } else if (role == "assistant") {
  15514. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  15515. }
  15516. }
  15517. if (add_ass) {
  15518. ss << "### Response:\n";
  15519. }
  15520. } else if (tmpl == "command-r" || (tmpl.find("<|START_OF_TURN_TOKEN|>") != std::string::npos && tmpl.find("<|USER_TOKEN|>") != std::string::npos)) {
  15521. // CohereForAI/c4ai-command-r-plus
  15522. for (auto message : chat) {
  15523. std::string role(message->role);
  15524. if (role == "system") {
  15525. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15526. } else if (role == "user") {
  15527. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15528. } else if (role == "assistant") {
  15529. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  15530. }
  15531. }
  15532. if (add_ass) {
  15533. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  15534. }
  15535. } else if (tmpl == "llama3" || (tmpl.find("<|start_header_id|>") != std::string::npos && tmpl.find("<|end_header_id|>") != std::string::npos)) {
  15536. // Llama 3
  15537. for (auto message : chat) {
  15538. std::string role(message->role);
  15539. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  15540. }
  15541. if (add_ass) {
  15542. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  15543. }
  15544. } else {
  15545. // template not supported
  15546. return -1;
  15547. }
  15548. dest = ss.str();
  15549. return dest.size();
  15550. }
  15551. LLAMA_API int32_t llama_chat_apply_template(
  15552. const struct llama_model * model,
  15553. const char * tmpl,
  15554. const struct llama_chat_message * chat,
  15555. size_t n_msg,
  15556. bool add_ass,
  15557. char * buf,
  15558. int32_t length) {
  15559. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  15560. if (tmpl == nullptr) {
  15561. GGML_ASSERT(model != nullptr);
  15562. // load template from model
  15563. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  15564. std::string template_key = "tokenizer.chat_template";
  15565. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  15566. if (res < 0) {
  15567. // worst case: there is no information about template, we will use chatml by default
  15568. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  15569. } else {
  15570. curr_tmpl = std::string(model_template.data(), model_template.size());
  15571. }
  15572. }
  15573. // format the chat to string
  15574. std::vector<const llama_chat_message *> chat_vec;
  15575. chat_vec.resize(n_msg);
  15576. for (size_t i = 0; i < n_msg; i++) {
  15577. chat_vec[i] = &chat[i];
  15578. }
  15579. std::string formatted_chat;
  15580. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  15581. if (res < 0) {
  15582. return res;
  15583. }
  15584. if (buf && length > 0) {
  15585. strncpy(buf, formatted_chat.c_str(), length);
  15586. }
  15587. return res;
  15588. }
  15589. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  15590. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  15591. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  15592. return strlen(split_path);
  15593. }
  15594. return 0;
  15595. }
  15596. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  15597. std::string str_split_path(split_path);
  15598. char postfix[32];
  15599. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  15600. std::string str_postfix(postfix);
  15601. // check if dest ends with postfix
  15602. int size_prefix = str_split_path.size() - str_postfix.size();
  15603. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  15604. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  15605. return size_prefix;
  15606. }
  15607. return 0;
  15608. }
  15609. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  15610. struct llama_timings result = {
  15611. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  15612. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  15613. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  15614. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  15615. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  15616. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  15617. /*.n_sample =*/ std::max(1, ctx->n_sample),
  15618. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  15619. /*.n_eval =*/ std::max(1, ctx->n_eval),
  15620. };
  15621. return result;
  15622. }
  15623. void llama_print_timings(struct llama_context * ctx) {
  15624. const llama_timings timings = llama_get_timings(ctx);
  15625. LLAMA_LOG_INFO("\n");
  15626. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  15627. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15628. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  15629. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  15630. __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);
  15631. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15632. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  15633. 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));
  15634. }
  15635. void llama_reset_timings(struct llama_context * ctx) {
  15636. ctx->t_start_us = ggml_time_us();
  15637. ctx->t_sample_us = ctx->n_sample = 0;
  15638. ctx->t_eval_us = ctx->n_eval = 0;
  15639. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  15640. }
  15641. const char * llama_print_system_info(void) {
  15642. static std::string s;
  15643. s = "";
  15644. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  15645. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  15646. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  15647. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  15648. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  15649. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  15650. s += "AVX512_BF16 = " + std::to_string(ggml_cpu_has_avx512_bf16()) + " | ";
  15651. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  15652. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  15653. s += "SVE = " + std::to_string(ggml_cpu_has_sve()) + " | ";
  15654. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  15655. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  15656. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  15657. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  15658. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  15659. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  15660. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  15661. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  15662. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  15663. #ifdef GGML_USE_LLAMAFILE
  15664. s += "LLAMAFILE = 1 | ";
  15665. #else
  15666. s += "LLAMAFILE = 0 | ";
  15667. #endif
  15668. return s.c_str();
  15669. }
  15670. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  15671. fprintf(stream, "\n");
  15672. fprintf(stream, "###########\n");
  15673. fprintf(stream, "# Timings #\n");
  15674. fprintf(stream, "###########\n");
  15675. fprintf(stream, "\n");
  15676. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  15677. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  15678. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  15679. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  15680. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  15681. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  15682. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  15683. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  15684. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  15685. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  15686. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  15687. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  15688. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  15689. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  15690. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  15691. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  15692. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  15693. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  15694. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  15695. }
  15696. // For internal test use
  15697. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  15698. struct llama_context * ctx
  15699. ) {
  15700. return ctx->model.tensors_by_name;
  15701. }
  15702. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  15703. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  15704. g_state.log_callback_user_data = user_data;
  15705. #ifdef GGML_USE_METAL
  15706. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15707. #elif defined(GGML_USE_CUDA)
  15708. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15709. #endif
  15710. }
  15711. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  15712. va_list args_copy;
  15713. va_copy(args_copy, args);
  15714. char buffer[128];
  15715. int len = vsnprintf(buffer, 128, format, args);
  15716. if (len < 128) {
  15717. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  15718. } else {
  15719. char* buffer2 = new char[len+1];
  15720. vsnprintf(buffer2, len+1, format, args_copy);
  15721. buffer2[len] = 0;
  15722. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  15723. delete[] buffer2;
  15724. }
  15725. va_end(args_copy);
  15726. }
  15727. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  15728. va_list args;
  15729. va_start(args, format);
  15730. llama_log_internal_v(level, format, args);
  15731. va_end(args);
  15732. }
  15733. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  15734. (void) level;
  15735. (void) user_data;
  15736. fputs(text, stderr);
  15737. fflush(stderr);
  15738. }