llama.cpp 727 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171
  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. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #include <algorithm>
  55. #include <array>
  56. #include <cassert>
  57. #include <cctype>
  58. #include <cfloat>
  59. #include <cinttypes>
  60. #include <climits>
  61. #include <cmath>
  62. #include <cstdarg>
  63. #include <cstddef>
  64. #include <cstdint>
  65. #include <cstdio>
  66. #include <cstring>
  67. #include <ctime>
  68. #include <forward_list>
  69. #include <fstream>
  70. #include <functional>
  71. #include <future>
  72. #include <initializer_list>
  73. #include <locale>
  74. #include <map>
  75. #include <memory>
  76. #include <mutex>
  77. #include <numeric>
  78. #include <queue>
  79. #include <random>
  80. #include <regex>
  81. #include <set>
  82. #include <sstream>
  83. #include <thread>
  84. #include <type_traits>
  85. #include <unordered_map>
  86. #if defined(_MSC_VER)
  87. #pragma warning(disable: 4244 4267) // possible loss of data
  88. #endif
  89. #ifdef __GNUC__
  90. #ifdef __MINGW32__
  91. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  92. #else
  93. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  94. #endif
  95. #else
  96. #define LLAMA_ATTRIBUTE_FORMAT(...)
  97. #endif
  98. #define LLAMA_MAX_NODES 8192
  99. #define LLAMA_MAX_EXPERTS 60
  100. //
  101. // logging
  102. //
  103. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  104. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  105. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  106. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  107. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  108. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  109. //
  110. // helpers
  111. //
  112. static size_t utf8_len(char src) {
  113. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  114. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  115. return lookup[highbits];
  116. }
  117. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  118. std::string result;
  119. for (size_t pos = 0; ; pos += search.length()) {
  120. auto new_pos = s.find(search, pos);
  121. if (new_pos == std::string::npos) {
  122. result += s.substr(pos, s.size() - pos);
  123. break;
  124. }
  125. result += s.substr(pos, new_pos - pos) + replace;
  126. pos = new_pos;
  127. }
  128. s = std::move(result);
  129. }
  130. static bool is_float_close(float a, float b, float abs_tol) {
  131. // Check for non-negative tolerance
  132. if (abs_tol < 0.0) {
  133. throw std::invalid_argument("Tolerance must be non-negative");
  134. }
  135. // Exact equality check
  136. if (a == b) {
  137. return true;
  138. }
  139. // Check for infinities
  140. if (std::isinf(a) || std::isinf(b)) {
  141. return false;
  142. }
  143. // Regular comparison using the provided absolute tolerance
  144. return std::fabs(b - a) <= abs_tol;
  145. }
  146. static void zeros(std::ofstream & file, size_t n) {
  147. char zero = 0;
  148. for (size_t i = 0; i < n; ++i) {
  149. file.write(&zero, 1);
  150. }
  151. }
  152. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  153. static std::string format(const char * fmt, ...) {
  154. va_list ap;
  155. va_list ap2;
  156. va_start(ap, fmt);
  157. va_copy(ap2, ap);
  158. int size = vsnprintf(NULL, 0, fmt, ap);
  159. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  160. std::vector<char> buf(size + 1);
  161. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  162. GGML_ASSERT(size2 == size);
  163. va_end(ap2);
  164. va_end(ap);
  165. return std::string(buf.data(), size);
  166. }
  167. //
  168. // gguf constants (sync with gguf.py)
  169. //
  170. enum llm_arch {
  171. LLM_ARCH_LLAMA,
  172. LLM_ARCH_FALCON,
  173. LLM_ARCH_BAICHUAN,
  174. LLM_ARCH_GROK,
  175. LLM_ARCH_GPT2,
  176. LLM_ARCH_GPTJ,
  177. LLM_ARCH_GPTNEOX,
  178. LLM_ARCH_MPT,
  179. LLM_ARCH_STARCODER,
  180. LLM_ARCH_PERSIMMON,
  181. LLM_ARCH_REFACT,
  182. LLM_ARCH_BERT,
  183. LLM_ARCH_NOMIC_BERT,
  184. LLM_ARCH_JINA_BERT_V2,
  185. LLM_ARCH_BLOOM,
  186. LLM_ARCH_STABLELM,
  187. LLM_ARCH_QWEN,
  188. LLM_ARCH_QWEN2,
  189. LLM_ARCH_QWEN2MOE,
  190. LLM_ARCH_PHI2,
  191. LLM_ARCH_PHI3,
  192. LLM_ARCH_PLAMO,
  193. LLM_ARCH_CODESHELL,
  194. LLM_ARCH_ORION,
  195. LLM_ARCH_INTERNLM2,
  196. LLM_ARCH_MINICPM,
  197. LLM_ARCH_GEMMA,
  198. LLM_ARCH_STARCODER2,
  199. LLM_ARCH_MAMBA,
  200. LLM_ARCH_XVERSE,
  201. LLM_ARCH_COMMAND_R,
  202. LLM_ARCH_DBRX,
  203. LLM_ARCH_OLMO,
  204. LLM_ARCH_UNKNOWN,
  205. };
  206. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  207. { LLM_ARCH_LLAMA, "llama" },
  208. { LLM_ARCH_FALCON, "falcon" },
  209. { LLM_ARCH_GROK, "grok" },
  210. { LLM_ARCH_GPT2, "gpt2" },
  211. { LLM_ARCH_GPTJ, "gptj" },
  212. { LLM_ARCH_GPTNEOX, "gptneox" },
  213. { LLM_ARCH_MPT, "mpt" },
  214. { LLM_ARCH_BAICHUAN, "baichuan" },
  215. { LLM_ARCH_STARCODER, "starcoder" },
  216. { LLM_ARCH_PERSIMMON, "persimmon" },
  217. { LLM_ARCH_REFACT, "refact" },
  218. { LLM_ARCH_BERT, "bert" },
  219. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  220. { LLM_ARCH_JINA_BERT_V2, "jina-bert-v2" },
  221. { LLM_ARCH_BLOOM, "bloom" },
  222. { LLM_ARCH_STABLELM, "stablelm" },
  223. { LLM_ARCH_QWEN, "qwen" },
  224. { LLM_ARCH_QWEN2, "qwen2" },
  225. { LLM_ARCH_QWEN2MOE, "qwen2moe" },
  226. { LLM_ARCH_PHI2, "phi2" },
  227. { LLM_ARCH_PHI3, "phi3" },
  228. { LLM_ARCH_PLAMO, "plamo" },
  229. { LLM_ARCH_CODESHELL, "codeshell" },
  230. { LLM_ARCH_ORION, "orion" },
  231. { LLM_ARCH_INTERNLM2, "internlm2" },
  232. { LLM_ARCH_MINICPM, "minicpm" },
  233. { LLM_ARCH_GEMMA, "gemma" },
  234. { LLM_ARCH_STARCODER2, "starcoder2" },
  235. { LLM_ARCH_MAMBA, "mamba" },
  236. { LLM_ARCH_XVERSE, "xverse" },
  237. { LLM_ARCH_COMMAND_R, "command-r" },
  238. { LLM_ARCH_DBRX, "dbrx" },
  239. { LLM_ARCH_OLMO, "olmo" },
  240. { LLM_ARCH_UNKNOWN, "(unknown)" },
  241. };
  242. enum llm_kv {
  243. LLM_KV_GENERAL_ARCHITECTURE,
  244. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  245. LLM_KV_GENERAL_ALIGNMENT,
  246. LLM_KV_GENERAL_NAME,
  247. LLM_KV_GENERAL_AUTHOR,
  248. LLM_KV_GENERAL_VERSION,
  249. LLM_KV_GENERAL_URL,
  250. LLM_KV_GENERAL_DESCRIPTION,
  251. LLM_KV_GENERAL_LICENSE,
  252. LLM_KV_GENERAL_SOURCE_URL,
  253. LLM_KV_GENERAL_SOURCE_HF_REPO,
  254. LLM_KV_VOCAB_SIZE,
  255. LLM_KV_CONTEXT_LENGTH,
  256. LLM_KV_EMBEDDING_LENGTH,
  257. LLM_KV_BLOCK_COUNT,
  258. LLM_KV_FEED_FORWARD_LENGTH,
  259. LLM_KV_USE_PARALLEL_RESIDUAL,
  260. LLM_KV_TENSOR_DATA_LAYOUT,
  261. LLM_KV_EXPERT_COUNT,
  262. LLM_KV_EXPERT_USED_COUNT,
  263. LLM_KV_POOLING_TYPE,
  264. LLM_KV_LOGIT_SCALE,
  265. LLM_KV_ATTENTION_HEAD_COUNT,
  266. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  267. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  268. LLM_KV_ATTENTION_CLAMP_KQV,
  269. LLM_KV_ATTENTION_KEY_LENGTH,
  270. LLM_KV_ATTENTION_VALUE_LENGTH,
  271. LLM_KV_ATTENTION_LAYERNORM_EPS,
  272. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  273. LLM_KV_ATTENTION_CAUSAL,
  274. LLM_KV_ROPE_DIMENSION_COUNT,
  275. LLM_KV_ROPE_FREQ_BASE,
  276. LLM_KV_ROPE_SCALE_LINEAR,
  277. LLM_KV_ROPE_SCALING_TYPE,
  278. LLM_KV_ROPE_SCALING_FACTOR,
  279. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  280. LLM_KV_ROPE_SCALING_FINETUNED,
  281. LLM_KV_SPLIT_NO,
  282. LLM_KV_SPLIT_COUNT,
  283. LLM_KV_SPLIT_TENSORS_COUNT,
  284. LLM_KV_SSM_INNER_SIZE,
  285. LLM_KV_SSM_CONV_KERNEL,
  286. LLM_KV_SSM_STATE_SIZE,
  287. LLM_KV_SSM_TIME_STEP_RANK,
  288. LLM_KV_TOKENIZER_MODEL,
  289. LLM_KV_TOKENIZER_PRE,
  290. LLM_KV_TOKENIZER_LIST,
  291. LLM_KV_TOKENIZER_TOKEN_TYPE,
  292. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  293. LLM_KV_TOKENIZER_SCORES,
  294. LLM_KV_TOKENIZER_MERGES,
  295. LLM_KV_TOKENIZER_BOS_ID,
  296. LLM_KV_TOKENIZER_EOS_ID,
  297. LLM_KV_TOKENIZER_UNK_ID,
  298. LLM_KV_TOKENIZER_SEP_ID,
  299. LLM_KV_TOKENIZER_PAD_ID,
  300. LLM_KV_TOKENIZER_CLS_ID,
  301. LLM_KV_TOKENIZER_MASK_ID,
  302. LLM_KV_TOKENIZER_ADD_BOS,
  303. LLM_KV_TOKENIZER_ADD_EOS,
  304. LLM_KV_TOKENIZER_ADD_PREFIX,
  305. LLM_KV_TOKENIZER_HF_JSON,
  306. LLM_KV_TOKENIZER_RWKV,
  307. LLM_KV_TOKENIZER_PREFIX_ID,
  308. LLM_KV_TOKENIZER_SUFFIX_ID,
  309. LLM_KV_TOKENIZER_MIDDLE_ID,
  310. LLM_KV_TOKENIZER_EOT_ID,
  311. };
  312. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  313. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  314. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  315. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  316. { LLM_KV_GENERAL_NAME, "general.name" },
  317. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  318. { LLM_KV_GENERAL_VERSION, "general.version" },
  319. { LLM_KV_GENERAL_URL, "general.url" },
  320. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  321. { LLM_KV_GENERAL_LICENSE, "general.license" },
  322. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  323. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  324. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  325. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  326. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  327. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  328. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  329. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  330. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  331. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  332. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  333. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  334. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  335. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  336. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  337. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  338. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  339. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  340. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  341. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  342. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  343. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  344. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  345. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  346. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  347. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  348. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  349. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  350. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  351. { LLM_KV_SPLIT_NO, "split.no" },
  352. { LLM_KV_SPLIT_COUNT, "split.count" },
  353. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  354. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  355. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  356. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  357. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  358. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  359. { LLM_KV_TOKENIZER_PRE, "tokenizer.ggml.pre" },
  360. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  361. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  362. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  363. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  364. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  365. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  366. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  367. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  368. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  369. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  370. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  371. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  372. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  373. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  374. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  375. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  376. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  377. { LLM_KV_TOKENIZER_PREFIX_ID, "tokenizer.ggml.prefix_token_id" },
  378. { LLM_KV_TOKENIZER_SUFFIX_ID, "tokenizer.ggml.suffix_token_id" },
  379. { LLM_KV_TOKENIZER_MIDDLE_ID, "tokenizer.ggml.middle_token_id" },
  380. { LLM_KV_TOKENIZER_EOT_ID, "tokenizer.ggml.eot_token_id" },
  381. };
  382. struct LLM_KV {
  383. LLM_KV(llm_arch arch) : arch(arch) {}
  384. llm_arch arch;
  385. std::string operator()(llm_kv kv) const {
  386. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  387. }
  388. };
  389. enum llm_tensor {
  390. LLM_TENSOR_TOKEN_EMBD,
  391. LLM_TENSOR_TOKEN_EMBD_NORM,
  392. LLM_TENSOR_TOKEN_TYPES,
  393. LLM_TENSOR_POS_EMBD,
  394. LLM_TENSOR_OUTPUT,
  395. LLM_TENSOR_OUTPUT_NORM,
  396. LLM_TENSOR_ROPE_FREQS,
  397. LLM_TENSOR_ATTN_Q,
  398. LLM_TENSOR_ATTN_K,
  399. LLM_TENSOR_ATTN_V,
  400. LLM_TENSOR_ATTN_QKV,
  401. LLM_TENSOR_ATTN_OUT,
  402. LLM_TENSOR_ATTN_NORM,
  403. LLM_TENSOR_ATTN_NORM_2,
  404. LLM_TENSOR_ATTN_OUT_NORM,
  405. LLM_TENSOR_ATTN_ROT_EMBD,
  406. LLM_TENSOR_FFN_GATE_INP,
  407. LLM_TENSOR_FFN_GATE_INP_SHEXP,
  408. LLM_TENSOR_FFN_NORM,
  409. LLM_TENSOR_FFN_GATE,
  410. LLM_TENSOR_FFN_DOWN,
  411. LLM_TENSOR_FFN_UP,
  412. LLM_TENSOR_FFN_ACT,
  413. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  414. LLM_TENSOR_FFN_GATE_EXP,
  415. LLM_TENSOR_FFN_UP_EXP,
  416. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  417. LLM_TENSOR_FFN_GATE_EXPS,
  418. LLM_TENSOR_FFN_UP_EXPS,
  419. LLM_TENSOR_FFN_DOWN_SHEXP,
  420. LLM_TENSOR_FFN_GATE_SHEXP,
  421. LLM_TENSOR_FFN_UP_SHEXP,
  422. LLM_TENSOR_ATTN_Q_NORM,
  423. LLM_TENSOR_ATTN_K_NORM,
  424. LLM_TENSOR_LAYER_OUT_NORM,
  425. LLM_TENSOR_SSM_IN,
  426. LLM_TENSOR_SSM_CONV1D,
  427. LLM_TENSOR_SSM_X,
  428. LLM_TENSOR_SSM_DT,
  429. LLM_TENSOR_SSM_A,
  430. LLM_TENSOR_SSM_D,
  431. LLM_TENSOR_SSM_OUT,
  432. };
  433. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  434. {
  435. LLM_ARCH_LLAMA,
  436. {
  437. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  438. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  439. { LLM_TENSOR_OUTPUT, "output" },
  440. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  441. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  442. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  443. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  444. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  445. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  446. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  447. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  448. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  449. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  450. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  451. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  452. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  453. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  454. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  455. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  456. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  457. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  458. },
  459. },
  460. {
  461. LLM_ARCH_BAICHUAN,
  462. {
  463. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  464. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  465. { LLM_TENSOR_OUTPUT, "output" },
  466. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  467. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  468. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  469. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  470. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  471. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  472. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  473. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  474. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  475. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  476. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  477. },
  478. },
  479. {
  480. LLM_ARCH_FALCON,
  481. {
  482. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  483. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  484. { LLM_TENSOR_OUTPUT, "output" },
  485. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  486. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  487. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  488. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  489. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  490. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  491. },
  492. },
  493. {
  494. LLM_ARCH_GROK,
  495. {
  496. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  497. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  498. { LLM_TENSOR_OUTPUT, "output" },
  499. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  500. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  501. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  502. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  503. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  504. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  505. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  506. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  507. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  508. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  509. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  510. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  511. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  512. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  513. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  514. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  515. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  516. },
  517. },
  518. {
  519. LLM_ARCH_GPT2,
  520. {
  521. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  522. { LLM_TENSOR_POS_EMBD, "position_embd" },
  523. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  524. { LLM_TENSOR_OUTPUT, "output" },
  525. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  526. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  527. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  528. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  529. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  530. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  531. },
  532. },
  533. {
  534. LLM_ARCH_GPTJ,
  535. {
  536. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  537. },
  538. },
  539. {
  540. LLM_ARCH_GPTNEOX,
  541. {
  542. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  543. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  544. { LLM_TENSOR_OUTPUT, "output" },
  545. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  546. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  547. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  548. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  549. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  550. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  551. },
  552. },
  553. {
  554. LLM_ARCH_PERSIMMON,
  555. {
  556. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  557. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  558. { LLM_TENSOR_OUTPUT, "output"},
  559. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  560. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  561. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  562. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  563. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  564. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  565. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  566. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  567. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  568. },
  569. },
  570. {
  571. LLM_ARCH_MPT,
  572. {
  573. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  574. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  575. { LLM_TENSOR_OUTPUT, "output"},
  576. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  577. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  578. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  579. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  580. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  581. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  582. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  583. { LLM_TENSOR_POS_EMBD, "position_embd" },
  584. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  585. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  586. },
  587. },
  588. {
  589. LLM_ARCH_STARCODER,
  590. {
  591. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  592. { LLM_TENSOR_POS_EMBD, "position_embd" },
  593. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  594. { LLM_TENSOR_OUTPUT, "output" },
  595. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  596. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  597. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  598. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  599. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  600. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  601. },
  602. },
  603. {
  604. LLM_ARCH_REFACT,
  605. {
  606. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  607. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  608. { LLM_TENSOR_OUTPUT, "output" },
  609. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  610. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  611. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  612. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  613. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  614. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  615. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  616. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  617. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  618. },
  619. },
  620. {
  621. LLM_ARCH_BERT,
  622. {
  623. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  624. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  625. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  626. { LLM_TENSOR_POS_EMBD, "position_embd" },
  627. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  628. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  629. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  630. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  631. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  632. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  633. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  634. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  635. },
  636. },
  637. {
  638. LLM_ARCH_NOMIC_BERT,
  639. {
  640. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  641. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  642. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  643. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  644. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  645. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  646. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  647. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  648. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  649. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  650. },
  651. },
  652. {
  653. LLM_ARCH_JINA_BERT_V2,
  654. {
  655. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  656. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  657. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  658. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  659. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  660. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  661. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  662. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  663. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  664. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  665. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  666. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  667. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  668. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  669. },
  670. },
  671. {
  672. LLM_ARCH_BLOOM,
  673. {
  674. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  675. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  676. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  677. { LLM_TENSOR_OUTPUT, "output" },
  678. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  679. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  680. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  681. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  682. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  683. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  684. },
  685. },
  686. {
  687. LLM_ARCH_STABLELM,
  688. {
  689. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  690. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  691. { LLM_TENSOR_OUTPUT, "output" },
  692. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  693. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  694. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  695. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  696. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  697. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  698. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  699. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  700. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  701. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  702. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  703. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  704. },
  705. },
  706. {
  707. LLM_ARCH_QWEN,
  708. {
  709. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  710. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  711. { LLM_TENSOR_OUTPUT, "output" },
  712. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  713. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  714. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  715. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  716. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  717. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  718. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  719. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  720. },
  721. },
  722. {
  723. LLM_ARCH_QWEN2,
  724. {
  725. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  726. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  727. { LLM_TENSOR_OUTPUT, "output" },
  728. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  729. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  730. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  731. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  732. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  733. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  734. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  735. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  736. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  737. },
  738. },
  739. {
  740. LLM_ARCH_QWEN2MOE,
  741. {
  742. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  743. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  744. { LLM_TENSOR_OUTPUT, "output" },
  745. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  746. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  747. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  748. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  749. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  750. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  751. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  752. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  753. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  754. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  755. { LLM_TENSOR_FFN_GATE_INP_SHEXP, "blk.%d.ffn_gate_inp_shexp" },
  756. { LLM_TENSOR_FFN_GATE_SHEXP, "blk.%d.ffn_gate_shexp" },
  757. { LLM_TENSOR_FFN_DOWN_SHEXP, "blk.%d.ffn_down_shexp" },
  758. { LLM_TENSOR_FFN_UP_SHEXP, "blk.%d.ffn_up_shexp" },
  759. },
  760. },
  761. {
  762. LLM_ARCH_PHI2,
  763. {
  764. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  765. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  766. { LLM_TENSOR_OUTPUT, "output" },
  767. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  768. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  769. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  770. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  771. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  772. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  773. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  774. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  775. },
  776. },
  777. {
  778. LLM_ARCH_PHI3,
  779. {
  780. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  781. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  782. { LLM_TENSOR_OUTPUT, "output" },
  783. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  784. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  785. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  786. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  787. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  788. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  789. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  790. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  791. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  792. },
  793. },
  794. {
  795. LLM_ARCH_PLAMO,
  796. {
  797. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  798. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  799. { LLM_TENSOR_OUTPUT, "output" },
  800. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  801. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  802. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  803. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  804. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  805. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  806. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  807. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  808. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  809. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  810. },
  811. },
  812. {
  813. LLM_ARCH_CODESHELL,
  814. {
  815. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  816. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  817. { LLM_TENSOR_OUTPUT, "output" },
  818. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  819. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  820. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  821. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  822. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  823. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  824. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  825. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  826. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  827. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  828. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  829. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  830. },
  831. },
  832. {
  833. LLM_ARCH_ORION,
  834. {
  835. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  836. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  837. { LLM_TENSOR_OUTPUT, "output" },
  838. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  839. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  840. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  841. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  842. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  843. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  844. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  845. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  846. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  847. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  848. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  849. },
  850. },
  851. {
  852. LLM_ARCH_INTERNLM2,
  853. {
  854. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  855. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  856. { LLM_TENSOR_OUTPUT, "output" },
  857. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  858. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  859. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  860. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  861. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  862. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  863. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  864. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  865. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  866. },
  867. },
  868. {
  869. LLM_ARCH_MINICPM,
  870. {
  871. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  872. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  873. { LLM_TENSOR_OUTPUT, "output" },
  874. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  875. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  876. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  877. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  878. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  879. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  880. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  881. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  882. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  883. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  884. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  885. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  886. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  887. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  888. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  889. },
  890. },
  891. {
  892. LLM_ARCH_GEMMA,
  893. {
  894. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  895. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  896. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  897. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  898. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  899. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  900. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  901. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  902. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  903. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  904. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  905. },
  906. },
  907. {
  908. LLM_ARCH_STARCODER2,
  909. {
  910. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  911. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  912. { LLM_TENSOR_OUTPUT, "output" },
  913. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  914. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  915. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  916. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  917. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  918. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  919. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  920. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  921. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  922. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  923. },
  924. },
  925. {
  926. LLM_ARCH_MAMBA,
  927. {
  928. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  929. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  930. { LLM_TENSOR_OUTPUT, "output" },
  931. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  932. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  933. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  934. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  935. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  936. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  937. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  938. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  939. },
  940. },
  941. {
  942. LLM_ARCH_XVERSE,
  943. {
  944. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  945. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  946. { LLM_TENSOR_OUTPUT, "output" },
  947. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  948. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  949. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  950. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  951. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  952. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  953. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  954. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  955. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  956. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  957. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  958. },
  959. },
  960. {
  961. LLM_ARCH_COMMAND_R,
  962. {
  963. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  964. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  965. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  966. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  967. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  968. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  969. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  970. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  971. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  972. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  973. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  974. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  975. },
  976. },
  977. {
  978. LLM_ARCH_DBRX,
  979. {
  980. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  981. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  982. { LLM_TENSOR_OUTPUT, "output" },
  983. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  984. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  985. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  986. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  987. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  988. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  989. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  990. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  991. },
  992. },
  993. {
  994. LLM_ARCH_OLMO,
  995. {
  996. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  997. { LLM_TENSOR_OUTPUT, "output" },
  998. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  999. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  1000. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  1001. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  1002. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  1003. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  1004. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  1005. },
  1006. },
  1007. {
  1008. LLM_ARCH_UNKNOWN,
  1009. {
  1010. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  1011. },
  1012. },
  1013. };
  1014. static llm_arch llm_arch_from_string(const std::string & name) {
  1015. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  1016. if (kv.second == name) {
  1017. return kv.first;
  1018. }
  1019. }
  1020. return LLM_ARCH_UNKNOWN;
  1021. }
  1022. // helper to handle gguf constants
  1023. // usage:
  1024. //
  1025. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  1026. //
  1027. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  1028. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  1029. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  1030. //
  1031. struct LLM_TN {
  1032. LLM_TN(llm_arch arch) : arch(arch) {}
  1033. llm_arch arch;
  1034. std::string operator()(llm_tensor tensor) const {
  1035. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1036. return "__missing__";
  1037. }
  1038. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  1039. }
  1040. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  1041. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1042. return "__missing__";
  1043. }
  1044. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  1045. }
  1046. std::string operator()(llm_tensor tensor, int bid) const {
  1047. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1048. return "__missing__";
  1049. }
  1050. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  1051. }
  1052. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  1053. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1054. return "__missing__";
  1055. }
  1056. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  1057. }
  1058. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  1059. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  1060. return "__missing__";
  1061. }
  1062. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  1063. }
  1064. };
  1065. //
  1066. // gguf helpers
  1067. //
  1068. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  1069. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  1070. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  1071. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  1072. };
  1073. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  1074. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  1075. if (kv.second == name) {
  1076. return (llama_rope_scaling_type) kv.first;
  1077. }
  1078. }
  1079. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  1080. }
  1081. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  1082. switch (type) {
  1083. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  1084. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  1085. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  1086. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  1087. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  1088. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  1089. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  1090. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  1091. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  1092. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  1093. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  1094. default: return format("unknown type %d", type);
  1095. }
  1096. }
  1097. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1098. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1099. switch (type) {
  1100. case GGUF_TYPE_STRING:
  1101. return gguf_get_val_str(ctx_gguf, i);
  1102. case GGUF_TYPE_ARRAY:
  1103. {
  1104. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1105. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1106. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1107. std::stringstream ss;
  1108. ss << "[";
  1109. for (int j = 0; j < arr_n; j++) {
  1110. if (arr_type == GGUF_TYPE_STRING) {
  1111. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1112. // escape quotes
  1113. replace_all(val, "\\", "\\\\");
  1114. replace_all(val, "\"", "\\\"");
  1115. ss << '"' << val << '"';
  1116. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1117. ss << "???";
  1118. } else {
  1119. ss << gguf_data_to_str(arr_type, data, j);
  1120. }
  1121. if (j < arr_n - 1) {
  1122. ss << ", ";
  1123. }
  1124. }
  1125. ss << "]";
  1126. return ss.str();
  1127. }
  1128. default:
  1129. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1130. }
  1131. }
  1132. //
  1133. // llama helpers
  1134. //
  1135. #if defined(_WIN32)
  1136. static std::string llama_format_win_err(DWORD err) {
  1137. LPSTR buf;
  1138. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1139. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1140. if (!size) {
  1141. return "FormatMessageA failed";
  1142. }
  1143. std::string ret(buf, size);
  1144. LocalFree(buf);
  1145. return ret;
  1146. }
  1147. #endif
  1148. template <typename T>
  1149. struct no_init {
  1150. T value;
  1151. no_init() { /* do nothing */ }
  1152. };
  1153. struct llama_file {
  1154. // use FILE * so we don't have to re-open the file to mmap
  1155. FILE * fp;
  1156. size_t size;
  1157. llama_file(const char * fname, const char * mode) {
  1158. fp = ggml_fopen(fname, mode);
  1159. if (fp == NULL) {
  1160. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1161. }
  1162. seek(0, SEEK_END);
  1163. size = tell();
  1164. seek(0, SEEK_SET);
  1165. }
  1166. size_t tell() const {
  1167. #ifdef _WIN32
  1168. __int64 ret = _ftelli64(fp);
  1169. #else
  1170. long ret = std::ftell(fp);
  1171. #endif
  1172. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1173. return (size_t) ret;
  1174. }
  1175. void seek(size_t offset, int whence) const {
  1176. #ifdef _WIN32
  1177. int ret = _fseeki64(fp, (__int64) offset, whence);
  1178. #else
  1179. int ret = std::fseek(fp, (long) offset, whence);
  1180. #endif
  1181. GGML_ASSERT(ret == 0); // same
  1182. }
  1183. void read_raw(void * ptr, size_t len) const {
  1184. if (len == 0) {
  1185. return;
  1186. }
  1187. errno = 0;
  1188. std::size_t ret = std::fread(ptr, len, 1, fp);
  1189. if (ferror(fp)) {
  1190. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1191. }
  1192. if (ret != 1) {
  1193. throw std::runtime_error("unexpectedly reached end of file");
  1194. }
  1195. }
  1196. uint32_t read_u32() const {
  1197. uint32_t ret;
  1198. read_raw(&ret, sizeof(ret));
  1199. return ret;
  1200. }
  1201. void write_raw(const void * ptr, size_t len) const {
  1202. if (len == 0) {
  1203. return;
  1204. }
  1205. errno = 0;
  1206. size_t ret = std::fwrite(ptr, len, 1, fp);
  1207. if (ret != 1) {
  1208. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1209. }
  1210. }
  1211. void write_u32(std::uint32_t val) const {
  1212. write_raw(&val, sizeof(val));
  1213. }
  1214. ~llama_file() {
  1215. if (fp) {
  1216. std::fclose(fp);
  1217. }
  1218. }
  1219. };
  1220. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1221. struct llama_mmap {
  1222. void * addr;
  1223. size_t size;
  1224. llama_mmap(const llama_mmap &) = delete;
  1225. #ifdef _POSIX_MAPPED_FILES
  1226. static constexpr bool SUPPORTED = true;
  1227. // list of mapped fragments (first_offset, last_offset)
  1228. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1229. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1230. size = file->size;
  1231. int fd = fileno(file->fp);
  1232. int flags = MAP_SHARED;
  1233. // prefetch/readahead impairs performance on NUMA systems
  1234. if (numa) { prefetch = 0; }
  1235. #ifdef __linux__
  1236. // advise the kernel to read the file sequentially (increases readahead)
  1237. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1238. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1239. strerror(errno));
  1240. }
  1241. if (prefetch) { flags |= MAP_POPULATE; }
  1242. #endif
  1243. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1244. if (addr == MAP_FAILED) { // NOLINT
  1245. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1246. }
  1247. if (prefetch > 0) {
  1248. // advise the kernel to preload the mapped memory
  1249. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1250. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1251. strerror(errno));
  1252. }
  1253. }
  1254. if (numa) {
  1255. // advise the kernel not to use readahead
  1256. // (because the next page might not belong on the same node)
  1257. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1258. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1259. strerror(errno));
  1260. }
  1261. }
  1262. // initialize list of mapped_fragments
  1263. mapped_fragments.emplace_back(0, file->size);
  1264. }
  1265. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1266. // align first to the next page
  1267. size_t offset_in_page = *first & (page_size - 1);
  1268. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1269. *first += offset_to_page;
  1270. // align last to the previous page
  1271. *last = *last & ~(page_size - 1);
  1272. if (*last <= *first) {
  1273. *last = *first;
  1274. }
  1275. }
  1276. // partially unmap the file in the range [first, last)
  1277. void unmap_fragment(size_t first, size_t last) {
  1278. // note: this function must not be called multiple times with overlapping ranges
  1279. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1280. int page_size = sysconf(_SC_PAGESIZE);
  1281. align_range(&first, &last, page_size);
  1282. size_t len = last - first;
  1283. if (len == 0) {
  1284. return;
  1285. }
  1286. GGML_ASSERT(first % page_size == 0);
  1287. GGML_ASSERT(last % page_size == 0);
  1288. GGML_ASSERT(last > first);
  1289. void * next_page_start = (uint8_t *) addr + first;
  1290. // unmap the range
  1291. if (munmap(next_page_start, len)) {
  1292. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1293. }
  1294. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1295. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1296. for (const auto & frag : mapped_fragments) {
  1297. if (frag.first < first && frag.second > last) {
  1298. // the range is in the middle of the fragment, split it
  1299. new_mapped_fragments.emplace_back(frag.first, first);
  1300. new_mapped_fragments.emplace_back(last, frag.second);
  1301. } else if (frag.first < first && frag.second > first) {
  1302. // the range starts in the middle of the fragment
  1303. new_mapped_fragments.emplace_back(frag.first, first);
  1304. } else if (frag.first < last && frag.second > last) {
  1305. // the range ends in the middle of the fragment
  1306. new_mapped_fragments.emplace_back(last, frag.second);
  1307. } else if (frag.first >= first && frag.second <= last) {
  1308. // the range covers the entire fragment
  1309. } else {
  1310. // the range is outside the fragment
  1311. new_mapped_fragments.push_back(frag);
  1312. }
  1313. }
  1314. mapped_fragments = std::move(new_mapped_fragments);
  1315. }
  1316. ~llama_mmap() {
  1317. for (const auto & frag : mapped_fragments) {
  1318. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1319. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1320. }
  1321. }
  1322. }
  1323. #elif defined(_WIN32)
  1324. static constexpr bool SUPPORTED = true;
  1325. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1326. GGML_UNUSED(numa);
  1327. size = file->size;
  1328. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1329. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1330. if (hMapping == NULL) {
  1331. DWORD error = GetLastError();
  1332. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1333. }
  1334. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1335. DWORD error = GetLastError();
  1336. CloseHandle(hMapping);
  1337. if (addr == NULL) {
  1338. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1339. }
  1340. if (prefetch > 0) {
  1341. #if _WIN32_WINNT >= 0x602
  1342. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1343. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1344. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1345. // may fail on pre-Windows 8 systems
  1346. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1347. if (pPrefetchVirtualMemory) {
  1348. // advise the kernel to preload the mapped memory
  1349. WIN32_MEMORY_RANGE_ENTRY range;
  1350. range.VirtualAddress = addr;
  1351. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1352. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1353. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1354. llama_format_win_err(GetLastError()).c_str());
  1355. }
  1356. }
  1357. #else
  1358. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1359. #endif
  1360. }
  1361. }
  1362. void unmap_fragment(size_t first, size_t last) {
  1363. // not supported
  1364. GGML_UNUSED(first);
  1365. GGML_UNUSED(last);
  1366. }
  1367. ~llama_mmap() {
  1368. if (!UnmapViewOfFile(addr)) {
  1369. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1370. llama_format_win_err(GetLastError()).c_str());
  1371. }
  1372. }
  1373. #else
  1374. static constexpr bool SUPPORTED = false;
  1375. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1376. GGML_UNUSED(file);
  1377. GGML_UNUSED(prefetch);
  1378. GGML_UNUSED(numa);
  1379. throw std::runtime_error("mmap not supported");
  1380. }
  1381. void unmap_fragment(size_t first, size_t last) {
  1382. GGML_UNUSED(first);
  1383. GGML_UNUSED(last);
  1384. throw std::runtime_error("mmap not supported");
  1385. }
  1386. #endif
  1387. };
  1388. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1389. // Represents some region of memory being locked using mlock or VirtualLock;
  1390. // will automatically unlock on destruction.
  1391. struct llama_mlock {
  1392. void * addr = NULL;
  1393. size_t size = 0;
  1394. bool failed_already = false;
  1395. llama_mlock() {}
  1396. llama_mlock(const llama_mlock &) = delete;
  1397. ~llama_mlock() {
  1398. if (size) {
  1399. raw_unlock(addr, size);
  1400. }
  1401. }
  1402. void init(void * ptr) {
  1403. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1404. addr = ptr;
  1405. }
  1406. void grow_to(size_t target_size) {
  1407. GGML_ASSERT(addr);
  1408. if (failed_already) {
  1409. return;
  1410. }
  1411. size_t granularity = lock_granularity();
  1412. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1413. if (target_size > size) {
  1414. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1415. size = target_size;
  1416. } else {
  1417. failed_already = true;
  1418. }
  1419. }
  1420. }
  1421. #ifdef _POSIX_MEMLOCK_RANGE
  1422. static constexpr bool SUPPORTED = true;
  1423. static size_t lock_granularity() {
  1424. return (size_t) sysconf(_SC_PAGESIZE);
  1425. }
  1426. #ifdef __APPLE__
  1427. #define MLOCK_SUGGESTION \
  1428. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1429. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1430. #else
  1431. #define MLOCK_SUGGESTION \
  1432. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1433. #endif
  1434. bool raw_lock(const void * addr, size_t size) const {
  1435. if (!mlock(addr, size)) {
  1436. return true;
  1437. }
  1438. char* errmsg = std::strerror(errno);
  1439. bool suggest = (errno == ENOMEM);
  1440. // Check if the resource limit is fine after all
  1441. struct rlimit lock_limit;
  1442. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1443. suggest = false;
  1444. }
  1445. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1446. suggest = false;
  1447. }
  1448. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1449. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1450. return false;
  1451. }
  1452. #undef MLOCK_SUGGESTION
  1453. static void raw_unlock(void * addr, size_t size) {
  1454. if (munlock(addr, size)) {
  1455. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1456. }
  1457. }
  1458. #elif defined(_WIN32)
  1459. static constexpr bool SUPPORTED = true;
  1460. static size_t lock_granularity() {
  1461. SYSTEM_INFO si;
  1462. GetSystemInfo(&si);
  1463. return (size_t) si.dwPageSize;
  1464. }
  1465. bool raw_lock(void * ptr, size_t len) const {
  1466. for (int tries = 1; ; tries++) {
  1467. if (VirtualLock(ptr, len)) {
  1468. return true;
  1469. }
  1470. if (tries == 2) {
  1471. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1472. len, size, llama_format_win_err(GetLastError()).c_str());
  1473. return false;
  1474. }
  1475. // It failed but this was only the first try; increase the working
  1476. // set size and try again.
  1477. SIZE_T min_ws_size, max_ws_size;
  1478. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1479. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1480. llama_format_win_err(GetLastError()).c_str());
  1481. return false;
  1482. }
  1483. // Per MSDN: "The maximum number of pages that a process can lock
  1484. // is equal to the number of pages in its minimum working set minus
  1485. // a small overhead."
  1486. // Hopefully a megabyte is enough overhead:
  1487. size_t increment = len + 1048576;
  1488. // The minimum must be <= the maximum, so we need to increase both:
  1489. min_ws_size += increment;
  1490. max_ws_size += increment;
  1491. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1492. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1493. llama_format_win_err(GetLastError()).c_str());
  1494. return false;
  1495. }
  1496. }
  1497. }
  1498. static void raw_unlock(void * ptr, size_t len) {
  1499. if (!VirtualUnlock(ptr, len)) {
  1500. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1501. llama_format_win_err(GetLastError()).c_str());
  1502. }
  1503. }
  1504. #else
  1505. static constexpr bool SUPPORTED = false;
  1506. static size_t lock_granularity() {
  1507. return (size_t) 65536;
  1508. }
  1509. bool raw_lock(const void * addr, size_t len) const {
  1510. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1511. return false;
  1512. }
  1513. static void raw_unlock(const void * addr, size_t len) {}
  1514. #endif
  1515. };
  1516. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1517. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1518. std::vector<char> result(8, 0);
  1519. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  1520. if (n_tokens < 0) {
  1521. result.resize(-n_tokens);
  1522. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  1523. GGML_ASSERT(check == -n_tokens);
  1524. }
  1525. else {
  1526. result.resize(n_tokens);
  1527. }
  1528. return std::string(result.data(), result.size());
  1529. }
  1530. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1531. ggml_backend_buffer_type_t buft = nullptr;
  1532. #if defined(GGML_USE_CUDA)
  1533. // host buffers should only be used when data is expected to be copied to/from the GPU
  1534. if (host_buffer) {
  1535. buft = ggml_backend_cuda_host_buffer_type();
  1536. }
  1537. #elif defined(GGML_USE_SYCL)
  1538. if (host_buffer) {
  1539. buft = ggml_backend_sycl_host_buffer_type();
  1540. }
  1541. #elif defined(GGML_USE_CPU_HBM)
  1542. buft = ggml_backend_cpu_hbm_buffer_type();
  1543. #elif defined(GGML_USE_VULKAN)
  1544. if (host_buffer) {
  1545. buft = ggml_backend_vk_host_buffer_type();
  1546. }
  1547. #endif
  1548. if (buft == nullptr) {
  1549. buft = ggml_backend_cpu_buffer_type();
  1550. }
  1551. return buft;
  1552. GGML_UNUSED(host_buffer);
  1553. }
  1554. //
  1555. // globals
  1556. //
  1557. struct llama_state {
  1558. llama_state() {
  1559. #ifdef GGML_USE_METAL
  1560. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1561. #elif defined(GGML_USE_CUDA)
  1562. ggml_backend_cuda_log_set_callback(log_callback, log_callback_user_data);
  1563. #endif
  1564. }
  1565. // We save the log callback globally
  1566. ggml_log_callback log_callback = llama_log_callback_default;
  1567. void * log_callback_user_data = nullptr;
  1568. };
  1569. static llama_state g_state;
  1570. // available llama models
  1571. enum e_model {
  1572. MODEL_UNKNOWN,
  1573. MODEL_17M,
  1574. MODEL_22M,
  1575. MODEL_33M,
  1576. MODEL_109M,
  1577. MODEL_137M,
  1578. MODEL_335M,
  1579. MODEL_0_5B,
  1580. MODEL_1B,
  1581. MODEL_2B,
  1582. MODEL_3B,
  1583. MODEL_4B,
  1584. MODEL_7B,
  1585. MODEL_8B,
  1586. MODEL_12B,
  1587. MODEL_13B,
  1588. MODEL_14B,
  1589. MODEL_15B,
  1590. MODEL_20B,
  1591. MODEL_30B,
  1592. MODEL_34B,
  1593. MODEL_35B,
  1594. MODEL_40B,
  1595. MODEL_65B,
  1596. MODEL_70B,
  1597. MODEL_314B,
  1598. MODEL_SMALL,
  1599. MODEL_MEDIUM,
  1600. MODEL_LARGE,
  1601. MODEL_XL,
  1602. MODEL_A2_7B,
  1603. MODEL_8x7B,
  1604. MODEL_8x22B,
  1605. MODEL_16x12B,
  1606. };
  1607. static const size_t kiB = 1024;
  1608. static const size_t MiB = 1024*kiB;
  1609. static const size_t GiB = 1024*MiB;
  1610. struct llama_hparams {
  1611. bool vocab_only;
  1612. bool rope_finetuned;
  1613. uint32_t n_vocab;
  1614. uint32_t n_ctx_train; // context size the model was trained on
  1615. uint32_t n_embd;
  1616. uint32_t n_head;
  1617. uint32_t n_head_kv;
  1618. uint32_t n_layer;
  1619. uint32_t n_rot;
  1620. 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
  1621. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1622. uint32_t n_ff;
  1623. uint32_t n_expert = 0;
  1624. uint32_t n_expert_used = 0;
  1625. uint32_t n_vocab_type = 0; // for BERT-style token types
  1626. float f_norm_eps;
  1627. float f_norm_rms_eps;
  1628. float rope_freq_base_train;
  1629. float rope_freq_scale_train;
  1630. uint32_t n_yarn_orig_ctx;
  1631. // for State Space Models
  1632. uint32_t ssm_d_conv = 0;
  1633. uint32_t ssm_d_inner = 0;
  1634. uint32_t ssm_d_state = 0;
  1635. uint32_t ssm_dt_rank = 0;
  1636. float f_clamp_kqv = 0.0f;
  1637. float f_max_alibi_bias = 0.0f;
  1638. float f_logit_scale = 0.0f;
  1639. bool causal_attn = true;
  1640. bool use_alibi = false;
  1641. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1642. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1643. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1644. bool operator!=(const llama_hparams & other) const {
  1645. if (this->vocab_only != other.vocab_only) return true;
  1646. if (this->n_vocab != other.n_vocab) return true;
  1647. if (this->n_ctx_train != other.n_ctx_train) return true;
  1648. if (this->n_embd != other.n_embd) return true;
  1649. if (this->n_head != other.n_head) return true;
  1650. if (this->n_head_kv != other.n_head_kv) return true;
  1651. if (this->n_layer != other.n_layer) return true;
  1652. if (this->n_rot != other.n_rot) return true;
  1653. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1654. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1655. if (this->n_ff != other.n_ff) return true;
  1656. if (this->n_expert != other.n_expert) return true;
  1657. if (this->n_expert_used != other.n_expert_used) return true;
  1658. if (this->rope_finetuned != other.rope_finetuned) return true;
  1659. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1660. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1661. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1662. if (this->ssm_d_state != other.ssm_d_state) return true;
  1663. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1664. const float EPSILON = 1e-9f;
  1665. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1666. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1667. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1668. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1669. return false;
  1670. }
  1671. uint32_t n_gqa() const {
  1672. if (n_head_kv == 0) {
  1673. return 0;
  1674. }
  1675. return n_head/n_head_kv;
  1676. }
  1677. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1678. return n_embd_head_k * n_head_kv;
  1679. }
  1680. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1681. return n_embd_head_v * n_head_kv;
  1682. }
  1683. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1684. // corresponds to Mamba's conv_states size
  1685. // TODO: maybe support other convolution strides than 1
  1686. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1687. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1688. }
  1689. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1690. // corresponds to Mamba's ssm_states size
  1691. return ssm_d_state * ssm_d_inner;
  1692. }
  1693. };
  1694. struct llama_cparams {
  1695. uint32_t n_ctx; // context size used during inference
  1696. uint32_t n_batch;
  1697. uint32_t n_ubatch;
  1698. uint32_t n_seq_max;
  1699. uint32_t n_threads; // number of threads to use for generation
  1700. uint32_t n_threads_batch; // number of threads to use for batch processing
  1701. float rope_freq_base;
  1702. float rope_freq_scale;
  1703. uint32_t n_yarn_orig_ctx;
  1704. // These hyperparameters are not exposed in GGUF, because all
  1705. // existing YaRN models use the same values for them.
  1706. float yarn_ext_factor;
  1707. float yarn_attn_factor;
  1708. float yarn_beta_fast;
  1709. float yarn_beta_slow;
  1710. float defrag_thold;
  1711. bool embeddings;
  1712. bool causal_attn;
  1713. bool offload_kqv;
  1714. bool flash_attn;
  1715. enum llama_pooling_type pooling_type;
  1716. ggml_backend_sched_eval_callback cb_eval;
  1717. void * cb_eval_user_data;
  1718. };
  1719. struct llama_layer {
  1720. // normalization
  1721. struct ggml_tensor * attn_norm;
  1722. struct ggml_tensor * attn_norm_b;
  1723. struct ggml_tensor * attn_norm_2;
  1724. struct ggml_tensor * attn_norm_2_b;
  1725. struct ggml_tensor * attn_q_norm;
  1726. struct ggml_tensor * attn_q_norm_b;
  1727. struct ggml_tensor * attn_k_norm;
  1728. struct ggml_tensor * attn_k_norm_b;
  1729. struct ggml_tensor * attn_out_norm;
  1730. struct ggml_tensor * attn_out_norm_b;
  1731. // attention
  1732. struct ggml_tensor * wq;
  1733. struct ggml_tensor * wk;
  1734. struct ggml_tensor * wv;
  1735. struct ggml_tensor * wo;
  1736. struct ggml_tensor * wqkv;
  1737. // attention bias
  1738. struct ggml_tensor * bq;
  1739. struct ggml_tensor * bk;
  1740. struct ggml_tensor * bv;
  1741. struct ggml_tensor * bo;
  1742. struct ggml_tensor * bqkv;
  1743. // normalization
  1744. struct ggml_tensor * ffn_norm;
  1745. struct ggml_tensor * ffn_norm_b;
  1746. struct ggml_tensor * layer_out_norm;
  1747. struct ggml_tensor * layer_out_norm_b;
  1748. // ff
  1749. struct ggml_tensor * ffn_gate; // w1
  1750. struct ggml_tensor * ffn_down; // w2
  1751. struct ggml_tensor * ffn_up; // w3
  1752. // ff MoE
  1753. struct ggml_tensor * ffn_gate_inp;
  1754. struct ggml_tensor * ffn_gate_exps;
  1755. struct ggml_tensor * ffn_down_exps;
  1756. struct ggml_tensor * ffn_up_exps ;
  1757. // ff shared expert (shexp)
  1758. struct ggml_tensor * ffn_gate_inp_shexp;
  1759. struct ggml_tensor * ffn_gate_shexp;
  1760. struct ggml_tensor * ffn_down_shexp;
  1761. struct ggml_tensor * ffn_up_shexp;
  1762. // ff bias
  1763. struct ggml_tensor * ffn_down_b; // b2
  1764. struct ggml_tensor * ffn_up_b; // b3
  1765. struct ggml_tensor * ffn_act;
  1766. // mamba proj
  1767. struct ggml_tensor * ssm_in;
  1768. struct ggml_tensor * ssm_x;
  1769. struct ggml_tensor * ssm_dt;
  1770. struct ggml_tensor * ssm_out;
  1771. // mamba
  1772. struct ggml_tensor * ssm_conv1d;
  1773. struct ggml_tensor * ssm_a;
  1774. struct ggml_tensor * ssm_d;
  1775. // mamba bias
  1776. struct ggml_tensor * ssm_conv1d_b;
  1777. struct ggml_tensor * ssm_dt_b;
  1778. };
  1779. struct llama_kv_cell {
  1780. llama_pos pos = -1;
  1781. llama_pos delta = 0;
  1782. int32_t src = 0; // used by recurrent state models to copy states
  1783. std::set<llama_seq_id> seq_id;
  1784. bool has_seq_id(const llama_seq_id & id) const {
  1785. return seq_id.find(id) != seq_id.end();
  1786. }
  1787. bool is_empty() const {
  1788. return seq_id.empty();
  1789. }
  1790. bool is_same_seq(const llama_kv_cell & other) const {
  1791. return seq_id == other.seq_id;
  1792. }
  1793. };
  1794. // ring-buffer of cached KV data
  1795. struct llama_kv_cache {
  1796. bool has_shift = false;
  1797. bool do_defrag = false;
  1798. bool do_copy = false;
  1799. bool recurrent = false; // with recurrent state models, a cell can hold the state for more than one past token
  1800. bool v_trans = true; // the value tensor is transposed
  1801. // Note: The value of head isn't only used to optimize searching
  1802. // for a free KV slot. llama_decode_internal also uses it, so it
  1803. // cannot be freely changed after a slot has been allocated.
  1804. uint32_t head = 0;
  1805. uint32_t size = 0;
  1806. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1807. // computed before each graph build
  1808. uint32_t n = 0;
  1809. ggml_type type_k = GGML_TYPE_F16;
  1810. ggml_type type_v = GGML_TYPE_F16;
  1811. std::vector<llama_kv_cell> cells;
  1812. std::vector<struct ggml_tensor *> k_l; // per layer
  1813. std::vector<struct ggml_tensor *> v_l;
  1814. std::vector<struct ggml_context *> ctxs;
  1815. std::vector<ggml_backend_buffer_t> bufs;
  1816. size_t total_size() const {
  1817. size_t size = 0;
  1818. for (ggml_backend_buffer_t buf : bufs) {
  1819. size += ggml_backend_buffer_get_size(buf);
  1820. }
  1821. return size;
  1822. }
  1823. ~llama_kv_cache() {
  1824. for (struct ggml_context * ctx : ctxs) {
  1825. ggml_free(ctx);
  1826. }
  1827. for (ggml_backend_buffer_t buf : bufs) {
  1828. ggml_backend_buffer_free(buf);
  1829. }
  1830. }
  1831. };
  1832. struct llama_control_vector {
  1833. std::vector<struct ggml_tensor *> tensors; // per layer
  1834. std::vector<struct ggml_context *> ctxs;
  1835. std::vector<ggml_backend_buffer_t> bufs;
  1836. int32_t layer_start = -1;
  1837. int32_t layer_end = -1;
  1838. ggml_tensor * tensor_for(int il) const {
  1839. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1840. return nullptr;
  1841. }
  1842. return tensors[il];
  1843. }
  1844. ~llama_control_vector() {
  1845. for (struct ggml_context * ctx : ctxs) {
  1846. ggml_free(ctx);
  1847. }
  1848. for (ggml_backend_buffer_t buf : bufs) {
  1849. ggml_backend_buffer_free(buf);
  1850. }
  1851. }
  1852. };
  1853. struct llama_vocab {
  1854. using id = int32_t;
  1855. using token = std::string;
  1856. using ttype = llama_token_type;
  1857. struct token_data {
  1858. token text;
  1859. float score;
  1860. ttype type;
  1861. };
  1862. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1863. enum llama_vocab_pre_type type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  1864. std::unordered_map<token, id> token_to_id;
  1865. std::vector<token_data> id_to_token;
  1866. std::unordered_map<token, id> special_tokens_cache;
  1867. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1868. // default LLaMA special tokens
  1869. id special_bos_id = 1;
  1870. id special_eos_id = 2;
  1871. id special_unk_id = 0;
  1872. id special_sep_id = -1;
  1873. id special_pad_id = -1;
  1874. id special_cls_id = -1;
  1875. id special_mask_id = -1;
  1876. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1877. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1878. id linefeed_id = 13;
  1879. id special_prefix_id = -1;
  1880. id special_suffix_id = -1;
  1881. id special_middle_id = -1;
  1882. id special_eot_id = -1; // TODO: move above after "eos_id", and here add "file separator" token
  1883. bool add_space_prefix = true;
  1884. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1885. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1886. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1887. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1888. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1889. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1890. if (it == bpe_ranks.end()) {
  1891. return -1;
  1892. }
  1893. return it->second;
  1894. }
  1895. };
  1896. struct llama_model {
  1897. e_model type = MODEL_UNKNOWN;
  1898. llm_arch arch = LLM_ARCH_UNKNOWN;
  1899. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1900. std::string name = "n/a";
  1901. llama_hparams hparams = {};
  1902. llama_vocab vocab;
  1903. struct ggml_tensor * tok_embd;
  1904. struct ggml_tensor * type_embd;
  1905. struct ggml_tensor * pos_embd;
  1906. struct ggml_tensor * tok_norm;
  1907. struct ggml_tensor * tok_norm_b;
  1908. struct ggml_tensor * output_norm;
  1909. struct ggml_tensor * output_norm_b;
  1910. struct ggml_tensor * output;
  1911. struct ggml_tensor * output_b;
  1912. std::vector<llama_layer> layers;
  1913. llama_split_mode split_mode;
  1914. int main_gpu;
  1915. int n_gpu_layers;
  1916. std::vector<std::string> rpc_servers;
  1917. // gguf metadata
  1918. std::unordered_map<std::string, std::string> gguf_kv;
  1919. // layer -> buffer type mapping
  1920. struct layer_buft {
  1921. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1922. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1923. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1924. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1925. ggml_backend_buffer_type_t buft; // everything else
  1926. };
  1927. layer_buft buft_input;
  1928. layer_buft buft_output;
  1929. std::vector<layer_buft> buft_layer;
  1930. // contexts where the model tensors metadata is stored
  1931. std::vector<struct ggml_context *> ctxs;
  1932. // the model memory buffers for the tensor data
  1933. std::vector<ggml_backend_buffer_t> bufs;
  1934. // model memory mapped files
  1935. llama_mmaps mappings;
  1936. // objects representing data potentially being locked in memory
  1937. llama_mlocks mlock_bufs;
  1938. llama_mlocks mlock_mmaps;
  1939. // for quantize-stats only
  1940. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1941. int64_t t_load_us = 0;
  1942. int64_t t_start_us = 0;
  1943. ~llama_model() {
  1944. for (struct ggml_context * ctx : ctxs) {
  1945. ggml_free(ctx);
  1946. }
  1947. for (ggml_backend_buffer_t buf : bufs) {
  1948. #ifdef GGML_USE_CUDA
  1949. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1950. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1951. }
  1952. #endif
  1953. ggml_backend_buffer_free(buf);
  1954. }
  1955. }
  1956. };
  1957. struct llama_context {
  1958. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1959. ~llama_context() {
  1960. ggml_backend_sched_free(sched);
  1961. for (ggml_backend_t backend : backends) {
  1962. ggml_backend_free(backend);
  1963. }
  1964. ggml_backend_buffer_free(buf_output);
  1965. }
  1966. llama_cparams cparams;
  1967. std::vector<ggml_backend_t> backends;
  1968. #ifdef GGML_USE_METAL
  1969. ggml_backend_t backend_metal = nullptr;
  1970. #endif
  1971. ggml_backend_t backend_cpu = nullptr;
  1972. const llama_model & model;
  1973. // key + value cache for the self attention
  1974. struct llama_kv_cache kv_self;
  1975. std::mt19937 rng;
  1976. bool has_evaluated_once = false;
  1977. int64_t t_start_us;
  1978. int64_t t_load_us;
  1979. int64_t t_sample_us = 0;
  1980. int64_t t_p_eval_us = 0;
  1981. int64_t t_eval_us = 0;
  1982. int64_t t_compute_start_us = 0;
  1983. int64_t n_queued_tokens = 0;
  1984. int32_t n_sample = 0; // number of tokens sampled
  1985. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1986. int32_t n_eval = 0; // number of eval calls
  1987. // host buffer for the model output (logits and embeddings)
  1988. ggml_backend_buffer_t buf_output = nullptr;
  1989. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1990. size_t logits_size = 0; // capacity (of floats) for logits
  1991. float * logits = nullptr;
  1992. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1993. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1994. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  1995. bool logits_all = false;
  1996. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1997. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1998. size_t embd_size = 0; // capacity (of floats) for embeddings
  1999. float * embd = nullptr;
  2000. // sequence embeddings output (map of [n_embd] vectors)
  2001. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  2002. std::map<llama_seq_id, std::vector<float>> embd_seq;
  2003. // memory buffers used to evaluate the model
  2004. std::vector<uint8_t> buf_compute_meta;
  2005. ggml_backend_sched_t sched = nullptr;
  2006. ggml_abort_callback abort_callback = nullptr;
  2007. void * abort_callback_data = nullptr;
  2008. // input tensors
  2009. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  2010. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  2011. struct ggml_tensor * inp_pos; // I32 [n_batch]
  2012. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  2013. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  2014. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  2015. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  2016. struct ggml_tensor * inp_cls; // I32 [n_batch]
  2017. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  2018. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  2019. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  2020. // control vectors
  2021. struct llama_control_vector cvec;
  2022. };
  2023. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(const llama_model & model, int gpu) {
  2024. ggml_backend_buffer_type_t buft = nullptr;
  2025. #ifdef GGML_USE_RPC
  2026. std::string endpoint = model.rpc_servers[gpu];
  2027. buft = ggml_backend_rpc_buffer_type(endpoint.c_str());
  2028. #elif defined(GGML_USE_METAL)
  2029. buft = ggml_backend_metal_buffer_type();
  2030. #elif defined(GGML_USE_CUDA)
  2031. buft = ggml_backend_cuda_buffer_type(gpu);
  2032. #elif defined(GGML_USE_VULKAN)
  2033. buft = ggml_backend_vk_buffer_type(gpu);
  2034. #elif defined(GGML_USE_SYCL)
  2035. buft = ggml_backend_sycl_buffer_type(gpu);
  2036. #elif defined(GGML_USE_CLBLAST)
  2037. buft = ggml_backend_opencl_buffer_type();
  2038. #elif defined(GGML_USE_KOMPUTE)
  2039. buft = ggml_backend_kompute_buffer_type(gpu);
  2040. if (buft == nullptr) {
  2041. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  2042. }
  2043. #endif
  2044. if (buft == nullptr) {
  2045. buft = llama_default_buffer_type_cpu(true);
  2046. }
  2047. return buft;
  2048. GGML_UNUSED(model);
  2049. GGML_UNUSED(gpu);
  2050. }
  2051. static ggml_backend_buffer_type_t llama_default_buffer_type_split(const llama_model & model, int fallback_gpu, const float * tensor_split) {
  2052. ggml_backend_buffer_type_t buft = nullptr;
  2053. #ifdef GGML_USE_CUDA
  2054. if (ggml_backend_cuda_get_device_count() > 1) {
  2055. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  2056. }
  2057. #endif
  2058. #ifdef GGML_USE_SYCL
  2059. if (ggml_backend_sycl_get_device_count() > 1) {
  2060. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  2061. }
  2062. #endif
  2063. if (buft == nullptr) {
  2064. buft = llama_default_buffer_type_offload(model, fallback_gpu);
  2065. }
  2066. return buft;
  2067. GGML_UNUSED(tensor_split);
  2068. }
  2069. static size_t llama_get_device_count(const llama_model & model) {
  2070. #if defined(GGML_USE_RPC)
  2071. return model.rpc_servers.size();
  2072. #elif defined(GGML_USE_CUDA)
  2073. return ggml_backend_cuda_get_device_count();
  2074. #elif defined(GGML_USE_SYCL)
  2075. return ggml_backend_sycl_get_device_count();
  2076. #elif defined(GGML_USE_VULKAN)
  2077. return ggml_backend_vk_get_device_count();
  2078. #else
  2079. return 1;
  2080. #endif
  2081. GGML_UNUSED(model);
  2082. }
  2083. static size_t llama_get_device_memory(const llama_model & model, int device) {
  2084. #if defined(GGML_USE_RPC)
  2085. size_t total;
  2086. size_t free;
  2087. std::string endpoint = model.rpc_servers[device];
  2088. ggml_backend_rpc_get_device_memory(endpoint.c_str(), &free, &total);
  2089. return free;
  2090. #elif defined(GGML_USE_CUDA)
  2091. size_t total;
  2092. size_t free;
  2093. ggml_backend_cuda_get_device_memory(device, &free, &total);
  2094. return free;
  2095. #elif defined(GGML_USE_SYCL)
  2096. size_t total;
  2097. size_t free;
  2098. ggml_backend_sycl_get_device_memory(device, &free, &total);
  2099. return free;
  2100. #elif defined(GGML_USE_VULKAN)
  2101. size_t total;
  2102. size_t free;
  2103. ggml_backend_vk_get_device_memory(device, &free, &total);
  2104. return free;
  2105. #else
  2106. return 1;
  2107. #endif
  2108. GGML_UNUSED(model);
  2109. GGML_UNUSED(device);
  2110. }
  2111. //
  2112. // kv cache helpers
  2113. //
  2114. static bool llama_kv_cache_init(
  2115. struct llama_kv_cache & cache,
  2116. const llama_context * ctx,
  2117. ggml_type type_k,
  2118. ggml_type type_v,
  2119. uint32_t kv_size,
  2120. bool offload) {
  2121. const llama_model & model = ctx->model;
  2122. const llama_cparams & cparams = ctx->cparams;
  2123. const struct llama_hparams & hparams = model.hparams;
  2124. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  2125. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  2126. const int64_t n_layer = hparams.n_layer;
  2127. cache.has_shift = false;
  2128. // TODO: find a nicer way to add other recurrent model architectures
  2129. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2130. cache.v_trans = !cparams.flash_attn;
  2131. // TODO: support mixed recurrent Transformer architectures
  2132. // NOTE: (!a || b) is a logical implication (a -> b)
  2133. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  2134. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  2135. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  2136. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  2137. cache.head = 0;
  2138. cache.size = kv_size;
  2139. cache.used = 0;
  2140. cache.type_k = type_k;
  2141. cache.type_v = type_v;
  2142. cache.cells.clear();
  2143. cache.cells.resize(kv_size);
  2144. if (cache.recurrent) {
  2145. // init state copy sources
  2146. for (uint32_t i = 0; i < cache.size; ++i) {
  2147. cache.cells[i].src = i;
  2148. }
  2149. }
  2150. #ifdef GGML_USE_CLBLAST
  2151. offload = false;
  2152. #endif
  2153. // count used buffer types
  2154. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2155. if (offload) {
  2156. for (int64_t i = 0; i < n_layer; ++i) {
  2157. buft_layer_count[model.buft_layer[i].buft]++;
  2158. }
  2159. } else {
  2160. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2161. }
  2162. // create a context for each buffer type
  2163. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2164. for (auto & it : buft_layer_count) {
  2165. int n_layers = it.second;
  2166. struct ggml_init_params params = {
  2167. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2168. /*.mem_buffer =*/ NULL,
  2169. /*.no_alloc =*/ true,
  2170. };
  2171. ggml_context * ctx = ggml_init(params);
  2172. if (!ctx) {
  2173. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2174. return false;
  2175. }
  2176. ctx_map[it.first] = ctx;
  2177. cache.ctxs.push_back(ctx);
  2178. }
  2179. cache.k_l.reserve(n_layer);
  2180. cache.v_l.reserve(n_layer);
  2181. for (int i = 0; i < (int) n_layer; i++) {
  2182. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2183. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2184. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2185. ggml_format_name(k, "cache_k_l%d", i);
  2186. ggml_format_name(v, "cache_v_l%d", i);
  2187. cache.k_l.push_back(k);
  2188. cache.v_l.push_back(v);
  2189. }
  2190. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2191. for (auto it : ctx_map) {
  2192. ggml_backend_buffer_type_t buft = it.first;
  2193. ggml_context * ctx = it.second;
  2194. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2195. if (!buf) {
  2196. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2197. return false;
  2198. }
  2199. ggml_backend_buffer_clear(buf, 0);
  2200. 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);
  2201. cache.bufs.push_back(buf);
  2202. }
  2203. return true;
  2204. }
  2205. // find an empty slot of size "n_tokens" in the cache
  2206. // updates the cache head
  2207. // Note: On success, it's important that cache.head points
  2208. // to the first cell of the slot.
  2209. static bool llama_kv_cache_find_slot(
  2210. struct llama_kv_cache & cache,
  2211. const struct llama_batch & batch) {
  2212. const uint32_t n_ctx = cache.size;
  2213. const uint32_t n_tokens = batch.n_tokens;
  2214. if (cache.recurrent) {
  2215. // For recurrent state architectures (like Mamba),
  2216. // each KV cache cell can store the state for a whole sequence.
  2217. llama_seq_id min = cache.size - 1;
  2218. llama_seq_id max = 0;
  2219. for (uint32_t i = 0; i < n_tokens; ++i) {
  2220. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2221. llama_seq_id seq_id = batch.seq_id[i][j];
  2222. // make sure it's a valid seq_id
  2223. if ((uint32_t) seq_id < cache.size) {
  2224. if (seq_id > max) {
  2225. max = seq_id;
  2226. }
  2227. if (seq_id < min) {
  2228. min = seq_id;
  2229. }
  2230. // Assuming the tokens are in-order
  2231. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2232. // What should happen when the pos backtracks or skips a value?
  2233. // Clearing the state mid-batch would require special-casing which isn't done.
  2234. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2235. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2236. }
  2237. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2238. cache.used += 1;
  2239. }
  2240. cache.cells[seq_id].pos = batch.pos[i];
  2241. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2242. } else {
  2243. // too big seq_id
  2244. // TODO: would it be possible to resize the KV cache size instead?
  2245. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2246. return false;
  2247. }
  2248. }
  2249. }
  2250. // allow getting the range of used cells, from head to head + n
  2251. cache.head = min;
  2252. cache.n = max - min + 1;
  2253. // sanity check
  2254. return max >= min;
  2255. }
  2256. // otherwise, one cell per token.
  2257. if (n_tokens > n_ctx) {
  2258. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2259. return false;
  2260. }
  2261. uint32_t n_tested = 0;
  2262. while (true) {
  2263. if (cache.head + n_tokens > n_ctx) {
  2264. n_tested += n_ctx - cache.head;
  2265. cache.head = 0;
  2266. continue;
  2267. }
  2268. bool found = true;
  2269. for (uint32_t i = 0; i < n_tokens; i++) {
  2270. if (cache.cells[cache.head + i].pos >= 0) {
  2271. found = false;
  2272. cache.head += i + 1;
  2273. n_tested += i + 1;
  2274. break;
  2275. }
  2276. }
  2277. if (found) {
  2278. break;
  2279. }
  2280. if (n_tested >= n_ctx) {
  2281. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2282. return false;
  2283. }
  2284. }
  2285. for (uint32_t i = 0; i < n_tokens; i++) {
  2286. cache.cells[cache.head + i].pos = batch.pos[i];
  2287. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2288. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2289. }
  2290. }
  2291. cache.used += n_tokens;
  2292. return true;
  2293. }
  2294. // find how many cells are currently in use
  2295. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2296. for (uint32_t i = cache.size; i > 0; --i) {
  2297. const llama_kv_cell & cell = cache.cells[i - 1];
  2298. if (cell.pos >= 0 && !cell.is_empty()) {
  2299. return i;
  2300. }
  2301. }
  2302. return 0;
  2303. }
  2304. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2305. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2306. cache.cells[i].pos = -1;
  2307. cache.cells[i].seq_id.clear();
  2308. }
  2309. cache.head = 0;
  2310. cache.used = 0;
  2311. for (auto & buf : cache.bufs) {
  2312. ggml_backend_buffer_clear(buf, 0);
  2313. }
  2314. }
  2315. static bool llama_kv_cache_seq_rm(
  2316. struct llama_kv_cache & cache,
  2317. llama_seq_id seq_id,
  2318. llama_pos p0,
  2319. llama_pos p1) {
  2320. uint32_t new_head = cache.size;
  2321. if (p0 < 0) p0 = 0;
  2322. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2323. // models like Mamba can't have a state partially erased
  2324. if (cache.recurrent) {
  2325. if (seq_id >= (int64_t) cache.size) {
  2326. // could be fatal
  2327. return false;
  2328. }
  2329. if (0 <= seq_id) {
  2330. // partial intersection is invalid
  2331. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2332. return false;
  2333. }
  2334. } else {
  2335. // seq_id is negative, then the range should include everything or nothing
  2336. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2337. return false;
  2338. }
  2339. }
  2340. }
  2341. for (uint32_t i = 0; i < cache.size; ++i) {
  2342. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2343. if (seq_id < 0) {
  2344. cache.cells[i].seq_id.clear();
  2345. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2346. cache.cells[i].seq_id.erase(seq_id);
  2347. } else {
  2348. continue;
  2349. }
  2350. if (cache.cells[i].is_empty()) {
  2351. // keep count of the number of used cells
  2352. if (cache.cells[i].pos >= 0) cache.used--;
  2353. cache.cells[i].pos = -1;
  2354. if (new_head == cache.size) new_head = i;
  2355. }
  2356. }
  2357. }
  2358. // If we freed up a slot, set head to it so searching can start there.
  2359. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2360. return true;
  2361. }
  2362. static void llama_kv_cache_seq_cp(
  2363. struct llama_kv_cache & cache,
  2364. llama_seq_id seq_id_src,
  2365. llama_seq_id seq_id_dst,
  2366. llama_pos p0,
  2367. llama_pos p1) {
  2368. if (p0 < 0) p0 = 0;
  2369. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2370. if (cache.recurrent) {
  2371. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2372. seq_id_src = cache.cells[seq_id_src].src;
  2373. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2374. // intent to "copy from"
  2375. // supports copy chains thanks to taking the source of the source
  2376. cache.cells[seq_id_dst].src = seq_id_src;
  2377. // preserve the "keep or clear" status of the copied sequence
  2378. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2379. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2380. } else {
  2381. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2382. }
  2383. cache.do_copy = true;
  2384. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2385. }
  2386. return;
  2387. }
  2388. // otherwise, this is the KV cache of a Transformer-like model
  2389. cache.head = 0;
  2390. for (uint32_t i = 0; i < cache.size; ++i) {
  2391. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2392. cache.cells[i].seq_id.insert(seq_id_dst);
  2393. }
  2394. }
  2395. }
  2396. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2397. uint32_t new_head = cache.size;
  2398. for (uint32_t i = 0; i < cache.size; ++i) {
  2399. if (!cache.cells[i].has_seq_id(seq_id)) {
  2400. if (cache.cells[i].pos >= 0) cache.used--;
  2401. cache.cells[i].pos = -1;
  2402. cache.cells[i].seq_id.clear();
  2403. if (new_head == cache.size) new_head = i;
  2404. } else {
  2405. cache.cells[i].seq_id.clear();
  2406. cache.cells[i].seq_id.insert(seq_id);
  2407. }
  2408. }
  2409. // If we freed up a slot, set head to it so searching can start there.
  2410. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2411. }
  2412. static void llama_kv_cache_seq_add(
  2413. struct llama_kv_cache & cache,
  2414. llama_seq_id seq_id,
  2415. llama_pos p0,
  2416. llama_pos p1,
  2417. llama_pos delta) {
  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. if (cache.recurrent) {
  2422. // for Mamba-like models, only the pos needs to be shifted
  2423. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2424. llama_kv_cell & cell = cache.cells[seq_id];
  2425. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2426. cell.pos += delta;
  2427. }
  2428. }
  2429. return;
  2430. }
  2431. for (uint32_t i = 0; i < cache.size; ++i) {
  2432. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2433. cache.has_shift = true;
  2434. cache.cells[i].pos += delta;
  2435. cache.cells[i].delta += delta;
  2436. if (cache.cells[i].pos < 0) {
  2437. if (!cache.cells[i].is_empty()) {
  2438. cache.used--;
  2439. }
  2440. cache.cells[i].pos = -1;
  2441. cache.cells[i].seq_id.clear();
  2442. if (new_head == cache.size) {
  2443. new_head = i;
  2444. }
  2445. }
  2446. }
  2447. }
  2448. // If we freed up a slot, set head to it so searching can start there.
  2449. // Otherwise we just start the next search from the beginning.
  2450. cache.head = new_head != cache.size ? new_head : 0;
  2451. }
  2452. static void llama_kv_cache_seq_div(
  2453. struct llama_kv_cache & cache,
  2454. llama_seq_id seq_id,
  2455. llama_pos p0,
  2456. llama_pos p1,
  2457. int d) {
  2458. if (p0 < 0) p0 = 0;
  2459. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2460. if (cache.recurrent) {
  2461. // for Mamba-like models, only the pos needs to be changed
  2462. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2463. llama_kv_cell & cell = cache.cells[seq_id];
  2464. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2465. cell.pos /= d;
  2466. }
  2467. }
  2468. return;
  2469. }
  2470. for (uint32_t i = 0; i < cache.size; ++i) {
  2471. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2472. cache.has_shift = true;
  2473. {
  2474. llama_pos p_old = cache.cells[i].pos;
  2475. cache.cells[i].pos /= d;
  2476. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2477. }
  2478. }
  2479. }
  2480. }
  2481. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2482. llama_pos result = 0;
  2483. for (uint32_t i = 0; i < cache.size; ++i) {
  2484. if (cache.cells[i].has_seq_id(seq_id)) {
  2485. result = std::max(result, cache.cells[i].pos);
  2486. }
  2487. }
  2488. return result;
  2489. }
  2490. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2491. cache.do_defrag = true;
  2492. }
  2493. static uint32_t llama_kv_cache_get_padding(const struct llama_cparams & cparams) {
  2494. // the FA kernels require padding to avoid extra runtime boundary checks
  2495. return cparams.flash_attn ? 256u : 32u;
  2496. }
  2497. //
  2498. // model loading and saving
  2499. //
  2500. enum llama_fver {
  2501. GGUF_FILE_VERSION_V1 = 1,
  2502. GGUF_FILE_VERSION_V2 = 2,
  2503. GGUF_FILE_VERSION_V3 = 3,
  2504. };
  2505. static const char * llama_file_version_name(llama_fver version) {
  2506. switch (version) {
  2507. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2508. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2509. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2510. }
  2511. return "unknown";
  2512. }
  2513. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2514. char buf[256];
  2515. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2516. for (size_t i = 1; i < ne.size(); i++) {
  2517. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2518. }
  2519. return buf;
  2520. }
  2521. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2522. char buf[256];
  2523. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2524. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2525. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2526. }
  2527. return buf;
  2528. }
  2529. namespace GGUFMeta {
  2530. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2531. struct GKV_Base_Type {
  2532. static constexpr gguf_type gt = gt_;
  2533. static T getter(const gguf_context * ctx, const int kid) {
  2534. return gfun(ctx, kid);
  2535. }
  2536. };
  2537. template<typename T> struct GKV_Base;
  2538. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2539. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2540. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2541. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2542. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2543. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2544. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2545. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2546. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2547. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2548. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2549. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2550. template<> struct GKV_Base<std::string> {
  2551. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2552. static std::string getter(const gguf_context * ctx, const int kid) {
  2553. return gguf_get_val_str(ctx, kid);
  2554. }
  2555. };
  2556. struct ArrayInfo {
  2557. const gguf_type gt;
  2558. const size_t length;
  2559. const void * data;
  2560. };
  2561. template<> struct GKV_Base<ArrayInfo> {
  2562. public:
  2563. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2564. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2565. return ArrayInfo {
  2566. gguf_get_arr_type(ctx, k),
  2567. size_t(gguf_get_arr_n(ctx, k)),
  2568. gguf_get_arr_data(ctx, k),
  2569. };
  2570. }
  2571. };
  2572. template<typename T>
  2573. class GKV : public GKV_Base<T> {
  2574. GKV() = delete;
  2575. public:
  2576. static T get_kv(const gguf_context * ctx, const int k) {
  2577. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2578. if (kt != GKV::gt) {
  2579. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2580. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2581. }
  2582. return GKV::getter(ctx, k);
  2583. }
  2584. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2585. switch (ty) {
  2586. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2587. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2588. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2589. case LLAMA_KV_OVERRIDE_TYPE_STR: return "str";
  2590. }
  2591. return "unknown";
  2592. }
  2593. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2594. if (!ovrd) { return false; }
  2595. if (ovrd->tag == expected_type) {
  2596. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2597. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2598. switch (ovrd->tag) {
  2599. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2600. LLAMA_LOG_INFO("%s\n", ovrd->val_bool ? "true" : "false");
  2601. } break;
  2602. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2603. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->val_i64);
  2604. } break;
  2605. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2606. LLAMA_LOG_INFO("%.6f\n", ovrd->val_f64);
  2607. } break;
  2608. case LLAMA_KV_OVERRIDE_TYPE_STR: {
  2609. LLAMA_LOG_INFO("%s\n", ovrd->val_str);
  2610. } break;
  2611. default:
  2612. // Shouldn't be possible to end up here, but just in case...
  2613. throw std::runtime_error(
  2614. format("Unsupported attempt to override %s type for metadata key %s\n",
  2615. override_type_to_str(ovrd->tag), ovrd->key));
  2616. }
  2617. return true;
  2618. }
  2619. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2620. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2621. return false;
  2622. }
  2623. template<typename OT>
  2624. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2625. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2626. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2627. target = ovrd->val_bool;
  2628. return true;
  2629. }
  2630. return false;
  2631. }
  2632. template<typename OT>
  2633. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2634. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2635. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2636. target = ovrd->val_i64;
  2637. return true;
  2638. }
  2639. return false;
  2640. }
  2641. template<typename OT>
  2642. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2643. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2644. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2645. target = ovrd->val_f64;
  2646. return true;
  2647. }
  2648. return false;
  2649. }
  2650. template<typename OT>
  2651. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2652. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2653. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_STR, ovrd)) {
  2654. target = ovrd->val_str;
  2655. return true;
  2656. }
  2657. return false;
  2658. }
  2659. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2660. if (try_override<T>(target, ovrd)) {
  2661. return true;
  2662. }
  2663. if (k < 0) { return false; }
  2664. target = get_kv(ctx, k);
  2665. return true;
  2666. }
  2667. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2668. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2669. }
  2670. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2671. return set(ctx, key.c_str(), target, ovrd);
  2672. }
  2673. };
  2674. }
  2675. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2676. struct llama_model_loader {
  2677. int n_kv = 0;
  2678. int n_tensors = 0;
  2679. int n_created = 0;
  2680. int64_t n_elements = 0;
  2681. size_t n_bytes = 0;
  2682. bool use_mmap = false;
  2683. bool check_tensors;
  2684. llama_files files;
  2685. llama_ftype ftype;
  2686. llama_fver fver;
  2687. llama_mmaps mappings;
  2688. // Holds information on a model weight
  2689. struct llama_tensor_weight {
  2690. uint16_t idx; // source file index
  2691. size_t offs; // tensor data offset in the original file
  2692. ggml_tensor * tensor;
  2693. 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) {
  2694. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2695. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2696. if (offs + ggml_nbytes(tensor) < offs || offs + ggml_nbytes(tensor) > file->size) {
  2697. throw std::runtime_error(format("tensor '%s' data is not within the file bounds, model is corrupted or incomplete", name));
  2698. }
  2699. }
  2700. };
  2701. std::vector<llama_tensor_weight> weights;
  2702. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2703. struct gguf_context * meta = NULL;
  2704. std::vector<ggml_context *> contexts;
  2705. std::string arch_name;
  2706. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2707. llama_model_loader(const std::string & fname, bool use_mmap, bool check_tensors, const struct llama_model_kv_override * param_overrides_p) {
  2708. int trace = 0;
  2709. if (getenv("LLAMA_TRACE")) {
  2710. trace = atoi(getenv("LLAMA_TRACE"));
  2711. }
  2712. if (param_overrides_p != nullptr) {
  2713. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2714. kv_overrides.insert({std::string(p->key), *p});
  2715. }
  2716. }
  2717. struct ggml_context * ctx = NULL;
  2718. struct gguf_init_params params = {
  2719. /*.no_alloc = */ true,
  2720. /*.ctx = */ &ctx,
  2721. };
  2722. meta = gguf_init_from_file(fname.c_str(), params);
  2723. if (!meta) {
  2724. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2725. }
  2726. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2727. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2728. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2729. contexts.emplace_back(ctx);
  2730. // Save tensors data offset of the main file.
  2731. // For subsidiary files, `meta` tensor data offset must not be used,
  2732. // so we build a unified tensors index for weights.
  2733. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2734. weights.emplace_back(files.back().get(), 0, cur->name, meta, cur);
  2735. }
  2736. uint16_t n_split = 0;
  2737. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2738. // Load additional GGML contexts
  2739. if (n_split > 1) {
  2740. uint16_t idx = 0;
  2741. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2742. if (idx != 0) {
  2743. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2744. }
  2745. char split_prefix[PATH_MAX] = {0};
  2746. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2747. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2748. }
  2749. if (trace > 0) {
  2750. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2751. }
  2752. char split_path[PATH_MAX] = {0};
  2753. for (idx = 1; idx < n_split; idx++) {
  2754. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2755. struct gguf_init_params split_params = {
  2756. /*.no_alloc = */ true,
  2757. /*.ctx = */ &ctx,
  2758. };
  2759. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2760. if (!ctx_gguf) {
  2761. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2762. }
  2763. files.emplace_back(new llama_file(split_path, "rb"));
  2764. contexts.emplace_back(ctx);
  2765. // Save tensors data offset info of the shard.
  2766. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2767. weights.emplace_back(files.back().get(), idx, cur->name, ctx_gguf, cur);
  2768. }
  2769. gguf_free(ctx_gguf);
  2770. }
  2771. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2772. // sanity check
  2773. {
  2774. const int n_tensors_loaded = (int) weights.size();
  2775. if (n_tensors != n_tensors_loaded) {
  2776. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2777. }
  2778. }
  2779. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2780. }
  2781. n_kv = gguf_get_n_kv(meta);
  2782. n_tensors = weights.size();
  2783. fver = (enum llama_fver) gguf_get_version(meta);
  2784. std::set<std::string> tensor_names;
  2785. for (auto & w : weights) {
  2786. n_elements += ggml_nelements(w.tensor);
  2787. n_bytes += ggml_nbytes(w.tensor);
  2788. // make sure there is no duplicated tensor names
  2789. const std::string name(w.tensor->name);
  2790. auto found = tensor_names.find(name);
  2791. if (found != tensor_names.end()) {
  2792. throw std::runtime_error(format("invalid model: tensor '%s' is duplicated", w.tensor->name));
  2793. }
  2794. tensor_names.insert(name);
  2795. }
  2796. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2797. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2798. // determine file type based on the number of tensors for each quantization and print meta data
  2799. // TODO: make optional
  2800. {
  2801. std::map<enum ggml_type, uint32_t> n_type;
  2802. uint32_t n_type_max = 0;
  2803. enum ggml_type type_max = GGML_TYPE_F32;
  2804. for (int i = 0; i < n_tensors; i++) {
  2805. const ggml_tensor * tensor = weights.at(i).tensor;
  2806. enum ggml_type type = tensor->type;
  2807. n_type[type]++;
  2808. if (n_type_max < n_type[type]) {
  2809. n_type_max = n_type[type];
  2810. type_max = type;
  2811. }
  2812. if (trace > 0) {
  2813. const uint16_t sid = weights.at(i).idx;
  2814. 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());
  2815. }
  2816. }
  2817. switch (type_max) {
  2818. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2819. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2820. case GGML_TYPE_BF16: ftype = LLAMA_FTYPE_MOSTLY_BF16; break;
  2821. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2822. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2823. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2824. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2825. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2826. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2827. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2828. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2829. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2830. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2831. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2832. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2833. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2834. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2835. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2836. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2837. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2838. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2839. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2840. default:
  2841. {
  2842. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2843. ftype = LLAMA_FTYPE_ALL_F32;
  2844. } break;
  2845. }
  2846. // this is a way to mark that we have "guessed" the file type
  2847. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2848. {
  2849. const int kid = gguf_find_key(meta, "general.file_type");
  2850. if (kid >= 0) {
  2851. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2852. }
  2853. }
  2854. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2855. for (int i = 0; i < n_kv; i++) {
  2856. const char * name = gguf_get_key(meta, i);
  2857. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2858. const std::string type_name =
  2859. type == GGUF_TYPE_ARRAY
  2860. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2861. : gguf_type_name(type);
  2862. std::string value = gguf_kv_to_str(meta, i);
  2863. const size_t MAX_VALUE_LEN = 40;
  2864. if (value.size() > MAX_VALUE_LEN) {
  2865. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2866. }
  2867. replace_all(value, "\n", "\\n");
  2868. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2869. }
  2870. // print type counts
  2871. for (auto & kv : n_type) {
  2872. if (kv.second == 0) {
  2873. continue;
  2874. }
  2875. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2876. }
  2877. }
  2878. if (!llama_mmap::SUPPORTED) {
  2879. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2880. use_mmap = false;
  2881. }
  2882. this->use_mmap = use_mmap;
  2883. this->check_tensors = check_tensors;
  2884. }
  2885. ~llama_model_loader() {
  2886. if (meta) {
  2887. gguf_free(meta);
  2888. }
  2889. for (auto * ctx : contexts) {
  2890. ggml_free(ctx);
  2891. }
  2892. }
  2893. template<typename T>
  2894. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2895. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2896. const int kid = gguf_find_key(meta, key.c_str());
  2897. if (kid < 0) {
  2898. if (required) {
  2899. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2900. }
  2901. return false;
  2902. }
  2903. struct GGUFMeta::ArrayInfo arr_info =
  2904. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2905. result = arr_info.length;
  2906. return true;
  2907. }
  2908. template<typename T>
  2909. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2910. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2911. return get_arr_n(llm_kv(kid), result, required);
  2912. }
  2913. template<typename T>
  2914. bool get_key(const std::string & key, T & result, const bool required = true) {
  2915. auto it = kv_overrides.find(key);
  2916. const struct llama_model_kv_override * override =
  2917. it != kv_overrides.end() ? &it->second : nullptr;
  2918. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2919. if (required && !found) {
  2920. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2921. }
  2922. return found;
  2923. }
  2924. template<typename T>
  2925. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2926. return get_key(llm_kv(kid), result, required);
  2927. }
  2928. std::string get_arch_name() const {
  2929. return arch_name;
  2930. }
  2931. enum llm_arch get_arch() const {
  2932. return llm_kv.arch;
  2933. }
  2934. const char * get_tensor_name(int i) const {
  2935. return weights.at(i).tensor->name;
  2936. }
  2937. const llama_tensor_weight * get_weight(const char * name) const {
  2938. for (const auto & weight : weights) {
  2939. if (strcmp(name, weight.tensor->name) == 0) {
  2940. return &weight;
  2941. }
  2942. }
  2943. return nullptr;
  2944. }
  2945. const llama_tensor_weight * get_weight(int i) const {
  2946. return get_weight(get_tensor_name(i));
  2947. }
  2948. const llama_tensor_weight & require_weight(const char * name) const {
  2949. const llama_tensor_weight * weight = get_weight(name);
  2950. if (!weight) {
  2951. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2952. }
  2953. return *weight;
  2954. }
  2955. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2956. const auto * weight = get_weight(name);
  2957. if (!weight) {
  2958. return nullptr;
  2959. }
  2960. return weight->tensor;
  2961. }
  2962. struct ggml_tensor * require_tensor_meta(const char * name) const {
  2963. struct ggml_tensor * tensor = get_tensor_meta(name);
  2964. if (!tensor) {
  2965. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2966. }
  2967. return tensor;
  2968. }
  2969. struct ggml_tensor * get_tensor_meta(int i) const {
  2970. return get_tensor_meta(get_tensor_name(i));
  2971. }
  2972. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2973. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2974. ggml_set_name(tensor, ggml_get_name(cur));
  2975. n_created++;
  2976. return tensor;
  2977. }
  2978. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  2979. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2980. if (cur == NULL) {
  2981. if (!required) {
  2982. return NULL;
  2983. }
  2984. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2985. }
  2986. {
  2987. bool is_ok = true;
  2988. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2989. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  2990. is_ok = false;
  2991. break;
  2992. }
  2993. }
  2994. if (!is_ok) {
  2995. throw std::runtime_error(
  2996. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2997. __func__, name.c_str(),
  2998. llama_format_tensor_shape(ne).c_str(),
  2999. llama_format_tensor_shape(cur).c_str()));
  3000. }
  3001. }
  3002. return cur;
  3003. }
  3004. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  3005. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3006. if (cur == NULL) {
  3007. return NULL;
  3008. }
  3009. return create_tensor_for(ctx, cur);
  3010. }
  3011. 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) {
  3012. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  3013. if (cur == NULL) {
  3014. return NULL;
  3015. }
  3016. if (cur->type != base->type) {
  3017. 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)));
  3018. }
  3019. std::array<int64_t, GGML_MAX_DIMS> dims;
  3020. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  3021. dims[i] = i < ne.size() ? ne[i] : 1;
  3022. }
  3023. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  3024. dims[0], dims[1], dims[2], dims[3],
  3025. cur->nb[1], cur->nb[2], cur->nb[3],
  3026. offset);
  3027. ggml_set_name(tensor, name.c_str());
  3028. n_created++;
  3029. return tensor;
  3030. }
  3031. void done_getting_tensors() const {
  3032. if (n_created != n_tensors) {
  3033. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  3034. }
  3035. }
  3036. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  3037. if (use_mmap) {
  3038. mappings.reserve(files.size());
  3039. mmaps_used.reserve(files.size());
  3040. for (const auto & file : files) {
  3041. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  3042. mmaps_used.emplace_back(mapping->size, 0);
  3043. if (mlock_mmaps) {
  3044. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  3045. mlock_mmap->init(mapping->addr);
  3046. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  3047. }
  3048. mappings.emplace_back(std::move(mapping));
  3049. }
  3050. }
  3051. // compute the total size of all tensors for progress reporting
  3052. for (auto & w : weights) {
  3053. size_data += ggml_nbytes(w.tensor);
  3054. }
  3055. }
  3056. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  3057. GGML_ASSERT(!mappings.empty());
  3058. const auto & mapping = mappings.at(idx);
  3059. *first = mapping->size;
  3060. *last = 0;
  3061. *addr = mapping->addr;
  3062. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3063. try {
  3064. const auto * weight = get_weight(ggml_get_name(tensor));
  3065. if (!weight) {
  3066. continue;
  3067. }
  3068. if (weight->idx != idx) {
  3069. continue;
  3070. }
  3071. *first = std::min(*first, weight->offs);
  3072. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  3073. } catch(...) {
  3074. // the tensor is not in the model
  3075. }
  3076. }
  3077. }
  3078. // for backwards compatibility, does not support ggml-backend
  3079. void load_data_for(struct ggml_tensor * cur) const {
  3080. const auto & w = require_weight(ggml_get_name(cur));
  3081. if (use_mmap) {
  3082. const auto & mapping = mappings.at(w.idx);
  3083. if (cur->data == nullptr) {
  3084. cur->data = (uint8_t *)mapping->addr + w.offs;
  3085. } else {
  3086. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  3087. }
  3088. } else {
  3089. GGML_ASSERT(cur->data != nullptr);
  3090. GGML_ASSERT(w.idx < files.size());
  3091. const auto & file = files.at(w.idx);
  3092. file->seek(w.offs, SEEK_SET);
  3093. file->read_raw(cur->data, ggml_nbytes(cur));
  3094. }
  3095. if (check_tensors && !ggml_validate_row_data(cur->type, cur->data, ggml_nbytes(cur))) {
  3096. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3097. }
  3098. }
  3099. size_t size_done = 0;
  3100. size_t size_data = 0;
  3101. std::vector<std::pair<size_t, size_t>> mmaps_used;
  3102. // Returns false if cancelled by progress_callback
  3103. bool load_all_data(
  3104. struct ggml_context * ctx,
  3105. llama_buf_map & bufs_mmap,
  3106. llama_mlocks * lmlocks,
  3107. llama_progress_callback progress_callback,
  3108. void * progress_callback_user_data) {
  3109. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  3110. std::vector<no_init<uint8_t>> read_buf;
  3111. std::vector<std::future<std::pair<ggml_tensor *, bool>>> validation_result;
  3112. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3113. const auto * weight = get_weight(ggml_get_name(cur));
  3114. if (weight == nullptr) {
  3115. // this can happen with split experts models
  3116. continue;
  3117. }
  3118. if (progress_callback) {
  3119. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  3120. return false;
  3121. }
  3122. }
  3123. size_t n_size = ggml_nbytes(cur);
  3124. if (use_mmap) {
  3125. const auto & mapping = mappings.at(weight->idx);
  3126. ggml_backend_buffer_t buf_mmap = nullptr;
  3127. if (bufs_mmap.count(weight->idx)) {
  3128. buf_mmap = bufs_mmap.at(weight->idx);
  3129. }
  3130. uint8_t * data = (uint8_t *) mapping->addr + weight->offs;
  3131. if (check_tensors) {
  3132. validation_result.emplace_back(std::async(std::launch::async, [cur, data, n_size] {
  3133. return std::make_pair(cur, ggml_validate_row_data(cur->type, data, n_size));
  3134. }));
  3135. }
  3136. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  3137. if (buf_mmap && cur->data == nullptr) {
  3138. ggml_backend_tensor_alloc(buf_mmap, cur, data);
  3139. if (lmlocks) {
  3140. const auto & lmlock = lmlocks->at(weight->idx);
  3141. lmlock->grow_to(weight->offs + n_size);
  3142. }
  3143. auto & mmap_used = mmaps_used[weight->idx];
  3144. mmap_used.first = std::min(mmap_used.first, weight->offs);
  3145. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  3146. } else {
  3147. ggml_backend_tensor_set(cur, data, 0, n_size);
  3148. }
  3149. } else {
  3150. GGML_ASSERT(weight->idx < files.size());
  3151. const auto & file = files.at(weight->idx);
  3152. if (ggml_backend_buffer_is_host(cur->buffer)) {
  3153. file->seek(weight->offs, SEEK_SET);
  3154. file->read_raw(cur->data, n_size);
  3155. if (check_tensors) {
  3156. validation_result.emplace_back(std::async(std::launch::async, [cur, n_size] {
  3157. return std::make_pair(cur, ggml_validate_row_data(cur->type, cur->data, n_size));
  3158. }));
  3159. }
  3160. } else {
  3161. read_buf.resize(n_size);
  3162. file->seek(weight->offs, SEEK_SET);
  3163. file->read_raw(read_buf.data(), n_size);
  3164. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3165. if (check_tensors && !ggml_validate_row_data(cur->type, read_buf.data(), n_size)) {
  3166. throw std::runtime_error(format("tensor '%s' has invalid data", ggml_get_name(cur)));
  3167. }
  3168. }
  3169. }
  3170. size_done += n_size;
  3171. }
  3172. // check validation results
  3173. bool validation_failed = false;
  3174. for (auto & future : validation_result) {
  3175. auto result = future.get();
  3176. if (!result.second) {
  3177. LLAMA_LOG_ERROR("%s: tensor '%s' has invalid data\n", __func__, ggml_get_name(result.first));
  3178. validation_failed = true;
  3179. }
  3180. }
  3181. if (validation_failed) {
  3182. throw std::runtime_error("found tensors with invalid data");
  3183. }
  3184. // check if this is the last call and do final cleanup
  3185. if (size_done >= size_data) {
  3186. // unmap offloaded tensors and metadata
  3187. if (use_mmap) {
  3188. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3189. const auto & mmap_used = mmaps_used.at(idx);
  3190. auto & mapping = mappings.at(idx);
  3191. mapping->unmap_fragment(0, mmap_used.first);
  3192. if (mmap_used.second != 0) {
  3193. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3194. }
  3195. }
  3196. }
  3197. if (progress_callback) {
  3198. // Even though the model is done loading, we still honor
  3199. // cancellation since we need to free allocations.
  3200. return progress_callback(1.0f, progress_callback_user_data);
  3201. }
  3202. }
  3203. return true;
  3204. }
  3205. };
  3206. template<>
  3207. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3208. uint32_t tmp;
  3209. const bool found = get_key(kid, tmp, required);
  3210. if (found) {
  3211. result = (enum llama_pooling_type) tmp;
  3212. } else {
  3213. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3214. }
  3215. return found;
  3216. }
  3217. //
  3218. // load LLaMA models
  3219. //
  3220. static const char * llama_model_arch_name(llm_arch arch) {
  3221. auto it = LLM_ARCH_NAMES.find(arch);
  3222. if (it == LLM_ARCH_NAMES.end()) {
  3223. return "unknown";
  3224. }
  3225. return it->second;
  3226. }
  3227. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3228. if (ftype & LLAMA_FTYPE_GUESSED) {
  3229. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3230. }
  3231. switch (ftype) {
  3232. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3233. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3234. case LLAMA_FTYPE_MOSTLY_BF16: return "BF16";
  3235. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3236. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3237. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  3238. return "Q4_1, some F16";
  3239. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3240. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3241. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3242. // K-quants
  3243. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3244. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3245. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3246. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3247. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3248. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3249. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3250. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3251. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3252. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3253. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  3254. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3255. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3256. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3257. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3258. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  3259. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  3260. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  3261. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3262. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3263. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3264. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3265. default: return "unknown, may not work";
  3266. }
  3267. }
  3268. static const char * llama_model_type_name(e_model type) {
  3269. switch (type) {
  3270. case MODEL_22M: return "22M";
  3271. case MODEL_33M: return "33M";
  3272. case MODEL_109M: return "109M";
  3273. case MODEL_137M: return "137M";
  3274. case MODEL_0_5B: return "0.5B";
  3275. case MODEL_1B: return "1B";
  3276. case MODEL_2B: return "2B";
  3277. case MODEL_3B: return "3B";
  3278. case MODEL_7B: return "7B";
  3279. case MODEL_8B: return "8B";
  3280. case MODEL_12B: return "12B";
  3281. case MODEL_13B: return "13B";
  3282. case MODEL_14B: return "14B";
  3283. case MODEL_15B: return "15B";
  3284. case MODEL_20B: return "20B";
  3285. case MODEL_30B: return "30B";
  3286. case MODEL_34B: return "34B";
  3287. case MODEL_35B: return "35B";
  3288. case MODEL_40B: return "40B";
  3289. case MODEL_65B: return "65B";
  3290. case MODEL_70B: return "70B";
  3291. case MODEL_314B: return "314B";
  3292. case MODEL_SMALL: return "0.1B";
  3293. case MODEL_MEDIUM: return "0.4B";
  3294. case MODEL_LARGE: return "0.8B";
  3295. case MODEL_XL: return "1.5B";
  3296. case MODEL_A2_7B: return "A2.7B";
  3297. case MODEL_8x7B: return "8x7B";
  3298. case MODEL_8x22B: return "8x22B";
  3299. case MODEL_16x12B: return "16x12B";
  3300. default: return "?B";
  3301. }
  3302. }
  3303. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3304. switch (type) {
  3305. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3306. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3307. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3308. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3309. default: return "unknown";
  3310. }
  3311. }
  3312. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3313. model.arch = ml.get_arch();
  3314. if (model.arch == LLM_ARCH_UNKNOWN) {
  3315. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3316. }
  3317. }
  3318. static void llm_load_hparams(
  3319. llama_model_loader & ml,
  3320. llama_model & model) {
  3321. auto & hparams = model.hparams;
  3322. const gguf_context * ctx = ml.meta;
  3323. // get metadata as string
  3324. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3325. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3326. if (type == GGUF_TYPE_ARRAY) {
  3327. continue;
  3328. }
  3329. const char * name = gguf_get_key(ctx, i);
  3330. const std::string value = gguf_kv_to_str(ctx, i);
  3331. model.gguf_kv.emplace(name, value);
  3332. }
  3333. // get general kv
  3334. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3335. // get hparams kv
  3336. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3337. // everything past this point is not vocab-related
  3338. if (hparams.vocab_only) {
  3339. return;
  3340. }
  3341. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3342. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3343. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3344. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3345. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3346. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3347. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3348. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3349. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3350. if (hparams.n_expert > 0) {
  3351. GGML_ASSERT(hparams.n_expert_used > 0);
  3352. } else {
  3353. GGML_ASSERT(hparams.n_expert_used == 0);
  3354. }
  3355. // n_head_kv is optional, default to n_head
  3356. hparams.n_head_kv = hparams.n_head;
  3357. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3358. bool rope_finetuned = false;
  3359. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3360. hparams.rope_finetuned = rope_finetuned;
  3361. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3362. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3363. // rope_freq_base (optional)
  3364. hparams.rope_freq_base_train = 10000.0f;
  3365. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3366. std::string rope_scaling("linear");
  3367. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3368. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3369. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3370. // rope_freq_scale (inverse of the kv) is optional
  3371. float ropescale = 0.0f;
  3372. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3373. // try the old key name
  3374. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3375. }
  3376. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3377. // sanity check for n_rot (optional)
  3378. {
  3379. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3380. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3381. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3382. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3383. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3384. }
  3385. }
  3386. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3387. // gpt-j n_rot = rotary_dim
  3388. }
  3389. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3390. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3391. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3392. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3393. // arch-specific KVs
  3394. switch (model.arch) {
  3395. case LLM_ARCH_LLAMA:
  3396. {
  3397. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3398. if (hparams.n_expert == 8) {
  3399. switch (hparams.n_layer) {
  3400. case 32: model.type = e_model::MODEL_8x7B; break;
  3401. case 56: model.type = e_model::MODEL_8x22B; break;
  3402. default: model.type = e_model::MODEL_UNKNOWN;
  3403. }
  3404. } else {
  3405. switch (hparams.n_layer) {
  3406. case 22: model.type = e_model::MODEL_1B; break;
  3407. case 26: model.type = e_model::MODEL_3B; break;
  3408. case 32: model.type = hparams.n_vocab < 40000 ? e_model::MODEL_7B : e_model::MODEL_8B; break;
  3409. case 40: model.type = e_model::MODEL_13B; break;
  3410. case 48: model.type = e_model::MODEL_34B; break;
  3411. case 60: model.type = e_model::MODEL_30B; break;
  3412. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3413. default: model.type = e_model::MODEL_UNKNOWN;
  3414. }
  3415. }
  3416. } break;
  3417. case LLM_ARCH_MINICPM:
  3418. {
  3419. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3420. switch (hparams.n_layer) {
  3421. case 40: model.type = e_model::MODEL_2B; break;
  3422. default: model.type = e_model::MODEL_UNKNOWN;
  3423. }
  3424. } break;
  3425. case LLM_ARCH_GROK:
  3426. {
  3427. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3428. switch (hparams.n_layer) {
  3429. case 64: model.type = e_model::MODEL_314B; break;
  3430. default: model.type = e_model::MODEL_UNKNOWN;
  3431. }
  3432. } break;
  3433. case LLM_ARCH_FALCON:
  3434. {
  3435. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3436. switch (hparams.n_layer) {
  3437. case 32: model.type = e_model::MODEL_7B; break;
  3438. case 60: model.type = e_model::MODEL_40B; break;
  3439. default: model.type = e_model::MODEL_UNKNOWN;
  3440. }
  3441. } break;
  3442. case LLM_ARCH_BAICHUAN:
  3443. {
  3444. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3445. switch (hparams.n_layer) {
  3446. case 32: model.type = e_model::MODEL_7B; break;
  3447. case 40: model.type = e_model::MODEL_13B; break;
  3448. default: model.type = e_model::MODEL_UNKNOWN;
  3449. }
  3450. if (model.type == e_model::MODEL_13B) {
  3451. // TODO: become GGUF KV parameter
  3452. hparams.f_max_alibi_bias = 8.0f;
  3453. }
  3454. } break;
  3455. case LLM_ARCH_STARCODER:
  3456. {
  3457. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3458. switch (hparams.n_layer) {
  3459. case 24: model.type = e_model::MODEL_1B; break;
  3460. case 36: model.type = e_model::MODEL_3B; break;
  3461. case 42: model.type = e_model::MODEL_7B; break;
  3462. case 40: model.type = e_model::MODEL_15B; break;
  3463. default: model.type = e_model::MODEL_UNKNOWN;
  3464. }
  3465. } break;
  3466. case LLM_ARCH_PERSIMMON:
  3467. {
  3468. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3469. switch (hparams.n_layer) {
  3470. case 36: model.type = e_model::MODEL_8B; break;
  3471. default: model.type = e_model::MODEL_UNKNOWN;
  3472. }
  3473. } break;
  3474. case LLM_ARCH_REFACT:
  3475. {
  3476. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3477. switch (hparams.n_layer) {
  3478. case 32: model.type = e_model::MODEL_1B; break;
  3479. default: model.type = e_model::MODEL_UNKNOWN;
  3480. }
  3481. // TODO: become GGUF KV parameter
  3482. hparams.f_max_alibi_bias = 8.0f;
  3483. } break;
  3484. case LLM_ARCH_BERT:
  3485. {
  3486. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3487. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3488. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3489. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3490. switch (hparams.n_layer) {
  3491. case 3:
  3492. model.type = e_model::MODEL_17M; break; // bge-micro
  3493. case 6:
  3494. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3495. case 12:
  3496. switch (hparams.n_embd) {
  3497. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3498. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3499. } break;
  3500. case 24:
  3501. model.type = e_model::MODEL_335M; break; // bge-large
  3502. }
  3503. } break;
  3504. case LLM_ARCH_JINA_BERT_V2:
  3505. {
  3506. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3507. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3508. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3509. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3510. hparams.f_max_alibi_bias = 8.0f;
  3511. switch (hparams.n_layer) {
  3512. case 4: model.type = e_model::MODEL_33M; break; // jina-embeddings-small
  3513. case 12: model.type = e_model::MODEL_137M; break; // jina-embeddings-base
  3514. }
  3515. } break;
  3516. case LLM_ARCH_NOMIC_BERT:
  3517. {
  3518. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3519. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3520. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3521. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3522. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3523. model.type = e_model::MODEL_137M;
  3524. }
  3525. } break;
  3526. case LLM_ARCH_BLOOM:
  3527. {
  3528. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3529. switch (hparams.n_layer) {
  3530. case 24: model.type = e_model::MODEL_1B; break;
  3531. case 30:
  3532. switch (hparams.n_embd) {
  3533. case 2560: model.type = e_model::MODEL_3B; break;
  3534. case 4096: model.type = e_model::MODEL_7B; break;
  3535. } break;
  3536. }
  3537. // TODO: become GGUF KV parameter
  3538. hparams.f_max_alibi_bias = 8.0f;
  3539. } break;
  3540. case LLM_ARCH_MPT:
  3541. {
  3542. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3543. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3544. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3545. switch (hparams.n_layer) {
  3546. case 32: model.type = e_model::MODEL_7B; break;
  3547. case 48: model.type = e_model::MODEL_30B; break;
  3548. default: model.type = e_model::MODEL_UNKNOWN;
  3549. }
  3550. } break;
  3551. case LLM_ARCH_STABLELM:
  3552. {
  3553. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3554. switch (hparams.n_layer) {
  3555. case 24: model.type = e_model::MODEL_1B; break;
  3556. case 32: model.type = e_model::MODEL_3B; break;
  3557. case 40: model.type = e_model::MODEL_12B; break;
  3558. default: model.type = e_model::MODEL_UNKNOWN;
  3559. }
  3560. } break;
  3561. case LLM_ARCH_QWEN:
  3562. {
  3563. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3564. switch (hparams.n_layer) {
  3565. case 32: model.type = e_model::MODEL_7B; break;
  3566. case 40: model.type = e_model::MODEL_13B; break;
  3567. default: model.type = e_model::MODEL_UNKNOWN;
  3568. }
  3569. } break;
  3570. case LLM_ARCH_QWEN2:
  3571. {
  3572. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3573. switch (hparams.n_layer) {
  3574. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3575. case 32: model.type = e_model::MODEL_7B; break;
  3576. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3577. case 80: model.type = e_model::MODEL_70B; break;
  3578. default: model.type = e_model::MODEL_UNKNOWN;
  3579. }
  3580. } break;
  3581. case LLM_ARCH_QWEN2MOE:
  3582. {
  3583. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3584. switch (hparams.n_layer) {
  3585. case 24: model.type = e_model::MODEL_A2_7B; break;
  3586. default: model.type = e_model::MODEL_UNKNOWN;
  3587. }
  3588. } break;
  3589. case LLM_ARCH_PHI2:
  3590. {
  3591. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3592. switch (hparams.n_layer) {
  3593. case 24: model.type = e_model::MODEL_1B; break;
  3594. case 32: model.type = e_model::MODEL_3B; break;
  3595. default: model.type = e_model::MODEL_UNKNOWN;
  3596. }
  3597. } break;
  3598. case LLM_ARCH_PHI3:
  3599. {
  3600. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3601. switch (hparams.n_layer) {
  3602. case 24: model.type = e_model::MODEL_1B; break;
  3603. case 32: model.type = e_model::MODEL_3B; break;
  3604. default: model.type = e_model::MODEL_UNKNOWN;
  3605. }
  3606. } break;
  3607. case LLM_ARCH_PLAMO:
  3608. {
  3609. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3610. switch (hparams.n_layer) {
  3611. case 40: model.type = e_model::MODEL_13B; break;
  3612. default: model.type = e_model::MODEL_UNKNOWN;
  3613. }
  3614. } break;
  3615. case LLM_ARCH_GPT2:
  3616. {
  3617. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3618. switch (hparams.n_layer) {
  3619. case 12: model.type = e_model::MODEL_SMALL; break;
  3620. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3621. case 36: model.type = e_model::MODEL_LARGE; break;
  3622. case 48: model.type = e_model::MODEL_XL; break;
  3623. default: model.type = e_model::MODEL_UNKNOWN;
  3624. }
  3625. } break;
  3626. case LLM_ARCH_CODESHELL:
  3627. {
  3628. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3629. switch (hparams.n_layer) {
  3630. case 42: model.type = e_model::MODEL_SMALL; break;
  3631. default: model.type = e_model::MODEL_UNKNOWN;
  3632. }
  3633. } break;
  3634. case LLM_ARCH_ORION:
  3635. {
  3636. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3637. switch (hparams.n_layer) {
  3638. case 40: model.type = e_model::MODEL_14B; break;
  3639. default: model.type = e_model::MODEL_UNKNOWN;
  3640. }
  3641. } break;
  3642. case LLM_ARCH_INTERNLM2:
  3643. {
  3644. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3645. switch (hparams.n_layer) {
  3646. case 32: model.type = e_model::MODEL_7B; break;
  3647. case 48: model.type = e_model::MODEL_20B; break;
  3648. default: model.type = e_model::MODEL_UNKNOWN;
  3649. }
  3650. } break;
  3651. case LLM_ARCH_GEMMA:
  3652. {
  3653. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3654. switch (hparams.n_layer) {
  3655. case 18: model.type = e_model::MODEL_2B; break;
  3656. case 28: model.type = e_model::MODEL_7B; break;
  3657. default: model.type = e_model::MODEL_UNKNOWN;
  3658. }
  3659. } break;
  3660. case LLM_ARCH_STARCODER2:
  3661. {
  3662. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3663. switch (hparams.n_layer) {
  3664. case 30: model.type = e_model::MODEL_3B; break;
  3665. case 32: model.type = e_model::MODEL_7B; break;
  3666. case 40: model.type = e_model::MODEL_15B; break;
  3667. default: model.type = e_model::MODEL_UNKNOWN;
  3668. }
  3669. } break;
  3670. case LLM_ARCH_MAMBA:
  3671. {
  3672. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3673. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3674. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3675. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3676. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3677. switch (hparams.n_layer) {
  3678. case 24:
  3679. switch (hparams.n_embd) {
  3680. case 768: model.type = e_model::MODEL_SMALL; break;
  3681. default: model.type = e_model::MODEL_UNKNOWN;
  3682. } break;
  3683. case 48:
  3684. switch (hparams.n_embd) {
  3685. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3686. case 1536: model.type = e_model::MODEL_LARGE; break;
  3687. case 2048: model.type = e_model::MODEL_XL; break;
  3688. default: model.type = e_model::MODEL_UNKNOWN;
  3689. } break;
  3690. case 64:
  3691. switch (hparams.n_embd) {
  3692. case 2560: model.type = e_model::MODEL_3B; break;
  3693. default: model.type = e_model::MODEL_UNKNOWN;
  3694. } break;
  3695. default: model.type = e_model::MODEL_UNKNOWN;
  3696. }
  3697. } break;
  3698. case LLM_ARCH_XVERSE:
  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. case 80: model.type = e_model::MODEL_65B; break;
  3705. default: model.type = e_model::MODEL_UNKNOWN;
  3706. }
  3707. } break;
  3708. case LLM_ARCH_COMMAND_R:
  3709. {
  3710. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3711. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3712. switch (hparams.n_layer) {
  3713. case 40: model.type = e_model::MODEL_35B; break;
  3714. default: model.type = e_model::MODEL_UNKNOWN;
  3715. }
  3716. } break;
  3717. case LLM_ARCH_DBRX:
  3718. {
  3719. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3720. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  3721. switch (hparams.n_layer) {
  3722. case 40: model.type = e_model::MODEL_16x12B; break;
  3723. default: model.type = e_model::MODEL_UNKNOWN;
  3724. }
  3725. } break;
  3726. case LLM_ARCH_OLMO:
  3727. {
  3728. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3729. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3730. switch (hparams.n_layer) {
  3731. case 22: model.type = e_model::MODEL_1B; break;
  3732. case 32: model.type = e_model::MODEL_7B; break;
  3733. case 80: model.type = e_model::MODEL_70B; break;
  3734. default: model.type = e_model::MODEL_UNKNOWN;
  3735. }
  3736. } break;
  3737. default: (void)0;
  3738. }
  3739. model.ftype = ml.ftype;
  3740. if (hparams.f_max_alibi_bias > 0.0f) {
  3741. hparams.use_alibi = true;
  3742. }
  3743. hparams.rope_type = llama_rope_type(&model);
  3744. }
  3745. // TODO: This should probably be in llama.h
  3746. static std::vector<llama_vocab::id> llama_tokenize_internal(
  3747. const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special = false
  3748. );
  3749. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3750. static void llm_load_vocab(
  3751. llama_model_loader & ml,
  3752. llama_model & model) {
  3753. auto & vocab = model.vocab;
  3754. struct gguf_context * ctx = ml.meta;
  3755. const auto kv = LLM_KV(model.arch);
  3756. // determine vocab type
  3757. {
  3758. std::string tokenizer_model;
  3759. std::string tokenizer_pre;
  3760. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_model);
  3761. ml.get_key(LLM_KV_TOKENIZER_PRE, tokenizer_pre, false);
  3762. if (tokenizer_model == "no_vocab") {
  3763. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3764. // default special tokens
  3765. vocab.special_bos_id = -1;
  3766. vocab.special_eos_id = -1;
  3767. vocab.special_unk_id = -1;
  3768. vocab.special_sep_id = -1;
  3769. vocab.special_pad_id = -1;
  3770. vocab.special_cls_id = -1;
  3771. vocab.special_mask_id = -1;
  3772. vocab.linefeed_id = -1;
  3773. return;
  3774. } else if (tokenizer_model == "llama") {
  3775. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3776. // default special tokens
  3777. vocab.special_bos_id = 1;
  3778. vocab.special_eos_id = 2;
  3779. vocab.special_unk_id = 0;
  3780. vocab.special_sep_id = -1;
  3781. vocab.special_pad_id = -1;
  3782. vocab.special_cls_id = -1;
  3783. vocab.special_mask_id = -1;
  3784. // For Fill-In-the-Middle (FIM)/infill models which where converted
  3785. // prior to support of FIM special tokens in GGUF, the following
  3786. // will allow those models to continue to work. The general names
  3787. // of the known models are currently CodeLlama (LLM_ARCH_LLAMA) and
  3788. // CodeGemma (LLM_ARCH_GEMMA). This can potentially be removed once
  3789. // new versions of these models have been published.
  3790. std::string gen_name;
  3791. ml.get_key(LLM_KV_GENERAL_NAME, gen_name, false);
  3792. std::transform(gen_name.begin(), gen_name.end(), gen_name.begin(),
  3793. [](unsigned char c){ return std::tolower(c); });
  3794. if (gen_name.find("code") != std::string::npos) {
  3795. if (model.arch == LLM_ARCH_LLAMA) {
  3796. vocab.special_prefix_id = 32007;
  3797. vocab.special_suffix_id = 32008;
  3798. vocab.special_middle_id = 32009;
  3799. vocab.special_eot_id = 32010;
  3800. } else if (model.arch == LLM_ARCH_GEMMA) {
  3801. vocab.special_prefix_id = 67;
  3802. vocab.special_suffix_id = 69;
  3803. vocab.special_middle_id = 68;
  3804. // TODO: this is not EOT, it is "file separator" token, needs fix
  3805. // https://huggingface.co/google/codegemma-7b-it/blob/9b1d9231388358c04d90bd003458f5070d97db44/tokenizer_config.json#L565-L572
  3806. //vocab.special_eot_id = 70;
  3807. vocab.special_eot_id = 107;
  3808. }
  3809. }
  3810. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3811. if (add_space_prefix_keyidx != -1) {
  3812. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3813. } // The default value of add_space_prefix is true.
  3814. } else if (tokenizer_model == "bert") {
  3815. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3816. // default special tokens
  3817. vocab.special_bos_id = -1;
  3818. vocab.special_eos_id = -1;
  3819. vocab.special_unk_id = 100;
  3820. vocab.special_sep_id = 102;
  3821. vocab.special_pad_id = 0;
  3822. vocab.special_cls_id = 101;
  3823. vocab.special_mask_id = 103;
  3824. vocab.add_space_prefix = false;
  3825. } else {
  3826. if (tokenizer_model == "gpt2") {
  3827. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3828. } else {
  3829. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_model.c_str());
  3830. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3831. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3832. return;
  3833. }
  3834. // read bpe merges and populate bpe ranks
  3835. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3836. if (merges_keyidx == -1) {
  3837. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3838. }
  3839. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3840. for (int i = 0; i < n_merges; i++) {
  3841. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3842. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3843. std::string first;
  3844. std::string second;
  3845. const size_t pos = word.find(' ', 1);
  3846. if (pos != std::string::npos) {
  3847. first = word.substr(0, pos);
  3848. second = word.substr(pos + 1);
  3849. }
  3850. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3851. }
  3852. // default special tokens
  3853. vocab.special_bos_id = 11;
  3854. vocab.special_eos_id = 11;
  3855. vocab.special_unk_id = -1;
  3856. vocab.special_sep_id = -1;
  3857. vocab.special_pad_id = -1;
  3858. vocab.special_cls_id = -1;
  3859. vocab.special_mask_id = -1;
  3860. }
  3861. // for now, only BPE models have pre-tokenizers
  3862. if (vocab.type == LLAMA_VOCAB_TYPE_BPE) {
  3863. if (tokenizer_pre.empty()) {
  3864. LLAMA_LOG_WARN("%s: missing pre-tokenizer type, using: 'default'\n", __func__);
  3865. LLAMA_LOG_WARN("%s: \n", __func__);
  3866. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  3867. LLAMA_LOG_WARN("%s: GENERATION QUALITY WILL BE DEGRADED! \n", __func__);
  3868. LLAMA_LOG_WARN("%s: CONSIDER REGENERATING THE MODEL \n", __func__);
  3869. LLAMA_LOG_WARN("%s: ************************************ \n", __func__);
  3870. LLAMA_LOG_WARN("%s: \n", __func__);
  3871. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  3872. } else if (
  3873. tokenizer_pre == "default") {
  3874. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  3875. } else if (
  3876. tokenizer_pre == "llama3" ||
  3877. tokenizer_pre == "llama-v3" ||
  3878. tokenizer_pre == "llama-bpe") {
  3879. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_LLAMA3;
  3880. } else if (
  3881. tokenizer_pre == "deepseek-llm") {
  3882. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM;
  3883. } else if (
  3884. tokenizer_pre == "deepseek-coder") {
  3885. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER;
  3886. } else if (
  3887. tokenizer_pre == "falcon") {
  3888. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_FALCON;
  3889. } else if (
  3890. tokenizer_pre == "mpt") {
  3891. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_MPT;
  3892. } else if (
  3893. tokenizer_pre == "starcoder") {
  3894. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STARCODER;
  3895. } else if (
  3896. tokenizer_pre == "gpt-2" ||
  3897. tokenizer_pre == "jina-es" ||
  3898. tokenizer_pre == "jina-de" ||
  3899. tokenizer_pre == "jina-v2-es" ||
  3900. tokenizer_pre == "jina-v2-de") {
  3901. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_GPT2;
  3902. } else if (
  3903. tokenizer_pre == "refact") {
  3904. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_REFACT;
  3905. } else if (
  3906. tokenizer_pre == "command-r") {
  3907. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_COMMAND_R;
  3908. } else if (
  3909. tokenizer_pre == "qwen2") {
  3910. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_QWEN2;
  3911. } else if (
  3912. tokenizer_pre == "stablelm2") {
  3913. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_STABLELM2;
  3914. } else if (
  3915. tokenizer_pre == "olmo") {
  3916. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_OLMO;
  3917. } else if (
  3918. tokenizer_pre == "dbrx") {
  3919. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DBRX;
  3920. } else {
  3921. throw std::runtime_error(format("unknown pre-tokenizer type: '%s'", tokenizer_pre.c_str()));
  3922. }
  3923. } else {
  3924. vocab.type_pre = LLAMA_VOCAB_PRE_TYPE_DEFAULT;
  3925. }
  3926. }
  3927. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3928. if (token_idx == -1) {
  3929. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3930. }
  3931. const float * scores = nullptr;
  3932. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3933. if (score_idx != -1) {
  3934. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3935. }
  3936. const int * toktypes = nullptr;
  3937. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3938. if (toktype_idx != -1) {
  3939. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3940. }
  3941. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3942. vocab.id_to_token.resize(n_vocab);
  3943. for (uint32_t i = 0; i < n_vocab; i++) {
  3944. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3945. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3946. vocab.token_to_id[word] = i;
  3947. auto & token_data = vocab.id_to_token[i];
  3948. token_data.text = std::move(word);
  3949. token_data.score = scores ? scores[i] : 0.0f;
  3950. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3951. }
  3952. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3953. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3954. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3955. try {
  3956. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3957. } catch (const std::exception & e) {
  3958. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3959. vocab.linefeed_id = vocab.special_pad_id;
  3960. }
  3961. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3962. vocab.linefeed_id = vocab.special_pad_id;
  3963. } else {
  3964. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3965. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3966. vocab.linefeed_id = ids[0];
  3967. }
  3968. // special tokens
  3969. {
  3970. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3971. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3972. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3973. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3974. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3975. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3976. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  3977. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  3978. { LLM_KV_TOKENIZER_PREFIX_ID, vocab.special_prefix_id },
  3979. { LLM_KV_TOKENIZER_SUFFIX_ID, vocab.special_suffix_id },
  3980. { LLM_KV_TOKENIZER_MIDDLE_ID, vocab.special_middle_id },
  3981. { LLM_KV_TOKENIZER_EOT_ID, vocab.special_eot_id },
  3982. };
  3983. for (const auto & it : special_token_types) {
  3984. const std::string & key = kv(std::get<0>(it));
  3985. int32_t & id = std::get<1>(it);
  3986. uint32_t new_id;
  3987. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3988. continue;
  3989. }
  3990. if (new_id >= vocab.id_to_token.size()) {
  3991. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3992. __func__, key.c_str(), new_id, id);
  3993. } else {
  3994. id = new_id;
  3995. }
  3996. }
  3997. // Handle add_bos_token and add_eos_token
  3998. {
  3999. bool temp = true;
  4000. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  4001. vocab.special_add_bos = int(temp);
  4002. }
  4003. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  4004. vocab.special_add_eos = int(temp);
  4005. }
  4006. }
  4007. // find EOT token: "<|eot_id|>", "<|im_end|>", "<end_of_turn>", etc.
  4008. //
  4009. // TODO: convert scripts should provide this token through the KV metadata LLAMA_KV_TOKENIZER_EOT_ID
  4010. // for now, we apply this workaround to find the EOT token based on its text
  4011. if (vocab.special_eot_id == -1) {
  4012. for (const auto & t : vocab.token_to_id) {
  4013. if (
  4014. // TODO: gemma "<end_of_turn>" is exported as a normal token, so the following check does not work
  4015. // need to fix convert script
  4016. //vocab.id_to_token[t.second].type == LLAMA_TOKEN_TYPE_CONTROL &&
  4017. (t.first == "<|eot_id|>" ||
  4018. t.first == "<|im_end|>" ||
  4019. t.first == "<|end|>" ||
  4020. t.first == "<end_of_turn>"
  4021. )
  4022. ) {
  4023. vocab.special_eot_id = t.second;
  4024. break;
  4025. }
  4026. }
  4027. }
  4028. }
  4029. // build special tokens cache
  4030. {
  4031. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  4032. // and will always be correctly labeled in 'added_tokens.json' etc.
  4033. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  4034. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  4035. // are special tokens.
  4036. // From testing, this appears to correlate 1:1 with special tokens.
  4037. //
  4038. // Counting special tokens and verifying in only one direction
  4039. // is sufficient to detect difference in those two sets.
  4040. //
  4041. uint32_t special_tokens_count_by_type = 0;
  4042. uint32_t special_tokens_count_from_verification = 0;
  4043. bool special_tokens_definition_mismatch = false;
  4044. for (const auto & t : vocab.token_to_id) {
  4045. const auto & token = t.first;
  4046. const auto & id = t.second;
  4047. // Count all non-normal tokens in the vocab while iterating
  4048. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  4049. special_tokens_count_by_type++;
  4050. }
  4051. // Skip single character tokens
  4052. if (token.length() > 1) {
  4053. bool is_tokenizable = false;
  4054. // Split token string representation in two, in all possible ways
  4055. // and check if both halves can be matched to a valid token
  4056. for (unsigned i = 1; i < token.length();) {
  4057. const auto left = token.substr(0, i);
  4058. const auto right = token.substr(i);
  4059. // check if we didnt partition in the middle of a utf sequence
  4060. auto utf = utf8_len(left.at(left.length() - 1));
  4061. if (utf == 1) {
  4062. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  4063. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  4064. is_tokenizable = true;
  4065. break;
  4066. }
  4067. i++;
  4068. } else {
  4069. // skip over the rest of multibyte utf sequence
  4070. i += utf - 1;
  4071. }
  4072. }
  4073. if (!is_tokenizable) {
  4074. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  4075. // it's faster to re-filter them here, since there are way less candidates now
  4076. // Calculate a total "utf" length of a token string representation
  4077. size_t utf8_str_len = 0;
  4078. for (unsigned i = 0; i < token.length();) {
  4079. utf8_str_len++;
  4080. i += utf8_len(token.at(i));
  4081. }
  4082. // And skip the ones which are one character
  4083. if (utf8_str_len > 1) {
  4084. // At this point what we have left are special tokens only
  4085. vocab.special_tokens_cache[token] = id;
  4086. // Count manually found special tokens
  4087. special_tokens_count_from_verification++;
  4088. // If this manually found special token is not marked as such, flag a mismatch
  4089. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  4090. special_tokens_definition_mismatch = true;
  4091. }
  4092. }
  4093. }
  4094. }
  4095. }
  4096. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  4097. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  4098. __func__,
  4099. special_tokens_count_from_verification, vocab.id_to_token.size(),
  4100. special_tokens_count_by_type, vocab.id_to_token.size()
  4101. );
  4102. } else {
  4103. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  4104. __func__,
  4105. special_tokens_count_from_verification, vocab.id_to_token.size()
  4106. );
  4107. }
  4108. }
  4109. }
  4110. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  4111. const auto & hparams = model.hparams;
  4112. const auto & vocab = model.vocab;
  4113. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  4114. // hparams
  4115. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  4116. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  4117. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  4118. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  4119. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  4120. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  4121. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  4122. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  4123. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  4124. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  4125. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  4126. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  4127. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  4128. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  4129. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  4130. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  4131. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  4132. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  4133. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  4134. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  4135. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  4136. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  4137. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  4138. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  4139. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  4140. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  4141. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  4142. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  4143. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  4144. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  4145. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  4146. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  4147. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  4148. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  4149. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  4150. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  4151. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  4152. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  4153. if (ml.n_elements >= 1e12) {
  4154. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  4155. } else if (ml.n_elements >= 1e9) {
  4156. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  4157. } else if (ml.n_elements >= 1e6) {
  4158. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  4159. } else {
  4160. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  4161. }
  4162. if (ml.n_bytes < GiB) {
  4163. 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);
  4164. } else {
  4165. 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);
  4166. }
  4167. // general kv
  4168. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  4169. // special tokens
  4170. 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() ); }
  4171. 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() ); }
  4172. 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() ); }
  4173. 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() ); }
  4174. 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() ); }
  4175. 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() ); }
  4176. 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() ); }
  4177. 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() ); }
  4178. 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() ); }
  4179. 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() ); }
  4180. 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() ); }
  4181. 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() ); }
  4182. }
  4183. // Returns false if cancelled by progress_callback
  4184. static bool llm_load_tensors(
  4185. llama_model_loader & ml,
  4186. llama_model & model,
  4187. int n_gpu_layers,
  4188. enum llama_split_mode split_mode,
  4189. int main_gpu,
  4190. const float * tensor_split,
  4191. bool use_mlock,
  4192. llama_progress_callback progress_callback,
  4193. void * progress_callback_user_data) {
  4194. model.t_start_us = ggml_time_us();
  4195. auto & hparams = model.hparams;
  4196. #ifdef GGML_USE_SYCL
  4197. // disable MoE with SYCL until mul_mat_id is updated
  4198. if (hparams.n_expert > 0) {
  4199. n_gpu_layers = 0;
  4200. }
  4201. #endif
  4202. model.split_mode = split_mode;
  4203. model.main_gpu = main_gpu;
  4204. model.n_gpu_layers = n_gpu_layers;
  4205. const int64_t n_layer = hparams.n_layer;
  4206. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  4207. bool use_mmap_buffer = true;
  4208. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  4209. model.buft_input = llama_default_buffer_type_cpu(true);
  4210. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  4211. model.buft_layer.resize(n_layer);
  4212. // assign cpu layers
  4213. for (int64_t i = 0; i < i_gpu_start; ++i) {
  4214. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  4215. }
  4216. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  4217. // calculate the split points
  4218. int device_count = llama_get_device_count(model);
  4219. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  4220. std::vector<float> splits(device_count);
  4221. if (all_zero) {
  4222. // default split, by free memory
  4223. for (int i = 0; i < device_count; ++i) {
  4224. splits[i] = llama_get_device_memory(model, i);
  4225. }
  4226. } else {
  4227. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  4228. }
  4229. // sum and normalize the splits to get the split points
  4230. float split_sum = 0.0f;
  4231. for (int i = 0; i < device_count; ++i) {
  4232. split_sum += splits[i];
  4233. splits[i] = split_sum;
  4234. }
  4235. for (int i = 0; i < device_count; ++i) {
  4236. splits[i] /= split_sum;
  4237. }
  4238. // assign the repeating layers to the devices according to the splits
  4239. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  4240. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  4241. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  4242. model.buft_layer[i] = llama_default_buffer_type_offload(model, layer_gpu);
  4243. }
  4244. // assign the output layer
  4245. if (n_gpu_layers > n_layer) {
  4246. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  4247. model.buft_output = llama_default_buffer_type_offload(model, layer_gpu);
  4248. } else {
  4249. model.buft_output = llama_default_buffer_type_cpu(true);
  4250. }
  4251. } else {
  4252. ggml_backend_buffer_type_t split_buft;
  4253. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  4254. split_buft = llama_default_buffer_type_split(model, main_gpu, tensor_split);
  4255. } else {
  4256. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  4257. split_buft = llama_default_buffer_type_offload(model, main_gpu);
  4258. }
  4259. // assign the repeating layers
  4260. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  4261. model.buft_layer[i] = {
  4262. split_buft,
  4263. llama_default_buffer_type_offload(model, main_gpu)
  4264. };
  4265. }
  4266. // assign the output layer
  4267. if (n_gpu_layers > n_layer) {
  4268. model.buft_output = {
  4269. split_buft,
  4270. llama_default_buffer_type_offload(model, main_gpu)
  4271. };
  4272. } else {
  4273. model.buft_output = llama_default_buffer_type_cpu(true);
  4274. }
  4275. }
  4276. // count used buffer types
  4277. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  4278. buft_layer_count[model.buft_input.buft]++;
  4279. buft_layer_count[model.buft_input.buft_matrix]++;
  4280. buft_layer_count[model.buft_output.buft]++;
  4281. buft_layer_count[model.buft_output.buft_matrix]++;
  4282. for (int64_t i = 0; i < n_layer; ++i) {
  4283. buft_layer_count[model.buft_layer[i].buft]++;
  4284. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  4285. }
  4286. // create one context per buffer type
  4287. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  4288. // for moe merged tensors
  4289. ctx_size += ggml_tensor_overhead()*n_layer*3;
  4290. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  4291. for (auto & it : buft_layer_count) {
  4292. struct ggml_init_params params = {
  4293. /*.mem_size =*/ ctx_size,
  4294. /*.mem_buffer =*/ NULL,
  4295. /*.no_alloc =*/ true,
  4296. };
  4297. ggml_context * ctx = ggml_init(params);
  4298. if (!ctx) {
  4299. throw std::runtime_error(format("failed to create context"));
  4300. }
  4301. ctx_map[it.first] = ctx;
  4302. model.ctxs.push_back(ctx);
  4303. }
  4304. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  4305. // create tensors for the weights
  4306. {
  4307. const int64_t n_embd = hparams.n_embd;
  4308. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4309. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4310. const int64_t n_embd_gqa = n_embd_v_gqa;
  4311. const int64_t n_vocab = hparams.n_vocab;
  4312. const int64_t n_vocab_type = hparams.n_vocab_type;
  4313. const int64_t n_ff = hparams.n_ff;
  4314. const int64_t n_expert = hparams.n_expert;
  4315. if (n_expert > 0 && hparams.n_expert_used == 0) {
  4316. throw std::runtime_error("model has expert layers but no expert layers are used");
  4317. }
  4318. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  4319. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  4320. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  4321. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  4322. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  4323. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  4324. model.layers.resize(n_layer);
  4325. const auto tn = LLM_TN(model.arch);
  4326. switch (model.arch) {
  4327. case LLM_ARCH_LLAMA:
  4328. case LLM_ARCH_REFACT:
  4329. case LLM_ARCH_MINICPM:
  4330. {
  4331. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4332. // output
  4333. {
  4334. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4335. if (model.arch != LLM_ARCH_MINICPM){
  4336. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4337. // if output is NULL, init from the input tok embed
  4338. if (model.output == NULL) {
  4339. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4340. ml.n_created--; // artificial tensor
  4341. ml.size_data += ggml_nbytes(model.output);
  4342. }
  4343. }
  4344. }
  4345. for (int i = 0; i < n_layer; ++i) {
  4346. ggml_context * ctx_layer = ctx_for_layer(i);
  4347. ggml_context * ctx_split = ctx_for_layer_split(i);
  4348. auto & layer = model.layers[i];
  4349. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4350. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4351. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4352. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4353. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4354. // optional bias tensors
  4355. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4356. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4357. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4358. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4359. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4360. if (n_expert == 0) {
  4361. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4362. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4363. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4364. } else {
  4365. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4366. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4367. if (layer.ffn_gate_exps) {
  4368. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4369. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4370. } else {
  4371. // merge split expert into a single tensor for compatibility with older models
  4372. // requires disabling mmap
  4373. use_mmap_buffer = false;
  4374. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4375. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4376. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4377. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4378. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4379. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4380. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4381. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4382. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4383. for (uint32_t x = 0; x < n_expert; ++x) {
  4384. // the individual experts are loaded into a view of the merged tensor
  4385. 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);
  4386. 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);
  4387. 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);
  4388. }
  4389. }
  4390. }
  4391. }
  4392. } break;
  4393. case LLM_ARCH_GROK:
  4394. {
  4395. if (n_expert == 0) {
  4396. throw std::runtime_error("Grok model cannot have zero experts");
  4397. }
  4398. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4399. // output
  4400. {
  4401. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4402. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4403. // if output is NULL, init from the input tok embed
  4404. if (model.output == NULL) {
  4405. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4406. ml.n_created--; // artificial tensor
  4407. ml.size_data += ggml_nbytes(model.output);
  4408. }
  4409. }
  4410. for (int i = 0; i < n_layer; ++i) {
  4411. ggml_context * ctx_layer = ctx_for_layer(i);
  4412. ggml_context * ctx_split = ctx_for_layer_split(i);
  4413. auto & layer = model.layers[i];
  4414. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4415. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4416. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4417. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4418. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4419. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4420. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4421. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4422. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4423. if (layer.ffn_gate_exps) {
  4424. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4425. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4426. } else {
  4427. // merge split expert into a single tensor for compatibility with older models
  4428. // requires disabling mmap
  4429. use_mmap_buffer = false;
  4430. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4431. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4432. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4433. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4434. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4435. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4436. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4437. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4438. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4439. for (uint32_t x = 0; x < n_expert; ++x) {
  4440. // the individual experts are loaded into a view of the merged tensor
  4441. 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);
  4442. 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);
  4443. 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);
  4444. }
  4445. }
  4446. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4447. }
  4448. } break;
  4449. case LLM_ARCH_DBRX:
  4450. {
  4451. if (n_expert == 0) {
  4452. throw std::runtime_error("DBRX model cannot have zero experts");
  4453. }
  4454. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4455. // output
  4456. {
  4457. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4458. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4459. }
  4460. for (int i = 0; i < n_layer; ++i) {
  4461. ggml_context * ctx_layer = ctx_for_layer(i);
  4462. ggml_context * ctx_split = ctx_for_layer_split(i);
  4463. auto & layer = model.layers[i];
  4464. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4465. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4466. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4467. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4468. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4469. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4470. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  4471. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4472. }
  4473. } break;
  4474. case LLM_ARCH_BAICHUAN:
  4475. {
  4476. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4477. {
  4478. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4479. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4480. }
  4481. for (int i = 0; i < n_layer; ++i) {
  4482. ggml_context * ctx_layer = ctx_for_layer(i);
  4483. ggml_context * ctx_split = ctx_for_layer_split(i);
  4484. auto & layer = model.layers[i];
  4485. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4486. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4487. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4488. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4489. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4490. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4491. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4492. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4493. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4494. }
  4495. } break;
  4496. case LLM_ARCH_FALCON:
  4497. {
  4498. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4499. // output
  4500. {
  4501. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4502. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4503. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4504. if (!model.output) {
  4505. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4506. ml.n_created--; // artificial tensor
  4507. ml.size_data += ggml_nbytes(model.output);
  4508. }
  4509. }
  4510. for (int i = 0; i < n_layer; ++i) {
  4511. ggml_context * ctx_layer = ctx_for_layer(i);
  4512. ggml_context * ctx_split = ctx_for_layer_split(i);
  4513. auto & layer = model.layers[i];
  4514. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4515. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4516. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  4517. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  4518. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4519. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4520. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4521. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4522. }
  4523. } break;
  4524. case LLM_ARCH_STARCODER:
  4525. {
  4526. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4527. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4528. // output
  4529. {
  4530. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4531. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4532. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4533. if (!model.output) {
  4534. // needs to be on GPU
  4535. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4536. ml.n_created--; // artificial tensor
  4537. ml.size_data += ggml_nbytes(model.output);
  4538. }
  4539. }
  4540. for (int i = 0; i < n_layer; ++i) {
  4541. ggml_context * ctx_layer = ctx_for_layer(i);
  4542. ggml_context * ctx_split = ctx_for_layer_split(i);
  4543. auto & layer = model.layers[i];
  4544. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4545. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4546. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4547. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4548. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4549. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4550. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4551. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4552. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4553. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4554. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4555. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4556. }
  4557. } break;
  4558. case LLM_ARCH_PERSIMMON:
  4559. {
  4560. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4561. {
  4562. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4563. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4564. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4565. }
  4566. for (int i = 0; i < n_layer; ++i) {
  4567. ggml_context * ctx_layer = ctx_for_layer(i);
  4568. ggml_context * ctx_split = ctx_for_layer_split(i);
  4569. auto & layer = model.layers[i];
  4570. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4571. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4572. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4573. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4574. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4575. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4576. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4577. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4578. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4579. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4580. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4581. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4582. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4583. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4584. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4585. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4586. }
  4587. } break;
  4588. case LLM_ARCH_BERT:
  4589. case LLM_ARCH_NOMIC_BERT:
  4590. {
  4591. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4592. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4593. if (model.arch == LLM_ARCH_BERT) {
  4594. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4595. }
  4596. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4597. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4598. for (int i = 0; i < n_layer; ++i) {
  4599. ggml_context * ctx_layer = ctx_for_layer(i);
  4600. ggml_context * ctx_split = ctx_for_layer_split(i);
  4601. auto & layer = model.layers[i];
  4602. if (model.arch == LLM_ARCH_BERT) {
  4603. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4604. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4605. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4606. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4607. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4608. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4609. } else {
  4610. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4611. }
  4612. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4613. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4614. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4615. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4616. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4617. if (model.arch == LLM_ARCH_BERT) {
  4618. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4619. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4620. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4621. } else {
  4622. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4623. }
  4624. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4625. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4626. }
  4627. } break;
  4628. case LLM_ARCH_JINA_BERT_V2:
  4629. {
  4630. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // word_embeddings
  4631. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type}); //token_type_embeddings
  4632. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd}); // LayerNorm
  4633. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd}); //LayerNorm bias
  4634. for (int i = 0; i < n_layer; ++i) {
  4635. ggml_context * ctx_layer = ctx_for_layer(i);
  4636. ggml_context * ctx_split = ctx_for_layer_split(i);
  4637. auto & layer = model.layers[i]; // JinaBertLayer
  4638. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4639. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4640. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, false);
  4641. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, false);
  4642. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4643. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4644. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, false);
  4645. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, false);
  4646. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4647. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4648. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}); //output_dens
  4649. layer.bo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}); //output_dens
  4650. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd}); //output_norm
  4651. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4652. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4653. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4654. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4655. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4656. layer.layer_out_norm = ml.create_tensor(ctx_split, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4657. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4658. }
  4659. } break;
  4660. case LLM_ARCH_BLOOM:
  4661. {
  4662. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4663. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4664. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4665. // output
  4666. {
  4667. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4668. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4669. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4670. }
  4671. for (int i = 0; i < n_layer; ++i) {
  4672. ggml_context * ctx_layer = ctx_for_layer(i);
  4673. ggml_context * ctx_split = ctx_for_layer_split(i);
  4674. auto & layer = model.layers[i];
  4675. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4676. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4677. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4678. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4679. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4680. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4681. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4682. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4683. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4684. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4685. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4686. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4687. }
  4688. } break;
  4689. case LLM_ARCH_MPT:
  4690. {
  4691. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4692. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, false);
  4693. // output
  4694. {
  4695. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4696. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4697. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4698. if (!model.output) {
  4699. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4700. ml.n_created--; // artificial tensor
  4701. ml.size_data += ggml_nbytes(model.output);
  4702. }
  4703. }
  4704. for (int i = 0; i < n_layer; ++i) {
  4705. ggml_context * ctx_layer = ctx_for_layer(i);
  4706. ggml_context * ctx_split = ctx_for_layer_split(i);
  4707. auto & layer = model.layers[i];
  4708. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4709. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4710. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4711. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4712. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4713. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4714. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4715. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4716. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4717. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4718. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4719. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4720. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, false);
  4721. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, false);
  4722. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, false);
  4723. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, false);
  4724. // AWQ ScaleActivation layer
  4725. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4726. }
  4727. } break;
  4728. case LLM_ARCH_STABLELM:
  4729. {
  4730. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4731. // output
  4732. {
  4733. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4734. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4735. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4736. }
  4737. for (int i = 0; i < n_layer; ++i) {
  4738. ggml_context * ctx_layer = ctx_for_layer(i);
  4739. ggml_context * ctx_split = ctx_for_layer_split(i);
  4740. auto & layer = model.layers[i];
  4741. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4742. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4743. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4744. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4745. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4746. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4747. // optional bias tensors, present in Stable LM 2 1.6B
  4748. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4749. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4750. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4751. // optional q and k layernorms, present in StableLM 2 12B
  4752. 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}, false);
  4753. 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}, false);
  4754. // optional FFN norm, not present in StableLM 2 12B which uses parallel residual
  4755. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, false);
  4756. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4757. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4758. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4759. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4760. }
  4761. } break;
  4762. case LLM_ARCH_QWEN:
  4763. {
  4764. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4765. // output
  4766. {
  4767. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4768. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4769. }
  4770. for (int i = 0; i < n_layer; ++i) {
  4771. ggml_context * ctx_layer = ctx_for_layer(i);
  4772. ggml_context * ctx_split = ctx_for_layer_split(i);
  4773. auto & layer = model.layers[i];
  4774. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4775. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4776. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4777. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4778. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4779. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4780. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4781. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4782. }
  4783. } break;
  4784. case LLM_ARCH_QWEN2:
  4785. {
  4786. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4787. // output
  4788. {
  4789. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4790. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4791. // if output is NULL, init from the input tok embed
  4792. if (model.output == NULL) {
  4793. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4794. ml.n_created--; // artificial tensor
  4795. ml.size_data += ggml_nbytes(model.output);
  4796. }
  4797. }
  4798. for (int i = 0; i < n_layer; ++i) {
  4799. ggml_context * ctx_layer = ctx_for_layer(i);
  4800. ggml_context * ctx_split = ctx_for_layer_split(i);
  4801. auto & layer = model.layers[i];
  4802. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4803. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4804. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4805. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4806. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4807. // optional bias tensors
  4808. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4809. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4810. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4811. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4812. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4813. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4814. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4815. }
  4816. } break;
  4817. case LLM_ARCH_QWEN2MOE:
  4818. {
  4819. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4820. // output
  4821. {
  4822. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4823. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4824. }
  4825. for (int i = 0; i < n_layer; ++i) {
  4826. ggml_context * ctx_layer = ctx_for_layer(i);
  4827. ggml_context * ctx_split = ctx_for_layer_split(i);
  4828. auto & layer = model.layers[i];
  4829. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4830. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4831. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4832. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4833. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4834. // optional bias tensors
  4835. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4836. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4837. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4838. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4839. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4840. GGML_ASSERT(hparams.n_expert > 0);
  4841. GGML_ASSERT(hparams.n_expert_used > 0);
  4842. // MoE branch
  4843. auto n_ff_exp = n_ff / hparams.n_expert_used;
  4844. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  4845. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert});
  4846. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), { n_embd, n_ff_exp, n_expert});
  4847. // Shared expert branch
  4848. layer.ffn_gate_inp_shexp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP_SHEXP, "weight", i), {n_embd});
  4849. layer.ffn_gate_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff});
  4850. layer.ffn_down_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), { n_ff, n_embd});
  4851. layer.ffn_up_shexp = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff});
  4852. }
  4853. } break;
  4854. case LLM_ARCH_PHI2:
  4855. {
  4856. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4857. // output
  4858. {
  4859. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4860. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4861. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4862. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4863. }
  4864. for (int i = 0; i < n_layer; ++i) {
  4865. ggml_context * ctx_layer = ctx_for_layer(i);
  4866. ggml_context * ctx_split = ctx_for_layer_split(i);
  4867. auto & layer = model.layers[i];
  4868. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4869. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4870. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4871. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4872. if (layer.wqkv == nullptr) {
  4873. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4874. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4875. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4876. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4877. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4878. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4879. }
  4880. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4881. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4882. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4883. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4884. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4885. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4886. }
  4887. } break;
  4888. case LLM_ARCH_PHI3:
  4889. {
  4890. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab });
  4891. // output
  4892. {
  4893. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd });
  4894. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab });
  4895. }
  4896. for (int i = 0; i < n_layer; ++i) {
  4897. ggml_context* ctx_layer = ctx_for_layer(i);
  4898. ggml_context* ctx_split = ctx_for_layer_split(i);
  4899. auto& layer = model.layers[i];
  4900. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), { n_embd });
  4901. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), { n_embd, n_embd + 2 * n_embd_gqa }, false);
  4902. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), { n_embd, n_embd });
  4903. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), { n_embd });
  4904. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd });
  4905. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), { n_embd, 2 * n_ff });
  4906. }
  4907. } break;
  4908. case LLM_ARCH_PLAMO:
  4909. {
  4910. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4911. // output
  4912. {
  4913. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4914. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4915. }
  4916. for (int i = 0; i < n_layer; ++i) {
  4917. ggml_context * ctx_layer = ctx_for_layer(i);
  4918. ggml_context * ctx_split = ctx_for_layer_split(i);
  4919. auto & layer = model.layers[i];
  4920. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4921. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4922. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4923. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4924. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4925. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4926. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4927. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4928. }
  4929. } break;
  4930. case LLM_ARCH_GPT2:
  4931. {
  4932. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4933. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4934. // output
  4935. {
  4936. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4937. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4938. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4939. }
  4940. for (int i = 0; i < n_layer; ++i) {
  4941. ggml_context * ctx_layer = ctx_for_layer(i);
  4942. ggml_context * ctx_split = ctx_for_layer_split(i);
  4943. auto & layer = model.layers[i];
  4944. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4945. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4946. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4947. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4948. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4949. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4950. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4951. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4952. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4953. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4954. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4955. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4956. }
  4957. } break;
  4958. case LLM_ARCH_CODESHELL:
  4959. {
  4960. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4961. // output
  4962. {
  4963. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4964. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4965. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4966. }
  4967. for (int i = 0; i < n_layer; ++i) {
  4968. ggml_context * ctx_layer = ctx_for_layer(i);
  4969. ggml_context * ctx_split = ctx_for_layer_split(i);
  4970. auto & layer = model.layers[i];
  4971. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4972. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4973. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4974. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4975. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4976. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4977. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4978. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4979. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4980. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4981. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4982. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4983. }
  4984. } break;
  4985. case LLM_ARCH_ORION:
  4986. {
  4987. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4988. {
  4989. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4990. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4991. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4992. }
  4993. for (int i = 0; i < n_layer; ++i) {
  4994. ggml_context * ctx_layer = ctx_for_layer(i);
  4995. ggml_context * ctx_split = ctx_for_layer_split(i);
  4996. auto & layer = model.layers[i];
  4997. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4998. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4999. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5000. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5001. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5002. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5003. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5004. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5005. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5006. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5007. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5008. }
  5009. } break;
  5010. case LLM_ARCH_INTERNLM2:
  5011. {
  5012. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5013. // output
  5014. {
  5015. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5016. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5017. }
  5018. for (int i = 0; i < n_layer; ++i) {
  5019. ggml_context * ctx_layer = ctx_for_layer(i);
  5020. ggml_context * ctx_split = ctx_for_layer_split(i);
  5021. auto & layer = model.layers[i];
  5022. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5023. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  5024. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5025. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5026. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5027. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5028. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5029. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5030. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5031. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5032. }
  5033. } break;
  5034. case LLM_ARCH_GEMMA:
  5035. {
  5036. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5037. // output
  5038. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5039. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  5040. ml.n_created--; // artificial tensor
  5041. ml.size_data += ggml_nbytes(model.output);
  5042. const int64_t n_ff = hparams.n_ff;
  5043. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5044. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5045. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5046. for (uint32_t i = 0; i < n_layer; ++i) {
  5047. ggml_context * ctx_layer = ctx_for_layer(i);
  5048. ggml_context * ctx_split = ctx_for_layer_split(i);
  5049. auto & layer = model.layers[i];
  5050. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5051. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  5052. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  5053. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  5054. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  5055. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5056. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5057. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5058. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5059. }
  5060. } break;
  5061. case LLM_ARCH_STARCODER2:
  5062. {
  5063. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5064. // output
  5065. {
  5066. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5067. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  5068. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  5069. // if output is NULL, init from the input tok embed
  5070. if (model.output == NULL) {
  5071. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5072. ml.n_created--; // artificial tensor
  5073. ml.size_data += ggml_nbytes(model.output);
  5074. }
  5075. }
  5076. for (int i = 0; i < n_layer; ++i) {
  5077. ggml_context * ctx_layer = ctx_for_layer(i);
  5078. ggml_context * ctx_split = ctx_for_layer_split(i);
  5079. auto & layer = model.layers[i];
  5080. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5081. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  5082. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5083. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5084. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5085. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5086. // optional bias tensors
  5087. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  5088. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  5089. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  5090. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  5091. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5092. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  5093. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5094. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5095. // optional bias tensors
  5096. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  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_MAMBA:
  5101. {
  5102. const int64_t d_conv = hparams.ssm_d_conv;
  5103. const int64_t d_inner = hparams.ssm_d_inner;
  5104. const int64_t d_state = hparams.ssm_d_state;
  5105. const int64_t dt_rank = hparams.ssm_dt_rank;
  5106. // only an expansion factor of 2 is supported for now
  5107. GGML_ASSERT(2 * n_embd == d_inner);
  5108. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5109. // output
  5110. {
  5111. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5112. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  5113. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  5114. if (model.output == NULL) {
  5115. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5116. ml.n_created--; // artificial tensor
  5117. ml.size_data += ggml_nbytes(model.output);
  5118. }
  5119. }
  5120. for (int i = 0; i < n_layer; ++i) {
  5121. ggml_context * ctx_layer = ctx_for_layer(i);
  5122. ggml_context * ctx_split = ctx_for_layer_split(i);
  5123. auto & layer = model.layers[i];
  5124. // norm
  5125. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5126. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  5127. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  5128. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  5129. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  5130. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  5131. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  5132. // no "weight" suffix for these
  5133. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  5134. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  5135. // out_proj
  5136. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  5137. }
  5138. } break;
  5139. case LLM_ARCH_XVERSE:
  5140. {
  5141. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5142. {
  5143. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5144. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  5145. }
  5146. for (int i = 0; i < n_layer; ++i) {
  5147. ggml_context * ctx_layer = ctx_for_layer(i);
  5148. ggml_context * ctx_split = ctx_for_layer_split(i);
  5149. auto & layer = model.layers[i];
  5150. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5151. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5152. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5153. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5154. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5155. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  5156. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5157. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5158. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5159. }
  5160. } break;
  5161. case LLM_ARCH_COMMAND_R:
  5162. {
  5163. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5164. // output
  5165. {
  5166. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  5167. // init output from the input tok embed
  5168. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5169. ml.n_created--; // artificial tensor
  5170. ml.size_data += ggml_nbytes(model.output);
  5171. }
  5172. for (int i = 0; i < n_layer; ++i) {
  5173. ggml_context * ctx_layer = ctx_for_layer(i);
  5174. ggml_context * ctx_split = ctx_for_layer_split(i);
  5175. auto & layer = model.layers[i];
  5176. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  5177. if (n_layer >= 64){
  5178. 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});
  5179. 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});
  5180. }
  5181. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5182. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5183. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5184. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5185. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5186. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5187. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5188. }
  5189. } break;
  5190. case LLM_ARCH_OLMO: // adapted from LLM_ARCH_LLAMA with norm params removed
  5191. {
  5192. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5193. // output
  5194. {
  5195. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  5196. // if output is NULL, init from the input tok embed
  5197. if (model.output == NULL) {
  5198. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  5199. ml.n_created--; // artificial tensor
  5200. ml.size_data += ggml_nbytes(model.output);
  5201. }
  5202. }
  5203. for (int i = 0; i < n_layer; ++i) {
  5204. ggml_context * ctx_split = ctx_for_layer_split(i);
  5205. auto & layer = model.layers[i];
  5206. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  5207. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  5208. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  5209. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  5210. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  5211. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  5212. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  5213. }
  5214. } break;
  5215. default:
  5216. throw std::runtime_error("unknown architecture");
  5217. }
  5218. }
  5219. ml.done_getting_tensors();
  5220. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  5221. model.mappings.reserve(ml.mappings.size());
  5222. // create the backend buffers
  5223. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  5224. ctx_bufs.reserve(ctx_map.size());
  5225. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  5226. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  5227. model.bufs.reserve(n_max_backend_buffer);
  5228. for (auto & it : ctx_map) {
  5229. ggml_backend_buffer_type_t buft = it.first;
  5230. ggml_context * ctx = it.second;
  5231. llama_buf_map bufs;
  5232. bufs.reserve(n_max_backend_buffer);
  5233. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  5234. // 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
  5235. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  5236. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  5237. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5238. void * addr = nullptr;
  5239. size_t first, last;
  5240. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  5241. if (first >= last) {
  5242. continue;
  5243. }
  5244. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  5245. if (buf == nullptr) {
  5246. throw std::runtime_error("unable to allocate backend CPU buffer");
  5247. }
  5248. model.bufs.push_back(buf);
  5249. bufs.emplace(idx, buf);
  5250. #ifdef GGML_USE_CUDA
  5251. if (n_layer >= n_gpu_layers) {
  5252. ggml_backend_cuda_register_host_buffer(
  5253. ggml_backend_buffer_get_base(buf),
  5254. ggml_backend_buffer_get_size(buf));
  5255. }
  5256. #endif
  5257. }
  5258. }
  5259. #ifdef GGML_USE_METAL
  5260. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  5261. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5262. const size_t max_size = ggml_get_max_tensor_size(ctx);
  5263. void * addr = nullptr;
  5264. size_t first, last;
  5265. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  5266. if (first >= last) {
  5267. continue;
  5268. }
  5269. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  5270. if (buf == nullptr) {
  5271. throw std::runtime_error("unable to allocate backend metal buffer");
  5272. }
  5273. model.bufs.push_back(buf);
  5274. bufs.emplace(idx, buf);
  5275. }
  5276. }
  5277. #endif
  5278. else {
  5279. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  5280. if (buf == nullptr) {
  5281. throw std::runtime_error("unable to allocate backend buffer");
  5282. }
  5283. model.bufs.push_back(buf);
  5284. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  5285. model.mlock_bufs.emplace_back(new llama_mlock);
  5286. auto & mlock_buf = model.mlock_bufs.back();
  5287. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  5288. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  5289. }
  5290. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  5291. bufs.emplace(idx, buf);
  5292. }
  5293. }
  5294. if (bufs.empty()) {
  5295. throw std::runtime_error("failed to allocate buffer");
  5296. }
  5297. for (auto & buf : bufs) {
  5298. // indicate that this buffer contains weights
  5299. // 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
  5300. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  5301. }
  5302. ctx_bufs.emplace_back(ctx, bufs);
  5303. }
  5304. if (llama_supports_gpu_offload()) {
  5305. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  5306. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  5307. if (n_gpu_layers > (int) hparams.n_layer) {
  5308. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  5309. }
  5310. const int max_backend_supported_layers = hparams.n_layer + 1;
  5311. const int max_offloadable_layers = hparams.n_layer + 1;
  5312. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  5313. }
  5314. // print memory requirements
  5315. for (ggml_backend_buffer_t buf : model.bufs) {
  5316. 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);
  5317. }
  5318. // populate tensors_by_name
  5319. for (ggml_context * ctx : model.ctxs) {
  5320. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  5321. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  5322. }
  5323. }
  5324. // load tensor data
  5325. for (auto & it : ctx_bufs) {
  5326. ggml_context * ctx = it.first;
  5327. auto & bufs = it.second;
  5328. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  5329. return false;
  5330. }
  5331. }
  5332. if (use_mmap_buffer) {
  5333. for (auto & mapping : ml.mappings) {
  5334. model.mappings.emplace_back(std::move(mapping));
  5335. }
  5336. }
  5337. // loading time will be recalculate after the first eval, so
  5338. // we take page faults deferred by mmap() into consideration
  5339. model.t_load_us = ggml_time_us() - model.t_start_us;
  5340. return true;
  5341. }
  5342. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  5343. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  5344. try {
  5345. llama_model_loader ml(fname, params.use_mmap, params.check_tensors, params.kv_overrides);
  5346. model.hparams.vocab_only = params.vocab_only;
  5347. try {
  5348. llm_load_arch(ml, model);
  5349. } catch(const std::exception & e) {
  5350. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  5351. }
  5352. try {
  5353. llm_load_hparams(ml, model);
  5354. } catch(const std::exception & e) {
  5355. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  5356. }
  5357. try {
  5358. llm_load_vocab(ml, model);
  5359. } catch(const std::exception & e) {
  5360. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  5361. }
  5362. llm_load_print_meta(ml, model);
  5363. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  5364. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  5365. throw std::runtime_error("vocab size mismatch");
  5366. }
  5367. if (params.vocab_only) {
  5368. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  5369. return 0;
  5370. }
  5371. #ifdef GGML_USE_KOMPUTE
  5372. if (params.n_gpu_layers > 0 && (
  5373. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  5374. || !(
  5375. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  5376. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  5377. model.ftype == LLAMA_FTYPE_MOSTLY_BF16 ||
  5378. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  5379. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  5380. )
  5381. )) {
  5382. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  5383. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  5384. params.n_gpu_layers = 0;
  5385. }
  5386. #endif
  5387. #ifdef GGML_USE_SYCL
  5388. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  5389. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  5390. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  5391. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  5392. } else {
  5393. ggml_backend_sycl_set_mul_device_mode();
  5394. }
  5395. #endif
  5396. if (!llm_load_tensors(
  5397. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  5398. params.progress_callback, params.progress_callback_user_data
  5399. )) {
  5400. return -2;
  5401. }
  5402. } catch (const std::exception & err) {
  5403. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  5404. return -1;
  5405. }
  5406. return 0;
  5407. }
  5408. //
  5409. // llm_build
  5410. //
  5411. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  5412. enum llm_ffn_op_type {
  5413. LLM_FFN_SILU,
  5414. LLM_FFN_GELU,
  5415. LLM_FFN_RELU,
  5416. LLM_FFN_RELU_SQR,
  5417. };
  5418. enum llm_ffn_gate_type {
  5419. LLM_FFN_SEQ,
  5420. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  5421. };
  5422. enum llm_norm_type {
  5423. LLM_NORM,
  5424. LLM_NORM_RMS,
  5425. };
  5426. static struct ggml_tensor * llm_build_inp_embd(
  5427. struct ggml_context * ctx,
  5428. struct llama_context & lctx,
  5429. const llama_hparams & hparams,
  5430. const llama_batch & batch,
  5431. struct ggml_tensor * tok_embd,
  5432. const llm_build_cb & cb) {
  5433. const int64_t n_embd = hparams.n_embd;
  5434. struct ggml_tensor * inpL;
  5435. if (batch.token) {
  5436. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  5437. cb(lctx.inp_tokens, "inp_tokens", -1);
  5438. ggml_set_input(lctx.inp_tokens);
  5439. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  5440. } else {
  5441. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  5442. inpL = lctx.inp_embd;
  5443. ggml_set_input(lctx.inp_embd);
  5444. }
  5445. cb(inpL, "inp_embd", -1);
  5446. return inpL;
  5447. }
  5448. static void llm_build_kv_store(
  5449. struct ggml_context * ctx,
  5450. const llama_hparams & hparams,
  5451. const llama_cparams & cparams,
  5452. const llama_kv_cache & kv,
  5453. struct ggml_cgraph * graph,
  5454. struct ggml_tensor * k_cur,
  5455. struct ggml_tensor * v_cur,
  5456. int32_t n_tokens,
  5457. int32_t kv_head,
  5458. const llm_build_cb & cb,
  5459. int64_t il) {
  5460. const int64_t n_ctx = cparams.n_ctx;
  5461. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5462. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5463. GGML_ASSERT(kv.size == n_ctx);
  5464. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  5465. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  5466. cb(k_cache_view, "k_cache_view", il);
  5467. // note: storing RoPE-ed version of K in the KV cache
  5468. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  5469. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  5470. struct ggml_tensor * v_cache_view = nullptr;
  5471. if (cparams.flash_attn) {
  5472. v_cache_view = ggml_view_1d(ctx, kv.v_l[il], n_tokens*n_embd_v_gqa,
  5473. (kv_head)*ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa));
  5474. } else {
  5475. // note: the V cache is transposed when not using flash attention
  5476. v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  5477. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  5478. (kv_head)*ggml_element_size(kv.v_l[il]));
  5479. v_cur = ggml_transpose(ctx, v_cur);
  5480. }
  5481. cb(v_cache_view, "v_cache_view", il);
  5482. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur, v_cache_view));
  5483. }
  5484. static struct ggml_tensor * llm_build_norm(
  5485. struct ggml_context * ctx,
  5486. struct ggml_tensor * cur,
  5487. const llama_hparams & hparams,
  5488. struct ggml_tensor * mw,
  5489. struct ggml_tensor * mb,
  5490. llm_norm_type type,
  5491. const llm_build_cb & cb,
  5492. int il) {
  5493. switch (type) {
  5494. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  5495. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  5496. }
  5497. if (mw || mb) {
  5498. cb(cur, "norm", il);
  5499. }
  5500. if (mw) {
  5501. cur = ggml_mul(ctx, cur, mw);
  5502. if (mb) {
  5503. cb(cur, "norm_w", il);
  5504. }
  5505. }
  5506. if (mb) {
  5507. cur = ggml_add(ctx, cur, mb);
  5508. }
  5509. return cur;
  5510. }
  5511. static struct ggml_tensor * llm_build_ffn(
  5512. struct ggml_context * ctx,
  5513. struct ggml_tensor * cur,
  5514. struct ggml_tensor * up,
  5515. struct ggml_tensor * up_b,
  5516. struct ggml_tensor * gate,
  5517. struct ggml_tensor * gate_b,
  5518. struct ggml_tensor * down,
  5519. struct ggml_tensor * down_b,
  5520. struct ggml_tensor * act_scales,
  5521. llm_ffn_op_type type_op,
  5522. llm_ffn_gate_type type_gate,
  5523. const llm_build_cb & cb,
  5524. int il) {
  5525. struct ggml_tensor * tmp = up ? ggml_mul_mat(ctx, up, cur) : cur;
  5526. cb(tmp, "ffn_up", il);
  5527. if (up_b) {
  5528. tmp = ggml_add(ctx, tmp, up_b);
  5529. cb(tmp, "ffn_up_b", il);
  5530. }
  5531. if (gate) {
  5532. switch (type_gate) {
  5533. case LLM_FFN_SEQ:
  5534. {
  5535. cur = ggml_mul_mat(ctx, gate, tmp);
  5536. cb(cur, "ffn_gate", il);
  5537. } break;
  5538. case LLM_FFN_PAR:
  5539. {
  5540. cur = ggml_mul_mat(ctx, gate, cur);
  5541. cb(cur, "ffn_gate", il);
  5542. } break;
  5543. }
  5544. if (gate_b) {
  5545. cur = ggml_add(ctx, cur, gate_b);
  5546. cb(cur, "ffn_gate_b", il);
  5547. }
  5548. } else {
  5549. cur = tmp;
  5550. }
  5551. switch (type_op) {
  5552. case LLM_FFN_SILU:
  5553. {
  5554. cur = ggml_silu(ctx, cur);
  5555. cb(cur, "ffn_silu", il);
  5556. } break;
  5557. case LLM_FFN_GELU:
  5558. {
  5559. cur = ggml_gelu(ctx, cur);
  5560. cb(cur, "ffn_gelu", il);
  5561. if (act_scales != NULL) {
  5562. cur = ggml_div(ctx, cur, act_scales);
  5563. cb(cur, "ffn_act", il);
  5564. }
  5565. } break;
  5566. case LLM_FFN_RELU:
  5567. {
  5568. cur = ggml_relu(ctx, cur);
  5569. cb(cur, "ffn_relu", il);
  5570. } break;
  5571. case LLM_FFN_RELU_SQR:
  5572. {
  5573. cur = ggml_relu(ctx, cur);
  5574. cb(cur, "ffn_relu", il);
  5575. cur = ggml_sqr(ctx, cur);
  5576. cb(cur, "ffn_sqr(relu)", il);
  5577. } break;
  5578. }
  5579. if (type_gate == LLM_FFN_PAR) {
  5580. cur = ggml_mul(ctx, cur, tmp);
  5581. cb(cur, "ffn_gate_par", il);
  5582. }
  5583. cur = ggml_mul_mat(ctx, down, cur);
  5584. if (down_b) {
  5585. cb(cur, "ffn_down", il);
  5586. }
  5587. if (down_b) {
  5588. cur = ggml_add(ctx, cur, down_b);
  5589. }
  5590. return cur;
  5591. }
  5592. static struct ggml_tensor * llm_build_moe_ffn(
  5593. struct ggml_context * ctx,
  5594. struct ggml_tensor * cur,
  5595. struct ggml_tensor * gate_inp,
  5596. struct ggml_tensor * up_exps,
  5597. struct ggml_tensor * gate_exps,
  5598. struct ggml_tensor * down_exps,
  5599. int64_t n_expert,
  5600. int64_t n_expert_used,
  5601. llm_ffn_op_type type_op,
  5602. bool norm_w,
  5603. const llm_build_cb & cb,
  5604. int il) {
  5605. int64_t n_embd = cur->ne[0];
  5606. int64_t n_tokens = cur->ne[1];
  5607. ggml_tensor * logits = ggml_mul_mat(ctx, gate_inp, cur); // [n_expert, n_tokens]
  5608. cb(logits, "ffn_moe_logits", il);
  5609. ggml_tensor * probs = ggml_soft_max(ctx, logits); // [n_expert, n_tokens]
  5610. cb(probs, "ffn_moe_probs", il);
  5611. // select experts
  5612. ggml_tensor * selected_experts = ggml_top_k(ctx, probs, n_expert_used); // [n_expert_used, n_tokens]
  5613. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5614. cb(selected_experts, "ffn_moe_topk", il);
  5615. ggml_tensor * weights = ggml_get_rows(ctx,
  5616. ggml_reshape_3d(ctx, probs, 1, n_expert, n_tokens), selected_experts); // [1, n_expert_used, n_tokens]
  5617. cb(weights, "ffn_moe_weights", il);
  5618. if (norm_w) {
  5619. weights = ggml_reshape_2d(ctx, weights, n_expert_used, n_tokens);
  5620. ggml_tensor * weights_sum = ggml_sum_rows(ctx, weights); // [1, n_tokens]
  5621. cb(weights_sum, "ffn_moe_weights_sum", il);
  5622. weights = ggml_div(ctx, weights, weights_sum); // [n_expert_used, n_tokens]
  5623. cb(weights, "ffn_moe_weights_norm", il);
  5624. weights = ggml_reshape_3d(ctx, weights, 1, n_expert_used, n_tokens);
  5625. }
  5626. cur = ggml_reshape_3d(ctx, cur, n_embd, 1, n_tokens);
  5627. ggml_tensor * up = ggml_mul_mat_id(ctx, up_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  5628. cb(up, "ffn_moe_up", il);
  5629. ggml_tensor * gate = ggml_mul_mat_id(ctx, gate_exps, cur, selected_experts); // [n_ff, n_expert_used, n_tokens]
  5630. cb(gate, "ffn_moe_gate", il);
  5631. switch (type_op) {
  5632. case LLM_FFN_SILU:
  5633. {
  5634. gate = ggml_silu(ctx, gate);
  5635. cb(gate, "ffn_moe_silu", il);
  5636. } break;
  5637. case LLM_FFN_GELU:
  5638. {
  5639. gate = ggml_gelu(ctx, gate);
  5640. cb(gate, "ffn_moe_gelu", il);
  5641. } break;
  5642. default:
  5643. GGML_ASSERT(false);
  5644. }
  5645. ggml_tensor * par = ggml_mul(ctx, up, gate); // [n_ff, n_expert_used, n_tokens]
  5646. cb(par, "ffn_moe_gate_par", il);
  5647. ggml_tensor * experts = ggml_mul_mat_id(ctx, down_exps, par, selected_experts); // [n_embd, n_expert_used, n_tokens]
  5648. cb(experts, "ffn_moe_down", il);
  5649. experts = ggml_mul(ctx, experts, weights);
  5650. // aggregate experts
  5651. ggml_tensor * moe_out = nullptr;
  5652. for (int i = 0; i < n_expert_used; ++i) {
  5653. ggml_tensor * cur_expert = ggml_view_2d(ctx, experts, n_embd, n_tokens,
  5654. experts->nb[2], i*experts->nb[1]);
  5655. if (i == 0) {
  5656. moe_out = cur_expert;
  5657. } else {
  5658. moe_out = ggml_add(ctx, moe_out, cur_expert);
  5659. }
  5660. }
  5661. if (n_expert_used == 1) {
  5662. // avoid returning a non-contiguous tensor
  5663. moe_out = ggml_cont(ctx, moe_out);
  5664. }
  5665. return moe_out;
  5666. }
  5667. static struct ggml_tensor * llm_build_kqv(
  5668. struct ggml_context * ctx,
  5669. const llama_model & model,
  5670. const llama_hparams & hparams,
  5671. const llama_cparams & cparams,
  5672. const llama_kv_cache & kv,
  5673. struct ggml_cgraph * graph,
  5674. struct ggml_tensor * wo,
  5675. struct ggml_tensor * wo_b,
  5676. struct ggml_tensor * q_cur,
  5677. struct ggml_tensor * kq_mask,
  5678. int32_t n_tokens,
  5679. int32_t n_kv,
  5680. float kq_scale,
  5681. const llm_build_cb & cb,
  5682. int il) {
  5683. const int64_t n_ctx = cparams.n_ctx;
  5684. const int64_t n_head = hparams.n_head;
  5685. const int64_t n_head_kv = hparams.n_head_kv;
  5686. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5687. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5688. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5689. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  5690. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  5691. cb(q, "q", il);
  5692. struct ggml_tensor * k =
  5693. ggml_view_3d(ctx, kv.k_l[il],
  5694. n_embd_head_k, n_kv, n_head_kv,
  5695. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  5696. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  5697. 0);
  5698. cb(k, "k", il);
  5699. struct ggml_tensor * cur;
  5700. if (cparams.flash_attn) {
  5701. GGML_UNUSED(model);
  5702. GGML_UNUSED(n_ctx);
  5703. // split cached v into n_head heads (not transposed)
  5704. struct ggml_tensor * v =
  5705. ggml_view_3d(ctx, kv.v_l[il],
  5706. n_embd_head_v, n_kv, n_head_kv,
  5707. ggml_row_size(kv.v_l[il]->type, n_embd_v_gqa),
  5708. ggml_row_size(kv.v_l[il]->type, n_embd_head_v),
  5709. 0);
  5710. cb(v, "v", il);
  5711. cur = ggml_flash_attn_ext(ctx, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  5712. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3) {
  5713. ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
  5714. }
  5715. cur = ggml_reshape_2d(ctx, cur, n_embd_head_v*n_head, n_tokens);
  5716. } else {
  5717. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  5718. cb(kq, "kq", il);
  5719. if (model.arch == LLM_ARCH_PHI2 || model.arch == LLM_ARCH_PHI3) {
  5720. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  5721. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  5722. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5723. }
  5724. if (model.arch == LLM_ARCH_GROK) {
  5725. // need to do the following:
  5726. // multiply by attn_output_multiplyer of 0.08838834764831845
  5727. // and then :
  5728. // kq = 30 * tanh(kq / 30)
  5729. // before the softmax below
  5730. //try from phi2
  5731. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5732. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  5733. kq = ggml_scale(ctx, kq, 30);
  5734. }
  5735. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias);
  5736. cb(kq, "kq_soft_max_ext", il);
  5737. GGML_ASSERT(kv.size == n_ctx);
  5738. // split cached v into n_head heads
  5739. struct ggml_tensor * v =
  5740. ggml_view_3d(ctx, kv.v_l[il],
  5741. n_kv, n_embd_head_v, n_head_kv,
  5742. ggml_element_size(kv.v_l[il])*n_ctx,
  5743. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  5744. 0);
  5745. cb(v, "v", il);
  5746. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  5747. cb(kqv, "kqv", il);
  5748. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  5749. cb(kqv_merged, "kqv_merged", il);
  5750. cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_v*n_head, n_tokens);
  5751. cb(cur, "kqv_merged_cont", il);
  5752. }
  5753. ggml_build_forward_expand(graph, cur);
  5754. cur = ggml_mul_mat(ctx, wo, cur);
  5755. if (wo_b) {
  5756. cb(cur, "kqv_wo", il);
  5757. }
  5758. if (wo_b) {
  5759. cur = ggml_add(ctx, cur, wo_b);
  5760. }
  5761. return cur;
  5762. }
  5763. static struct ggml_tensor * llm_build_kv(
  5764. struct ggml_context * ctx,
  5765. const llama_model & model,
  5766. const llama_hparams & hparams,
  5767. const llama_cparams & cparams,
  5768. const llama_kv_cache & kv,
  5769. struct ggml_cgraph * graph,
  5770. struct ggml_tensor * wo,
  5771. struct ggml_tensor * wo_b,
  5772. struct ggml_tensor * k_cur,
  5773. struct ggml_tensor * v_cur,
  5774. struct ggml_tensor * q_cur,
  5775. struct ggml_tensor * kq_mask,
  5776. int32_t n_tokens,
  5777. int32_t kv_head,
  5778. int32_t n_kv,
  5779. float kq_scale,
  5780. const llm_build_cb & cb,
  5781. int il) {
  5782. // these nodes are added to the graph together so that they are not reordered
  5783. // by doing so, the number of splits in the graph is reduced
  5784. ggml_build_forward_expand(graph, q_cur);
  5785. ggml_build_forward_expand(graph, k_cur);
  5786. ggml_build_forward_expand(graph, v_cur);
  5787. llm_build_kv_store(ctx, hparams, cparams, kv, graph, k_cur, v_cur, n_tokens, kv_head, cb, il);
  5788. struct ggml_tensor * cur;
  5789. cur = llm_build_kqv(ctx, model, hparams, cparams, kv, graph, wo, wo_b,
  5790. q_cur, kq_mask, n_tokens, n_kv, kq_scale, cb, il);
  5791. cb(cur, "kqv_out", il);
  5792. return cur;
  5793. }
  5794. struct llm_build_context {
  5795. const llama_model & model;
  5796. llama_context & lctx;
  5797. const llama_hparams & hparams;
  5798. const llama_cparams & cparams;
  5799. const llama_batch & batch;
  5800. const llama_kv_cache & kv_self;
  5801. const int64_t n_embd;
  5802. const int64_t n_layer;
  5803. const int64_t n_rot;
  5804. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5805. const int64_t n_head;
  5806. const int64_t n_head_kv;
  5807. const int64_t n_embd_head_k;
  5808. const int64_t n_embd_k_gqa;
  5809. const int64_t n_embd_head_v;
  5810. const int64_t n_embd_v_gqa;
  5811. const int64_t n_expert;
  5812. const int64_t n_expert_used;
  5813. const float freq_base;
  5814. const float freq_scale;
  5815. const float ext_factor;
  5816. const float attn_factor;
  5817. const float beta_fast;
  5818. const float beta_slow;
  5819. const float norm_eps;
  5820. const float norm_rms_eps;
  5821. const int32_t n_tokens;
  5822. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5823. const int32_t n_outputs;
  5824. const int32_t kv_head; // index of where we store new KV data in the cache
  5825. const int32_t n_orig_ctx;
  5826. const bool flash_attn;
  5827. const enum llama_pooling_type pooling_type;
  5828. const enum llama_rope_type rope_type;
  5829. const llm_build_cb & cb;
  5830. std::vector<uint8_t> & buf_compute_meta;
  5831. struct ggml_context * ctx0 = nullptr;
  5832. // TODO: consider making the entire interface noexcept
  5833. llm_build_context(
  5834. llama_context & lctx,
  5835. const llama_batch & batch,
  5836. const llm_build_cb & cb,
  5837. bool worst_case) :
  5838. model (lctx.model),
  5839. lctx (lctx),
  5840. hparams (model.hparams),
  5841. cparams (lctx.cparams),
  5842. batch (batch),
  5843. kv_self (lctx.kv_self),
  5844. n_embd (hparams.n_embd),
  5845. n_layer (hparams.n_layer),
  5846. n_rot (hparams.n_rot),
  5847. n_ctx (cparams.n_ctx),
  5848. n_head (hparams.n_head),
  5849. n_head_kv (hparams.n_head_kv),
  5850. n_embd_head_k (hparams.n_embd_head_k),
  5851. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5852. n_embd_head_v (hparams.n_embd_head_v),
  5853. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5854. n_expert (hparams.n_expert),
  5855. n_expert_used (hparams.n_expert_used),
  5856. freq_base (cparams.rope_freq_base),
  5857. freq_scale (cparams.rope_freq_scale),
  5858. ext_factor (cparams.yarn_ext_factor),
  5859. attn_factor (cparams.yarn_attn_factor),
  5860. beta_fast (cparams.yarn_beta_fast),
  5861. beta_slow (cparams.yarn_beta_slow),
  5862. norm_eps (hparams.f_norm_eps),
  5863. norm_rms_eps (hparams.f_norm_rms_eps),
  5864. n_tokens (batch.n_tokens),
  5865. n_kv (worst_case ? kv_self.size : kv_self.n),
  5866. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5867. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5868. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5869. flash_attn (cparams.flash_attn),
  5870. pooling_type (cparams.pooling_type),
  5871. rope_type (hparams.rope_type),
  5872. cb (cb),
  5873. buf_compute_meta (lctx.buf_compute_meta) {
  5874. // all initializations should be done in init()
  5875. }
  5876. void init() {
  5877. struct ggml_init_params params = {
  5878. /*.mem_size =*/ buf_compute_meta.size(),
  5879. /*.mem_buffer =*/ buf_compute_meta.data(),
  5880. /*.no_alloc =*/ true,
  5881. };
  5882. ctx0 = ggml_init(params);
  5883. lctx.inp_tokens = nullptr;
  5884. lctx.inp_embd = nullptr;
  5885. lctx.inp_pos = nullptr;
  5886. lctx.inp_out_ids = nullptr;
  5887. lctx.inp_KQ_mask = nullptr;
  5888. lctx.inp_K_shift = nullptr;
  5889. lctx.inp_mean = nullptr;
  5890. lctx.inp_cls = nullptr;
  5891. lctx.inp_s_copy = nullptr;
  5892. lctx.inp_s_mask = nullptr;
  5893. lctx.inp_s_seq = nullptr;
  5894. }
  5895. void free() {
  5896. if (ctx0) {
  5897. ggml_free(ctx0);
  5898. ctx0 = nullptr;
  5899. }
  5900. }
  5901. struct ggml_cgraph * build_k_shift() {
  5902. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5903. GGML_ASSERT(kv_self.size == n_ctx);
  5904. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5905. cb(lctx.inp_K_shift, "K_shift", -1);
  5906. ggml_set_input(lctx.inp_K_shift);
  5907. for (int il = 0; il < n_layer; ++il) {
  5908. struct ggml_tensor * tmp =
  5909. // we rotate only the first n_rot dimensions
  5910. ggml_rope_custom_inplace(ctx0,
  5911. ggml_view_3d(ctx0, kv_self.k_l[il],
  5912. n_embd_head_k, n_head_kv, n_ctx,
  5913. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5914. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5915. 0),
  5916. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5917. ext_factor, attn_factor, beta_fast, beta_slow);
  5918. cb(tmp, "K_shifted", il);
  5919. ggml_build_forward_expand(gf, tmp);
  5920. }
  5921. return gf;
  5922. }
  5923. struct ggml_cgraph * build_s_copy() {
  5924. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5925. GGML_ASSERT(kv_self.recurrent);
  5926. struct ggml_tensor * state_copy = build_inp_s_copy();
  5927. for (int il = 0; il < n_layer; ++il) {
  5928. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5929. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5930. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5931. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5932. // TODO: name the intermediate tensors with cb()
  5933. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5934. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5935. }
  5936. return gf;
  5937. }
  5938. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5939. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5940. for (uint32_t i = 0; i < ids.size(); ++i) {
  5941. const uint32_t id = ids[i];
  5942. if (i == id || id == ids.size()) {
  5943. continue;
  5944. }
  5945. uint32_t nm = 1;
  5946. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5947. nm++;
  5948. }
  5949. for (int il = 0; il < n_layer; ++il) {
  5950. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5951. n_embd_k_gqa, nm,
  5952. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5953. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5954. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5955. n_embd_k_gqa, nm,
  5956. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5957. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5958. ggml_tensor * view_v_src;
  5959. ggml_tensor * view_v_dst;
  5960. if (flash_attn) {
  5961. // NOTE: the V cache is not transposed when using flash attention
  5962. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5963. n_embd_v_gqa, nm,
  5964. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  5965. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*i));
  5966. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5967. n_embd_v_gqa, nm,
  5968. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa),
  5969. ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*id));
  5970. } else {
  5971. view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5972. nm, n_embd_v_gqa,
  5973. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5974. ggml_row_size(kv_self.v_l[il]->type, i));
  5975. view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5976. nm, n_embd_v_gqa,
  5977. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5978. ggml_row_size(kv_self.v_l[il]->type, id));
  5979. }
  5980. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5981. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5982. }
  5983. i += nm - 1;
  5984. }
  5985. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5986. return gf;
  5987. }
  5988. struct ggml_tensor * build_inp_pos() {
  5989. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5990. cb(lctx.inp_pos, "inp_pos", -1);
  5991. ggml_set_input(lctx.inp_pos);
  5992. return lctx.inp_pos;
  5993. }
  5994. struct ggml_tensor * build_inp_out_ids() {
  5995. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5996. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5997. ggml_set_input(lctx.inp_out_ids);
  5998. return lctx.inp_out_ids;
  5999. }
  6000. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  6001. if (causal) {
  6002. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  6003. } else {
  6004. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, GGML_PAD(n_tokens, GGML_KQ_MASK_PAD));
  6005. }
  6006. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  6007. ggml_set_input(lctx.inp_KQ_mask);
  6008. return flash_attn ? ggml_cast(ctx0, lctx.inp_KQ_mask, GGML_TYPE_F16) : lctx.inp_KQ_mask;
  6009. }
  6010. struct ggml_tensor * build_inp_mean() {
  6011. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  6012. cb(lctx.inp_mean, "inp_mean", -1);
  6013. ggml_set_input(lctx.inp_mean);
  6014. return lctx.inp_mean;
  6015. }
  6016. struct ggml_tensor * build_inp_cls() {
  6017. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  6018. cb(lctx.inp_cls, "inp_cls", -1);
  6019. ggml_set_input(lctx.inp_cls);
  6020. return lctx.inp_cls;
  6021. }
  6022. struct ggml_tensor * build_inp_s_copy() {
  6023. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  6024. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  6025. ggml_set_input(lctx.inp_s_copy);
  6026. return lctx.inp_s_copy;
  6027. }
  6028. struct ggml_tensor * build_inp_s_mask() {
  6029. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  6030. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  6031. ggml_set_input(lctx.inp_s_mask);
  6032. return lctx.inp_s_mask;
  6033. }
  6034. struct ggml_tensor * build_inp_s_seq() {
  6035. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  6036. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  6037. ggml_set_input(lctx.inp_s_seq);
  6038. return lctx.inp_s_seq;
  6039. }
  6040. struct ggml_cgraph * build_llama() {
  6041. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6042. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6043. int32_t n_tokens = this->n_tokens;
  6044. const int64_t n_embd_head = hparams.n_embd_head_v;
  6045. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6046. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6047. struct ggml_tensor * cur;
  6048. struct ggml_tensor * inpL;
  6049. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6050. // inp_pos - contains the positions
  6051. struct ggml_tensor * inp_pos = build_inp_pos();
  6052. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6053. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6054. for (int il = 0; il < n_layer; ++il) {
  6055. struct ggml_tensor * inpSA = inpL;
  6056. // norm
  6057. cur = llm_build_norm(ctx0, inpL, hparams,
  6058. model.layers[il].attn_norm, NULL,
  6059. LLM_NORM_RMS, cb, il);
  6060. cb(cur, "attn_norm", il);
  6061. // self-attention
  6062. {
  6063. // compute Q and K and RoPE them
  6064. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6065. cb(Qcur, "Qcur", il);
  6066. if (model.layers[il].bq) {
  6067. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6068. cb(Qcur, "Qcur", il);
  6069. }
  6070. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6071. cb(Kcur, "Kcur", il);
  6072. if (model.layers[il].bk) {
  6073. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6074. cb(Kcur, "Kcur", il);
  6075. }
  6076. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6077. cb(Vcur, "Vcur", il);
  6078. if (model.layers[il].bv) {
  6079. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6080. cb(Vcur, "Vcur", il);
  6081. }
  6082. Qcur = ggml_rope_custom(
  6083. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6084. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6085. ext_factor, attn_factor, beta_fast, beta_slow
  6086. );
  6087. cb(Qcur, "Qcur", il);
  6088. Kcur = ggml_rope_custom(
  6089. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6090. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6091. ext_factor, attn_factor, beta_fast, beta_slow
  6092. );
  6093. cb(Kcur, "Kcur", il);
  6094. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6095. model.layers[il].wo, model.layers[il].bo,
  6096. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6097. }
  6098. if (il == n_layer - 1) {
  6099. // skip computing output for unused tokens
  6100. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6101. n_tokens = n_outputs;
  6102. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6103. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6104. }
  6105. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6106. cb(ffn_inp, "ffn_inp", il);
  6107. // feed-forward network
  6108. if (model.layers[il].ffn_gate_inp == nullptr) {
  6109. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6110. model.layers[il].ffn_norm, NULL,
  6111. LLM_NORM_RMS, cb, il);
  6112. cb(cur, "ffn_norm", il);
  6113. cur = llm_build_ffn(ctx0, cur,
  6114. model.layers[il].ffn_up, NULL,
  6115. model.layers[il].ffn_gate, NULL,
  6116. model.layers[il].ffn_down, NULL,
  6117. NULL,
  6118. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6119. cb(cur, "ffn_out", il);
  6120. } else {
  6121. // MoE branch
  6122. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6123. model.layers[il].ffn_norm, NULL,
  6124. LLM_NORM_RMS, cb, il);
  6125. cb(cur, "ffn_norm", il);
  6126. cur = llm_build_moe_ffn(ctx0, cur,
  6127. model.layers[il].ffn_gate_inp,
  6128. model.layers[il].ffn_up_exps,
  6129. model.layers[il].ffn_gate_exps,
  6130. model.layers[il].ffn_down_exps,
  6131. n_expert, n_expert_used,
  6132. LLM_FFN_SILU, true,
  6133. cb, il);
  6134. cb(cur, "ffn_moe_out", il);
  6135. }
  6136. cur = ggml_add(ctx0, cur, ffn_inp);
  6137. cb(cur, "ffn_out", il);
  6138. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6139. if (layer_dir != nullptr) {
  6140. cur = ggml_add(ctx0, cur, layer_dir);
  6141. }
  6142. cb(cur, "l_out", il);
  6143. // input for next layer
  6144. inpL = cur;
  6145. }
  6146. cur = inpL;
  6147. cur = llm_build_norm(ctx0, cur, hparams,
  6148. model.output_norm, NULL,
  6149. LLM_NORM_RMS, cb, -1);
  6150. cb(cur, "result_norm", -1);
  6151. // lm_head
  6152. cur = ggml_mul_mat(ctx0, model.output, cur);
  6153. cb(cur, "result_output", -1);
  6154. ggml_build_forward_expand(gf, cur);
  6155. return gf;
  6156. }
  6157. struct ggml_cgraph * build_baichuan() {
  6158. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6159. const int64_t n_embd_head = hparams.n_embd_head_v;
  6160. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6161. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6162. struct ggml_tensor * cur;
  6163. struct ggml_tensor * inpL;
  6164. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6165. // inp_pos - contains the positions
  6166. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  6167. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6168. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6169. for (int il = 0; il < n_layer; ++il) {
  6170. struct ggml_tensor * inpSA = inpL;
  6171. cur = llm_build_norm(ctx0, inpL, hparams,
  6172. model.layers[il].attn_norm, NULL,
  6173. LLM_NORM_RMS, cb, il);
  6174. cb(cur, "attn_norm", il);
  6175. // self-attention
  6176. {
  6177. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6178. cb(Qcur, "Qcur", il);
  6179. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6180. cb(Kcur, "Kcur", il);
  6181. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6182. cb(Vcur, "Vcur", il);
  6183. switch (model.type) {
  6184. case MODEL_7B:
  6185. Qcur = ggml_rope_custom(
  6186. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6187. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6188. ext_factor, attn_factor, beta_fast, beta_slow
  6189. );
  6190. Kcur = ggml_rope_custom(
  6191. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6192. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6193. ext_factor, attn_factor, beta_fast, beta_slow
  6194. );
  6195. break;
  6196. case MODEL_13B:
  6197. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  6198. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  6199. break;
  6200. default:
  6201. GGML_ASSERT(false);
  6202. }
  6203. cb(Qcur, "Qcur", il);
  6204. cb(Kcur, "Kcur", il);
  6205. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6206. model.layers[il].wo, NULL,
  6207. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6208. }
  6209. if (il == n_layer - 1) {
  6210. // skip computing output for unused tokens
  6211. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6212. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6213. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6214. }
  6215. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6216. cb(ffn_inp, "ffn_inp", il);
  6217. // feed-forward network
  6218. {
  6219. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6220. model.layers[il].ffn_norm, NULL,
  6221. LLM_NORM_RMS, cb, il);
  6222. cb(cur, "ffn_norm", il);
  6223. cur = llm_build_ffn(ctx0, cur,
  6224. model.layers[il].ffn_up, NULL,
  6225. model.layers[il].ffn_gate, NULL,
  6226. model.layers[il].ffn_down, NULL,
  6227. NULL,
  6228. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6229. cb(cur, "ffn_out", il);
  6230. }
  6231. cur = ggml_add(ctx0, cur, ffn_inp);
  6232. cb(cur, "l_out", il);
  6233. // input for next layer
  6234. inpL = cur;
  6235. }
  6236. cur = inpL;
  6237. cur = llm_build_norm(ctx0, cur, hparams,
  6238. model.output_norm, NULL,
  6239. LLM_NORM_RMS, cb, -1);
  6240. cb(cur, "result_norm", -1);
  6241. // lm_head
  6242. cur = ggml_mul_mat(ctx0, model.output, cur);
  6243. cb(cur, "result_output", -1);
  6244. ggml_build_forward_expand(gf, cur);
  6245. return gf;
  6246. }
  6247. struct ggml_cgraph * build_xverse() {
  6248. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6249. const int64_t n_embd_head = hparams.n_embd_head_v;
  6250. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6251. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6252. struct ggml_tensor * cur;
  6253. struct ggml_tensor * inpL;
  6254. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6255. // inp_pos - contains the positions
  6256. struct ggml_tensor * inp_pos = build_inp_pos();
  6257. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6258. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6259. for (int il = 0; il < n_layer; ++il) {
  6260. struct ggml_tensor * inpSA = inpL;
  6261. cur = llm_build_norm(ctx0, inpL, hparams,
  6262. model.layers[il].attn_norm, NULL,
  6263. LLM_NORM_RMS, cb, il);
  6264. cb(cur, "attn_norm", il);
  6265. // self-attention
  6266. {
  6267. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6268. cb(Qcur, "Qcur", il);
  6269. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6270. cb(Kcur, "Kcur", il);
  6271. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6272. cb(Vcur, "Vcur", il);
  6273. Qcur = ggml_rope_custom(
  6274. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6275. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6276. ext_factor, attn_factor, beta_fast, beta_slow
  6277. );
  6278. cb(Qcur, "Qcur", il);
  6279. Kcur = ggml_rope_custom(
  6280. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6281. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6282. ext_factor, attn_factor, beta_fast, beta_slow
  6283. );
  6284. cb(Kcur, "Kcur", il);
  6285. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6286. model.layers[il].wo, NULL,
  6287. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6288. }
  6289. if (il == n_layer - 1) {
  6290. // skip computing output for unused tokens
  6291. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6292. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6293. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6294. }
  6295. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6296. cb(ffn_inp, "ffn_inp", il);
  6297. // feed-forward network
  6298. {
  6299. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6300. model.layers[il].ffn_norm, NULL,
  6301. LLM_NORM_RMS, cb, il);
  6302. cb(cur, "ffn_norm", il);
  6303. cur = llm_build_ffn(ctx0, cur,
  6304. model.layers[il].ffn_up, NULL,
  6305. model.layers[il].ffn_gate, NULL,
  6306. model.layers[il].ffn_down, NULL,
  6307. NULL,
  6308. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6309. cb(cur, "ffn_out", il);
  6310. }
  6311. cur = ggml_add(ctx0, cur, ffn_inp);
  6312. cb(cur, "l_out", il);
  6313. // input for next layer
  6314. inpL = cur;
  6315. }
  6316. cur = inpL;
  6317. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  6318. cb(cur, "result_norm", -1);
  6319. // lm_head
  6320. cur = ggml_mul_mat(ctx0, model.output, cur);
  6321. cb(cur, "result_output", -1);
  6322. ggml_build_forward_expand(gf, cur);
  6323. return gf;
  6324. }
  6325. struct ggml_cgraph * build_falcon() {
  6326. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6327. const int64_t n_embd_head = hparams.n_embd_head_v;
  6328. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6329. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6330. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6331. struct ggml_tensor * cur;
  6332. struct ggml_tensor * inpL;
  6333. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6334. // inp_pos - contains the positions
  6335. struct ggml_tensor * inp_pos = build_inp_pos();
  6336. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6337. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6338. for (int il = 0; il < n_layer; ++il) {
  6339. struct ggml_tensor * attn_norm;
  6340. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6341. model.layers[il].attn_norm,
  6342. model.layers[il].attn_norm_b,
  6343. LLM_NORM, cb, il);
  6344. cb(attn_norm, "attn_norm", il);
  6345. // self-attention
  6346. {
  6347. if (model.layers[il].attn_norm_2) {
  6348. // Falcon-40B
  6349. cur = llm_build_norm(ctx0, inpL, hparams,
  6350. model.layers[il].attn_norm_2,
  6351. model.layers[il].attn_norm_2_b,
  6352. LLM_NORM, cb, il);
  6353. cb(cur, "attn_norm_2", il);
  6354. } else {
  6355. cur = attn_norm;
  6356. }
  6357. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6358. cb(cur, "wqkv", il);
  6359. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6360. 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)));
  6361. 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)));
  6362. cb(Qcur, "Qcur", il);
  6363. cb(Kcur, "Kcur", il);
  6364. cb(Vcur, "Vcur", il);
  6365. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6366. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6367. // using mode = 2 for neox mode
  6368. Qcur = ggml_rope_custom(
  6369. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6370. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6371. );
  6372. cb(Qcur, "Qcur", il);
  6373. Kcur = ggml_rope_custom(
  6374. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6375. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6376. );
  6377. cb(Kcur, "Kcur", il);
  6378. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6379. model.layers[il].wo, NULL,
  6380. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6381. }
  6382. if (il == n_layer - 1) {
  6383. // skip computing output for unused tokens
  6384. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6385. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6386. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6387. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  6388. }
  6389. struct ggml_tensor * ffn_inp = cur;
  6390. // feed forward
  6391. {
  6392. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  6393. model.layers[il].ffn_up, NULL,
  6394. NULL, NULL,
  6395. model.layers[il].ffn_down, NULL,
  6396. NULL,
  6397. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6398. cb(cur, "ffn_out", il);
  6399. }
  6400. cur = ggml_add(ctx0, cur, ffn_inp);
  6401. cb(cur, "l_out", il);
  6402. cur = ggml_add(ctx0, cur, inpL);
  6403. cb(cur, "l_out", il);
  6404. // input for next layer
  6405. inpL = cur;
  6406. }
  6407. cur = inpL;
  6408. // norm
  6409. cur = llm_build_norm(ctx0, cur, hparams,
  6410. model.output_norm,
  6411. model.output_norm_b,
  6412. LLM_NORM, cb, -1);
  6413. cb(cur, "result_norm", -1);
  6414. cur = ggml_mul_mat(ctx0, model.output, cur);
  6415. cb(cur, "result_output", -1);
  6416. ggml_build_forward_expand(gf, cur);
  6417. return gf;
  6418. }
  6419. struct ggml_cgraph * build_grok() {
  6420. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6421. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6422. int32_t n_tokens = this->n_tokens;
  6423. const int64_t n_embd_head = hparams.n_embd_head_v;
  6424. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6425. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6426. struct ggml_tensor * cur;
  6427. struct ggml_tensor * inpL;
  6428. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6429. // multiply by embedding_multiplier_scale of 78.38367176906169
  6430. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  6431. // inp_pos - contains the positions
  6432. struct ggml_tensor * inp_pos = build_inp_pos();
  6433. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6434. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6435. for (int il = 0; il < n_layer; ++il) {
  6436. struct ggml_tensor * inpSA = inpL;
  6437. // norm
  6438. cur = llm_build_norm(ctx0, inpL, hparams,
  6439. model.layers[il].attn_norm, NULL,
  6440. LLM_NORM_RMS, cb, il);
  6441. cb(cur, "attn_norm", il);
  6442. // self-attention
  6443. {
  6444. // compute Q and K and RoPE them
  6445. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6446. cb(Qcur, "Qcur", il);
  6447. if (model.layers[il].bq) {
  6448. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6449. cb(Qcur, "Qcur", il);
  6450. }
  6451. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6452. cb(Kcur, "Kcur", il);
  6453. if (model.layers[il].bk) {
  6454. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6455. cb(Kcur, "Kcur", il);
  6456. }
  6457. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6458. cb(Vcur, "Vcur", il);
  6459. if (model.layers[il].bv) {
  6460. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6461. cb(Vcur, "Vcur", il);
  6462. }
  6463. Qcur = ggml_rope_custom(
  6464. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6465. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6466. ext_factor, attn_factor, beta_fast, beta_slow
  6467. );
  6468. cb(Qcur, "Qcur", il);
  6469. Kcur = ggml_rope_custom(
  6470. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6471. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6472. ext_factor, attn_factor, beta_fast, beta_slow
  6473. );
  6474. cb(Kcur, "Kcur", il);
  6475. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6476. model.layers[il].wo, model.layers[il].bo,
  6477. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6478. }
  6479. if (il == n_layer - 1) {
  6480. // skip computing output for unused tokens
  6481. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6482. n_tokens = n_outputs;
  6483. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6484. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6485. }
  6486. // Grok
  6487. // if attn_out_norm is present then apply it before adding the input
  6488. if (model.layers[il].attn_out_norm) {
  6489. cur = llm_build_norm(ctx0, cur, hparams,
  6490. model.layers[il].attn_out_norm, NULL,
  6491. LLM_NORM_RMS, cb, il);
  6492. cb(cur, "attn_out_norm", il);
  6493. }
  6494. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6495. cb(ffn_inp, "ffn_inp", il);
  6496. // feed-forward network
  6497. // MoE branch
  6498. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6499. model.layers[il].ffn_norm, NULL,
  6500. LLM_NORM_RMS, cb, il);
  6501. cb(cur, "ffn_norm", il);
  6502. cur = llm_build_moe_ffn(ctx0, cur,
  6503. model.layers[il].ffn_gate_inp,
  6504. model.layers[il].ffn_up_exps,
  6505. model.layers[il].ffn_gate_exps,
  6506. model.layers[il].ffn_down_exps,
  6507. n_expert, n_expert_used,
  6508. LLM_FFN_GELU, true,
  6509. cb, il);
  6510. cb(cur, "ffn_moe_out", il);
  6511. // Grok
  6512. // if layer_out_norm is present then apply it before adding the input
  6513. // Idea: maybe ffn_out_norm is a better name
  6514. if (model.layers[il].layer_out_norm) {
  6515. cur = llm_build_norm(ctx0, cur, hparams,
  6516. model.layers[il].layer_out_norm, NULL,
  6517. LLM_NORM_RMS, cb, il);
  6518. cb(cur, "layer_out_norm", il);
  6519. }
  6520. cur = ggml_add(ctx0, cur, ffn_inp);
  6521. cb(cur, "ffn_out", il);
  6522. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6523. if (layer_dir != nullptr) {
  6524. cur = ggml_add(ctx0, cur, layer_dir);
  6525. }
  6526. cb(cur, "l_out", il);
  6527. // input for next layer
  6528. inpL = cur;
  6529. }
  6530. cur = inpL;
  6531. cur = llm_build_norm(ctx0, cur, hparams,
  6532. model.output_norm, NULL,
  6533. LLM_NORM_RMS, cb, -1);
  6534. cb(cur, "result_norm", -1);
  6535. // lm_head
  6536. cur = ggml_mul_mat(ctx0, model.output, cur);
  6537. // Grok
  6538. // multiply logits by output_multiplier_scale of 0.5773502691896257
  6539. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  6540. cb(cur, "result_output", -1);
  6541. ggml_build_forward_expand(gf, cur);
  6542. return gf;
  6543. }
  6544. struct ggml_cgraph * build_dbrx() {
  6545. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6546. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6547. int32_t n_tokens = this->n_tokens;
  6548. const int64_t n_embd_head = hparams.n_embd_head_v;
  6549. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6550. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6551. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6552. struct ggml_tensor * cur;
  6553. struct ggml_tensor * inpL;
  6554. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6555. // inp_pos - contains the positions
  6556. struct ggml_tensor * inp_pos = build_inp_pos();
  6557. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6558. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6559. for (int il = 0; il < n_layer; ++il) {
  6560. struct ggml_tensor * inpSA = inpL;
  6561. // norm
  6562. cur = llm_build_norm(ctx0, inpL, hparams,
  6563. model.layers[il].attn_norm, NULL,
  6564. LLM_NORM, cb, il);
  6565. cb(cur, "attn_norm", il);
  6566. // self-attention
  6567. {
  6568. struct ggml_tensor * Qcur = nullptr;
  6569. struct ggml_tensor * Kcur = nullptr;
  6570. struct ggml_tensor * Vcur = nullptr;
  6571. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6572. cb(cur, "wqkv", il);
  6573. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6574. cb(cur, "wqkv_clamped", il);
  6575. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6576. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6577. 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)));
  6578. cb(Qcur, "Qcur", il);
  6579. cb(Kcur, "Kcur", il);
  6580. cb(Vcur, "Vcur", il);
  6581. Qcur = ggml_rope_custom(
  6582. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6583. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6584. ext_factor, attn_factor, beta_fast, beta_slow
  6585. );
  6586. cb(Qcur, "Qcur", il);
  6587. Kcur = ggml_rope_custom(
  6588. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6589. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6590. ext_factor, attn_factor, beta_fast, beta_slow
  6591. );
  6592. cb(Kcur, "Kcur", il);
  6593. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6594. model.layers[il].wo, NULL,
  6595. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6596. }
  6597. if (il == n_layer - 1) {
  6598. // skip computing output for unused tokens
  6599. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6600. n_tokens = n_outputs;
  6601. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6602. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6603. }
  6604. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6605. cb(ffn_inp, "ffn_inp", il);
  6606. // feed-forward network
  6607. // MoE branch
  6608. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6609. model.layers[il].attn_out_norm, NULL,
  6610. LLM_NORM, cb, il);
  6611. cb(cur, "attn_out_norm", il);
  6612. cur = llm_build_moe_ffn(ctx0, cur,
  6613. model.layers[il].ffn_gate_inp,
  6614. model.layers[il].ffn_up_exps,
  6615. model.layers[il].ffn_gate_exps,
  6616. model.layers[il].ffn_down_exps,
  6617. n_expert, n_expert_used,
  6618. LLM_FFN_SILU, true,
  6619. cb, il);
  6620. cb(cur, "ffn_moe_out", il);
  6621. cur = ggml_add(ctx0, cur, ffn_inp);
  6622. cb(cur, "ffn_out", il);
  6623. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6624. if (layer_dir != nullptr) {
  6625. cur = ggml_add(ctx0, cur, layer_dir);
  6626. }
  6627. cb(cur, "l_out", il);
  6628. // input for next layer
  6629. inpL = cur;
  6630. }
  6631. cur = inpL;
  6632. cur = llm_build_norm(ctx0, cur, hparams,
  6633. model.output_norm, NULL,
  6634. LLM_NORM, cb, -1);
  6635. cb(cur, "result_norm", -1);
  6636. // lm_head
  6637. cur = ggml_mul_mat(ctx0, model.output, cur);
  6638. cb(cur, "result_output", -1);
  6639. ggml_build_forward_expand(gf, cur);
  6640. return gf;
  6641. }
  6642. struct ggml_cgraph * build_starcoder() {
  6643. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6644. const int64_t n_embd_head = hparams.n_embd_head_v;
  6645. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6646. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6647. struct ggml_tensor * cur;
  6648. struct ggml_tensor * inpL;
  6649. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6650. // inp_pos - contains the positions
  6651. struct ggml_tensor * inp_pos = build_inp_pos();
  6652. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6653. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6654. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6655. cb(pos, "pos_embd", -1);
  6656. inpL = ggml_add(ctx0, inpL, pos);
  6657. cb(inpL, "inpL", -1);
  6658. for (int il = 0; il < n_layer; ++il) {
  6659. cur = llm_build_norm(ctx0, inpL, hparams,
  6660. model.layers[il].attn_norm,
  6661. model.layers[il].attn_norm_b,
  6662. LLM_NORM, cb, il);
  6663. cb(cur, "attn_norm", il);
  6664. // self-attention
  6665. {
  6666. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6667. cb(cur, "wqkv", il);
  6668. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6669. cb(cur, "bqkv", il);
  6670. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6671. 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)));
  6672. 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)));
  6673. cb(Qcur, "Qcur", il);
  6674. cb(Kcur, "Kcur", il);
  6675. cb(Vcur, "Vcur", il);
  6676. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6677. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6678. model.layers[il].wo, model.layers[il].bo,
  6679. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6680. }
  6681. if (il == n_layer - 1) {
  6682. // skip computing output for unused tokens
  6683. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6684. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6685. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6686. }
  6687. // add the input
  6688. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6689. cb(ffn_inp, "ffn_inp", il);
  6690. // FF
  6691. {
  6692. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6693. model.layers[il].ffn_norm,
  6694. model.layers[il].ffn_norm_b,
  6695. LLM_NORM, cb, il);
  6696. cb(cur, "ffn_norm", il);
  6697. cur = llm_build_ffn(ctx0, cur,
  6698. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6699. NULL, NULL,
  6700. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6701. NULL,
  6702. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6703. cb(cur, "ffn_out", il);
  6704. }
  6705. inpL = ggml_add(ctx0, cur, ffn_inp);
  6706. cb(inpL, "l_out", il);
  6707. }
  6708. cur = llm_build_norm(ctx0, inpL, hparams,
  6709. model.output_norm,
  6710. model.output_norm_b,
  6711. LLM_NORM, cb, -1);
  6712. cb(cur, "result_norm", -1);
  6713. cur = ggml_mul_mat(ctx0, model.output, cur);
  6714. cb(cur, "result_output", -1);
  6715. ggml_build_forward_expand(gf, cur);
  6716. return gf;
  6717. }
  6718. struct ggml_cgraph * build_persimmon() {
  6719. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6720. const int64_t n_embd_head = hparams.n_embd_head_v;
  6721. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6722. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  6723. struct ggml_tensor * cur;
  6724. struct ggml_tensor * inpL;
  6725. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6726. // inp_pos - contains the positions
  6727. struct ggml_tensor * inp_pos = build_inp_pos();
  6728. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6729. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6730. for (int il = 0; il < n_layer; ++il) {
  6731. struct ggml_tensor * residual = inpL;
  6732. cur = llm_build_norm(ctx0, inpL, hparams,
  6733. model.layers[il].attn_norm,
  6734. model.layers[il].attn_norm_b,
  6735. LLM_NORM, cb, il);
  6736. cb(cur, "attn_norm", il);
  6737. // self attention
  6738. {
  6739. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6740. cb(cur, "wqkv", il);
  6741. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6742. cb(cur, "bqkv", il);
  6743. // split qkv
  6744. GGML_ASSERT(n_head_kv == n_head);
  6745. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  6746. cb(tmpqkv, "tmpqkv", il);
  6747. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  6748. cb(tmpqkv_perm, "tmpqkv", il);
  6749. struct ggml_tensor * tmpq = ggml_view_3d(
  6750. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6751. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6752. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6753. 0
  6754. );
  6755. cb(tmpq, "tmpq", il);
  6756. struct ggml_tensor * tmpk = ggml_view_3d(
  6757. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6758. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6759. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6760. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  6761. );
  6762. cb(tmpk, "tmpk", il);
  6763. // Q/K Layernorm
  6764. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  6765. model.layers[il].attn_q_norm,
  6766. model.layers[il].attn_q_norm_b,
  6767. LLM_NORM, cb, il);
  6768. cb(tmpq, "tmpq", il);
  6769. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  6770. model.layers[il].attn_k_norm,
  6771. model.layers[il].attn_k_norm_b,
  6772. LLM_NORM, cb, il);
  6773. cb(tmpk, "tmpk", il);
  6774. // RoPE the first n_rot of q/k, pass the other half, and concat.
  6775. struct ggml_tensor * qrot = ggml_view_3d(
  6776. ctx0, tmpq, n_rot, n_head, n_tokens,
  6777. ggml_element_size(tmpq) * n_embd_head,
  6778. ggml_element_size(tmpq) * n_embd_head * n_head,
  6779. 0
  6780. );
  6781. cb(qrot, "qrot", il);
  6782. struct ggml_tensor * krot = ggml_view_3d(
  6783. ctx0, tmpk, n_rot, n_head, n_tokens,
  6784. ggml_element_size(tmpk) * n_embd_head,
  6785. ggml_element_size(tmpk) * n_embd_head * n_head,
  6786. 0
  6787. );
  6788. cb(krot, "krot", il);
  6789. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  6790. struct ggml_tensor * qpass = ggml_view_3d(
  6791. ctx0, tmpq, n_rot, n_head, n_tokens,
  6792. ggml_element_size(tmpq) * n_embd_head,
  6793. ggml_element_size(tmpq) * n_embd_head * n_head,
  6794. ggml_element_size(tmpq) * n_rot
  6795. );
  6796. cb(qpass, "qpass", il);
  6797. struct ggml_tensor * kpass = ggml_view_3d(
  6798. ctx0, tmpk, n_rot, n_head, n_tokens,
  6799. ggml_element_size(tmpk) * n_embd_head,
  6800. ggml_element_size(tmpk) * n_embd_head * n_head,
  6801. ggml_element_size(tmpk) * n_rot
  6802. );
  6803. cb(kpass, "kpass", il);
  6804. struct ggml_tensor * qrotated = ggml_rope_custom(
  6805. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6806. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6807. );
  6808. cb(qrotated, "qrotated", il);
  6809. struct ggml_tensor * krotated = ggml_rope_custom(
  6810. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6811. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6812. );
  6813. cb(krotated, "krotated", il);
  6814. // ggml currently only supports concatenation on dim=2
  6815. // so we need to permute qrot, qpass, concat, then permute back.
  6816. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6817. cb(qrotated, "qrotated", il);
  6818. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6819. cb(krotated, "krotated", il);
  6820. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6821. cb(qpass, "qpass", il);
  6822. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6823. cb(kpass, "kpass", il);
  6824. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6825. cb(Qcur, "Qcur", il);
  6826. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6827. cb(Kcur, "Kcur", il);
  6828. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6829. cb(Q, "Q", il);
  6830. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6831. cb(Kcur, "Kcur", il);
  6832. struct ggml_tensor * Vcur = ggml_view_3d(
  6833. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6834. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6835. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6836. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6837. );
  6838. cb(Vcur, "Vcur", il);
  6839. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6840. model.layers[il].wo, model.layers[il].bo,
  6841. Kcur, Vcur, Q, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6842. }
  6843. if (il == n_layer - 1) {
  6844. // skip computing output for unused tokens
  6845. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6846. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6847. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6848. }
  6849. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6850. cb(ffn_inp, "ffn_inp", il);
  6851. // feed-forward network
  6852. {
  6853. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6854. model.layers[il].ffn_norm,
  6855. model.layers[il].ffn_norm_b,
  6856. LLM_NORM, cb, il);
  6857. cb(cur, "ffn_norm", il);
  6858. cur = llm_build_ffn(ctx0, cur,
  6859. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6860. NULL, NULL,
  6861. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6862. NULL,
  6863. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6864. cb(cur, "ffn_out", il);
  6865. }
  6866. cur = ggml_add(ctx0, cur, ffn_inp);
  6867. cb(cur, "l_out", il);
  6868. inpL = cur;
  6869. }
  6870. cur = inpL;
  6871. cur = llm_build_norm(ctx0, cur, hparams,
  6872. model.output_norm,
  6873. model.output_norm_b,
  6874. LLM_NORM, cb, -1);
  6875. cb(cur, "result_norm", -1);
  6876. cur = ggml_mul_mat(ctx0, model.output, cur);
  6877. cb(cur, "result_output", -1);
  6878. ggml_build_forward_expand(gf, cur);
  6879. return gf;
  6880. }
  6881. struct ggml_cgraph * build_refact() {
  6882. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6883. const int64_t n_embd_head = hparams.n_embd_head_v;
  6884. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6885. struct ggml_tensor * cur;
  6886. struct ggml_tensor * inpL;
  6887. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6888. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6889. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6890. for (int il = 0; il < n_layer; ++il) {
  6891. struct ggml_tensor * inpSA = inpL;
  6892. cur = llm_build_norm(ctx0, inpL, hparams,
  6893. model.layers[il].attn_norm, NULL,
  6894. LLM_NORM_RMS, cb, il);
  6895. cb(cur, "attn_norm", il);
  6896. // self-attention
  6897. {
  6898. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6899. cb(Qcur, "Qcur", il);
  6900. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6901. cb(Kcur, "Kcur", il);
  6902. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6903. cb(Vcur, "Vcur", il);
  6904. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6905. cb(Kcur, "Kcur", il);
  6906. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6907. cb(Qcur, "Qcur", il);
  6908. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  6909. model.layers[il].wo, NULL,
  6910. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6911. }
  6912. if (il == n_layer - 1) {
  6913. // skip computing output for unused tokens
  6914. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6915. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6916. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6917. }
  6918. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6919. cb(ffn_inp, "ffn_inp", il);
  6920. // feed-forward network
  6921. {
  6922. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6923. model.layers[il].ffn_norm, NULL,
  6924. LLM_NORM_RMS, cb, il);
  6925. cb(cur, "ffn_norm", il);
  6926. cur = llm_build_ffn(ctx0, cur,
  6927. model.layers[il].ffn_up, NULL,
  6928. model.layers[il].ffn_gate, NULL,
  6929. model.layers[il].ffn_down, NULL,
  6930. NULL,
  6931. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6932. cb(cur, "ffn_out", il);
  6933. }
  6934. cur = ggml_add(ctx0, cur, ffn_inp);
  6935. cb(cur, "l_out", il);
  6936. // input for next layer
  6937. inpL = cur;
  6938. }
  6939. cur = inpL;
  6940. cur = llm_build_norm(ctx0, cur, hparams,
  6941. model.output_norm, NULL,
  6942. LLM_NORM_RMS, cb, -1);
  6943. cb(cur, "result_norm", -1);
  6944. // lm_head
  6945. cur = ggml_mul_mat(ctx0, model.output, cur);
  6946. cb(cur, "result_output", -1);
  6947. ggml_build_forward_expand(gf, cur);
  6948. return gf;
  6949. }
  6950. struct ggml_cgraph * build_bert() {
  6951. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6952. const int64_t n_embd_head = hparams.n_embd_head_v;
  6953. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6954. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6955. struct ggml_tensor * cur;
  6956. struct ggml_tensor * inpL;
  6957. struct ggml_tensor * inp_pos = nullptr;
  6958. if (model.arch != LLM_ARCH_JINA_BERT_V2) {
  6959. inp_pos = build_inp_pos();
  6960. }
  6961. struct ggml_tensor * inp_mean = build_inp_mean();
  6962. struct ggml_tensor * inp_cls = build_inp_cls();
  6963. // construct input embeddings (token, type, position)
  6964. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6965. // token types are hardcoded to zero ("Sentence A")
  6966. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6967. inpL = ggml_add(ctx0, inpL, type_row0);
  6968. if (model.arch == LLM_ARCH_BERT) {
  6969. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6970. }
  6971. cb(inpL, "inp_embd", -1);
  6972. // embed layer norm
  6973. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6974. cb(inpL, "inp_norm", -1);
  6975. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6976. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6977. // iterate layers
  6978. for (int il = 0; il < n_layer; ++il) {
  6979. struct ggml_tensor * cur = inpL;
  6980. struct ggml_tensor * Qcur;
  6981. struct ggml_tensor * Kcur;
  6982. struct ggml_tensor * Vcur;
  6983. // self-attention
  6984. if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_JINA_BERT_V2) {
  6985. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6986. cb(Qcur, "Qcur", il);
  6987. if (model.layers[il].attn_q_norm) {
  6988. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  6989. model.layers[il].attn_q_norm,
  6990. model.layers[il].attn_q_norm_b,
  6991. LLM_NORM, cb, il);
  6992. }
  6993. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6994. cb(Kcur, "Kcur", il);
  6995. if (model.layers[il].attn_k_norm) {
  6996. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  6997. model.layers[il].attn_k_norm,
  6998. model.layers[il].attn_k_norm_b,
  6999. LLM_NORM, cb, il);
  7000. }
  7001. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  7002. cb(Vcur, "Vcur", il);
  7003. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7004. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7005. } else {
  7006. // compute Q and K and RoPE them
  7007. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7008. cb(cur, "wqkv", il);
  7009. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7010. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7011. 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)));
  7012. cb(Qcur, "Qcur", il);
  7013. cb(Kcur, "Kcur", il);
  7014. cb(Vcur, "Vcur", il);
  7015. Qcur = ggml_rope_custom(
  7016. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7017. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7018. ext_factor, attn_factor, beta_fast, beta_slow
  7019. );
  7020. cb(Qcur, "Qcur", il);
  7021. Kcur = ggml_rope_custom(
  7022. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7023. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7024. ext_factor, attn_factor, beta_fast, beta_slow
  7025. );
  7026. cb(Kcur, "Kcur", il);
  7027. }
  7028. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  7029. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  7030. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  7031. cb(kq, "kq", il);
  7032. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  7033. cb(kq, "kq_soft_max_ext", il);
  7034. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  7035. cb(v, "v", il);
  7036. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  7037. cb(kqv, "kqv", il);
  7038. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  7039. cb(kqv_merged, "kqv_merged", il);
  7040. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  7041. cb(cur, "kqv_merged_cont", il);
  7042. ggml_build_forward_expand(gf, cur);
  7043. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  7044. if (model.layers[il].bo) {
  7045. cb(cur, "kqv_wo", il);
  7046. }
  7047. if (model.layers[il].bo) {
  7048. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  7049. }
  7050. cb(cur, "kqv_out", il);
  7051. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  7052. // skip computing output for unused tokens
  7053. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7054. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7055. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7056. }
  7057. // re-add the layer input
  7058. cur = ggml_add(ctx0, cur, inpL);
  7059. // attention layer norm
  7060. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  7061. struct ggml_tensor * ffn_inp = cur;
  7062. cb(ffn_inp, "ffn_inp", il);
  7063. // feed-forward network
  7064. if (model.arch == LLM_ARCH_BERT) {
  7065. cur = llm_build_ffn(ctx0, cur,
  7066. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7067. NULL, NULL,
  7068. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7069. NULL,
  7070. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7071. } else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
  7072. cur = llm_build_ffn(ctx0, cur,
  7073. model.layers[il].ffn_up, NULL,
  7074. model.layers[il].ffn_gate, NULL,
  7075. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7076. NULL,
  7077. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7078. } else {
  7079. cur = llm_build_ffn(ctx0, cur,
  7080. model.layers[il].ffn_up, NULL,
  7081. model.layers[il].ffn_gate, NULL,
  7082. model.layers[il].ffn_down, NULL,
  7083. NULL,
  7084. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7085. }
  7086. cb(cur, "ffn_out", il);
  7087. // attentions bypass the intermediate layer
  7088. cur = ggml_add(ctx0, cur, ffn_inp);
  7089. // output layer norm
  7090. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  7091. // input for next layer
  7092. inpL = cur;
  7093. }
  7094. // final output
  7095. cur = inpL;
  7096. cb(cur, "result_embd", -1);
  7097. // pooling layer
  7098. switch (pooling_type) {
  7099. case LLAMA_POOLING_TYPE_NONE:
  7100. {
  7101. // nop
  7102. } break;
  7103. case LLAMA_POOLING_TYPE_MEAN:
  7104. {
  7105. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  7106. cb(cur, "result_embd_pooled", -1);
  7107. } break;
  7108. case LLAMA_POOLING_TYPE_CLS:
  7109. {
  7110. cur = ggml_get_rows(ctx0, cur, inp_cls);
  7111. cb(cur, "result_embd_pooled", -1);
  7112. } break;
  7113. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7114. {
  7115. GGML_ASSERT(false && "Invalid pooling type");
  7116. } break;
  7117. }
  7118. ggml_build_forward_expand(gf, cur);
  7119. return gf;
  7120. }
  7121. struct ggml_cgraph * build_bloom() {
  7122. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7123. const int64_t n_embd_head = hparams.n_embd_head_v;
  7124. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7125. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7126. struct ggml_tensor * cur;
  7127. struct ggml_tensor * inpL;
  7128. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7129. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7130. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7131. inpL = llm_build_norm(ctx0, inpL, hparams,
  7132. model.tok_norm,
  7133. model.tok_norm_b,
  7134. LLM_NORM, cb, -1);
  7135. cb(inpL, "inp_norm", -1);
  7136. for (int il = 0; il < n_layer; ++il) {
  7137. cur = llm_build_norm(ctx0, inpL, hparams,
  7138. model.layers[il].attn_norm,
  7139. model.layers[il].attn_norm_b,
  7140. LLM_NORM, cb, il);
  7141. cb(cur, "attn_norm", il);
  7142. // self-attention
  7143. {
  7144. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7145. cb(cur, "wqkv", il);
  7146. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7147. cb(cur, "bqkv", il);
  7148. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7149. 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)));
  7150. 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)));
  7151. cb(Qcur, "Qcur", il);
  7152. cb(Kcur, "Kcur", il);
  7153. cb(Vcur, "Vcur", il);
  7154. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7155. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7156. model.layers[il].wo, model.layers[il].bo,
  7157. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7158. }
  7159. if (il == n_layer - 1) {
  7160. // skip computing output for unused tokens
  7161. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7162. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7163. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7164. }
  7165. // Add the input
  7166. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7167. cb(ffn_inp, "ffn_inp", il);
  7168. // FF
  7169. {
  7170. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7171. model.layers[il].ffn_norm,
  7172. model.layers[il].ffn_norm_b,
  7173. LLM_NORM, cb, il);
  7174. cb(cur, "ffn_norm", il);
  7175. cur = llm_build_ffn(ctx0, cur,
  7176. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7177. NULL, NULL,
  7178. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7179. NULL,
  7180. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7181. cb(cur, "ffn_out", il);
  7182. }
  7183. inpL = ggml_add(ctx0, cur, ffn_inp);
  7184. cb(inpL, "l_out", il);
  7185. }
  7186. cur = llm_build_norm(ctx0, inpL, hparams,
  7187. model.output_norm,
  7188. model.output_norm_b,
  7189. LLM_NORM, cb, -1);
  7190. cb(cur, "result_norm", -1);
  7191. cur = ggml_mul_mat(ctx0, model.output, cur);
  7192. cb(cur, "result_output", -1);
  7193. ggml_build_forward_expand(gf, cur);
  7194. return gf;
  7195. }
  7196. struct ggml_cgraph * build_mpt() {
  7197. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7198. const int64_t n_embd_head = hparams.n_embd_head_v;
  7199. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7200. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7201. struct ggml_tensor * cur;
  7202. struct ggml_tensor * pos;
  7203. struct ggml_tensor * inpL;
  7204. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7205. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7206. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7207. if (model.pos_embd) {
  7208. // inp_pos - contains the positions
  7209. struct ggml_tensor * inp_pos = build_inp_pos();
  7210. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7211. cb(pos, "pos_embd", -1);
  7212. inpL = ggml_add(ctx0, inpL, pos);
  7213. cb(inpL, "inpL", -1);
  7214. }
  7215. for (int il = 0; il < n_layer; ++il) {
  7216. struct ggml_tensor * attn_norm;
  7217. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  7218. model.layers[il].attn_norm,
  7219. model.layers[il].attn_norm_b,
  7220. LLM_NORM, cb, il);
  7221. cb(attn_norm, "attn_norm", il);
  7222. // self-attention
  7223. {
  7224. cur = attn_norm;
  7225. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7226. cb(cur, "wqkv", il);
  7227. if (model.layers[il].bqkv){
  7228. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7229. cb(cur, "bqkv", il);
  7230. }
  7231. if (hparams.f_clamp_kqv > 0.0f) {
  7232. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  7233. cb(cur, "wqkv_clamped", il);
  7234. }
  7235. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7236. 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)));
  7237. 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)));
  7238. cb(Qcur, "Qcur", il);
  7239. cb(Kcur, "Kcur", il);
  7240. cb(Vcur, "Vcur", il);
  7241. // Q/K Layernorm
  7242. if (model.layers[il].attn_q_norm) {
  7243. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7244. model.layers[il].attn_q_norm,
  7245. model.layers[il].attn_q_norm_b,
  7246. LLM_NORM, cb, il);
  7247. cb(Qcur, "Qcur", il);
  7248. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7249. model.layers[il].attn_k_norm,
  7250. model.layers[il].attn_k_norm_b,
  7251. LLM_NORM, cb, il);
  7252. cb(Kcur, "Kcur", il);
  7253. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7254. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7255. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7256. model.layers[il].wo, model.layers[il].bo,
  7257. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7258. } else {
  7259. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7260. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7261. model.layers[il].wo, model.layers[il].bo,
  7262. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7263. }
  7264. }
  7265. if (il == n_layer - 1) {
  7266. // skip computing output for unused tokens
  7267. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7268. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7269. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7270. }
  7271. // Add the input
  7272. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7273. cb(ffn_inp, "ffn_inp", il);
  7274. // feed forward
  7275. {
  7276. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7277. model.layers[il].ffn_norm,
  7278. model.layers[il].ffn_norm_b,
  7279. LLM_NORM, cb, il);
  7280. cb(cur, "ffn_norm", il);
  7281. cur = llm_build_ffn(ctx0, cur,
  7282. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7283. NULL, NULL,
  7284. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7285. model.layers[il].ffn_act,
  7286. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7287. cb(cur, "ffn_out", il);
  7288. }
  7289. cur = ggml_add(ctx0, cur, ffn_inp);
  7290. cb(cur, "l_out", il);
  7291. // input for next layer
  7292. inpL = cur;
  7293. }
  7294. cur = inpL;
  7295. cur = llm_build_norm(ctx0, cur, hparams,
  7296. model.output_norm,
  7297. model.output_norm_b,
  7298. LLM_NORM, cb, -1);
  7299. cb(cur, "result_norm", -1);
  7300. cur = ggml_mul_mat(ctx0, model.output, cur);
  7301. cb(cur, "result_output", -1);
  7302. ggml_build_forward_expand(gf, cur);
  7303. return gf;
  7304. }
  7305. struct ggml_cgraph * build_stablelm() {
  7306. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  7307. const int64_t n_embd_head = hparams.n_embd_head_v;
  7308. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7309. struct ggml_tensor * cur;
  7310. struct ggml_tensor * inpL;
  7311. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7312. // inp_pos - contains the positions
  7313. struct ggml_tensor * inp_pos = build_inp_pos();
  7314. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7315. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7316. for (int il = 0; il < n_layer; ++il) {
  7317. // norm
  7318. cur = llm_build_norm(ctx0, inpL, hparams,
  7319. model.layers[il].attn_norm,
  7320. model.layers[il].attn_norm_b,
  7321. LLM_NORM, cb, il);
  7322. cb(cur, "attn_norm", il);
  7323. struct ggml_tensor * inpSA = cur;
  7324. // self-attention
  7325. {
  7326. // compute Q and K and RoPE them
  7327. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7328. cb(Qcur, "Qcur", il);
  7329. if (model.layers[il].bq) {
  7330. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7331. cb(Qcur, "Qcur", il);
  7332. }
  7333. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7334. cb(Kcur, "Kcur", il);
  7335. if (model.layers[il].bk) {
  7336. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7337. cb(Kcur, "Kcur", il);
  7338. }
  7339. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7340. cb(Vcur, "Vcur", il);
  7341. if (model.layers[il].bv) {
  7342. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7343. cb(Vcur, "Vcur", il);
  7344. }
  7345. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7346. cb(Qcur, "Qcur", il);
  7347. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7348. cb(Kcur, "Kcur", il);
  7349. if (model.layers[il].attn_q_norm) {
  7350. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7351. model.layers[il].attn_q_norm,
  7352. NULL,
  7353. LLM_NORM, cb, il);
  7354. cb(Qcur, "Qcur", il);
  7355. }
  7356. if (model.layers[il].attn_k_norm) {
  7357. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7358. model.layers[il].attn_k_norm,
  7359. NULL,
  7360. LLM_NORM, cb, il);
  7361. cb(Kcur, "Kcur", il);
  7362. }
  7363. Qcur = ggml_rope_custom(
  7364. ctx0, Qcur, inp_pos,
  7365. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7366. ext_factor, attn_factor, beta_fast, beta_slow
  7367. );
  7368. cb(Qcur, "Qcur", il);
  7369. Kcur = ggml_rope_custom(
  7370. ctx0, Kcur, inp_pos,
  7371. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7372. ext_factor, attn_factor, beta_fast, beta_slow
  7373. );
  7374. cb(Kcur, "Kcur", il);
  7375. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7376. model.layers[il].wo, NULL,
  7377. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7378. }
  7379. if (il == n_layer - 1) {
  7380. // skip computing output for unused tokens
  7381. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7382. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7383. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7384. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7385. }
  7386. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7387. cb(ffn_inp, "ffn_inp", il);
  7388. // feed-forward network
  7389. {
  7390. if (model.layers[il].ffn_norm) {
  7391. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7392. model.layers[il].ffn_norm,
  7393. model.layers[il].ffn_norm_b,
  7394. LLM_NORM, cb, il);
  7395. cb(cur, "ffn_norm", il);
  7396. } else {
  7397. // parallel residual
  7398. cur = inpSA;
  7399. }
  7400. cur = llm_build_ffn(ctx0, cur,
  7401. model.layers[il].ffn_up, NULL,
  7402. model.layers[il].ffn_gate, NULL,
  7403. model.layers[il].ffn_down, NULL,
  7404. NULL,
  7405. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7406. cb(cur, "ffn_out", il);
  7407. }
  7408. cur = ggml_add(ctx0, cur, ffn_inp);
  7409. cb(cur, "l_out", il);
  7410. // input for next layer
  7411. inpL = cur;
  7412. }
  7413. cur = inpL;
  7414. cur = llm_build_norm(ctx0, cur, hparams,
  7415. model.output_norm,
  7416. model.output_norm_b,
  7417. LLM_NORM, cb, -1);
  7418. cb(cur, "result_norm", -1);
  7419. // lm_head
  7420. cur = ggml_mul_mat(ctx0, model.output, cur);
  7421. cb(cur, "result_output", -1);
  7422. ggml_build_forward_expand(gf, cur);
  7423. return gf;
  7424. }
  7425. struct ggml_cgraph * build_qwen() {
  7426. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7427. const int64_t n_embd_head = hparams.n_embd_head_v;
  7428. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7429. struct ggml_tensor * cur;
  7430. struct ggml_tensor * inpL;
  7431. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7432. // inp_pos - contains the positions
  7433. struct ggml_tensor * inp_pos = build_inp_pos();
  7434. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7435. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7436. for (int il = 0; il < n_layer; ++il) {
  7437. struct ggml_tensor * inpSA = inpL;
  7438. cur = llm_build_norm(ctx0, inpL, hparams,
  7439. model.layers[il].attn_norm, NULL,
  7440. LLM_NORM_RMS, cb, il);
  7441. cb(cur, "attn_norm", il);
  7442. // self-attention
  7443. {
  7444. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7445. cb(cur, "wqkv", il);
  7446. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7447. cb(cur, "bqkv", il);
  7448. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7449. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7450. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  7451. cb(Qcur, "Qcur", il);
  7452. cb(Kcur, "Kcur", il);
  7453. cb(Vcur, "Vcur", il);
  7454. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7455. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7456. // using mode = 2 for neox mode
  7457. Qcur = ggml_rope_custom(
  7458. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7459. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7460. );
  7461. cb(Qcur, "Qcur", il);
  7462. Kcur = ggml_rope_custom(
  7463. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7464. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7465. );
  7466. cb(Kcur, "Kcur", il);
  7467. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7468. model.layers[il].wo, NULL,
  7469. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7470. }
  7471. if (il == n_layer - 1) {
  7472. // skip computing output for unused tokens
  7473. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7474. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7475. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7476. }
  7477. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7478. cb(ffn_inp, "ffn_inp", il);
  7479. // feed-forward forward
  7480. {
  7481. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7482. model.layers[il].ffn_norm, NULL,
  7483. LLM_NORM_RMS, cb, il);
  7484. cb(cur, "ffn_norm", il);
  7485. cur = llm_build_ffn(ctx0, cur,
  7486. model.layers[il].ffn_up, NULL,
  7487. model.layers[il].ffn_gate, NULL,
  7488. model.layers[il].ffn_down, NULL,
  7489. NULL,
  7490. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7491. cb(cur, "ffn_out", il);
  7492. }
  7493. cur = ggml_add(ctx0, cur, ffn_inp);
  7494. cb(cur, "l_out", il);
  7495. // input for next layer
  7496. inpL = cur;
  7497. }
  7498. cur = inpL;
  7499. cur = llm_build_norm(ctx0, cur, hparams,
  7500. model.output_norm, NULL,
  7501. LLM_NORM_RMS, cb, -1);
  7502. cb(cur, "result_norm", -1);
  7503. // lm_head
  7504. cur = ggml_mul_mat(ctx0, model.output, cur);
  7505. cb(cur, "result_output", -1);
  7506. ggml_build_forward_expand(gf, cur);
  7507. return gf;
  7508. }
  7509. struct ggml_cgraph * build_qwen2() {
  7510. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7511. const int64_t n_embd_head = hparams.n_embd_head_v;
  7512. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7513. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7514. struct ggml_tensor * cur;
  7515. struct ggml_tensor * inpL;
  7516. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7517. // inp_pos - contains the positions
  7518. struct ggml_tensor * inp_pos = build_inp_pos();
  7519. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7520. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7521. for (int il = 0; il < n_layer; ++il) {
  7522. struct ggml_tensor * inpSA = inpL;
  7523. // norm
  7524. cur = llm_build_norm(ctx0, inpL, hparams,
  7525. model.layers[il].attn_norm, NULL,
  7526. LLM_NORM_RMS, cb, il);
  7527. cb(cur, "attn_norm", il);
  7528. // self-attention
  7529. {
  7530. // compute Q and K and RoPE them
  7531. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7532. cb(Qcur, "Qcur", il);
  7533. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7534. cb(Qcur, "Qcur", il);
  7535. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7536. cb(Kcur, "Kcur", il);
  7537. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7538. cb(Kcur, "Kcur", il);
  7539. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7540. cb(Vcur, "Vcur", il);
  7541. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7542. cb(Vcur, "Vcur", il);
  7543. Qcur = ggml_rope_custom(
  7544. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7545. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7546. ext_factor, attn_factor, beta_fast, beta_slow
  7547. );
  7548. cb(Qcur, "Qcur", il);
  7549. Kcur = ggml_rope_custom(
  7550. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7551. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7552. ext_factor, attn_factor, beta_fast, beta_slow
  7553. );
  7554. cb(Kcur, "Kcur", il);
  7555. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7556. model.layers[il].wo, model.layers[il].bo,
  7557. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7558. }
  7559. if (il == n_layer - 1) {
  7560. // skip computing output for unused tokens
  7561. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7562. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7563. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7564. }
  7565. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7566. cb(ffn_inp, "ffn_inp", il);
  7567. // feed-forward network
  7568. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7569. model.layers[il].ffn_norm, NULL,
  7570. LLM_NORM_RMS, cb, il);
  7571. cb(cur, "ffn_norm", il);
  7572. cur = llm_build_ffn(ctx0, cur,
  7573. model.layers[il].ffn_up, NULL,
  7574. model.layers[il].ffn_gate, NULL,
  7575. model.layers[il].ffn_down, NULL,
  7576. NULL,
  7577. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7578. cb(cur, "ffn_out", il);
  7579. cur = ggml_add(ctx0, cur, ffn_inp);
  7580. cb(cur, "l_out", il);
  7581. // input for next layer
  7582. inpL = cur;
  7583. }
  7584. cur = inpL;
  7585. cur = llm_build_norm(ctx0, cur, hparams,
  7586. model.output_norm, NULL,
  7587. LLM_NORM_RMS, cb, -1);
  7588. cb(cur, "result_norm", -1);
  7589. // lm_head
  7590. cur = ggml_mul_mat(ctx0, model.output, cur);
  7591. cb(cur, "result_output", -1);
  7592. ggml_build_forward_expand(gf, cur);
  7593. return gf;
  7594. }
  7595. struct ggml_cgraph * build_qwen2moe() {
  7596. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7597. // mutable variable, needed during the last layer of the computation to skip unused tokens
  7598. int32_t n_tokens = this->n_tokens;
  7599. const int64_t n_embd_head = hparams.n_embd_head_v;
  7600. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7601. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7602. struct ggml_tensor * cur;
  7603. struct ggml_tensor * inpL;
  7604. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7605. // inp_pos - contains the positions
  7606. struct ggml_tensor * inp_pos = build_inp_pos();
  7607. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7608. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7609. for (int il = 0; il < n_layer; ++il) {
  7610. struct ggml_tensor * inpSA = inpL;
  7611. // norm
  7612. cur = llm_build_norm(ctx0, inpL, hparams,
  7613. model.layers[il].attn_norm, NULL,
  7614. LLM_NORM_RMS, cb, il);
  7615. cb(cur, "attn_norm", il);
  7616. // self_attention
  7617. {
  7618. // compute Q and K and RoPE them
  7619. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7620. cb(Qcur, "Qcur", il);
  7621. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7622. cb(Qcur, "Qcur", il);
  7623. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7624. cb(Kcur, "Kcur", il);
  7625. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7626. cb(Kcur, "Kcur", il);
  7627. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7628. cb(Vcur, "Vcur", il);
  7629. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7630. cb(Vcur, "Vcur", il);
  7631. Qcur = ggml_rope_custom(
  7632. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7633. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7634. ext_factor, attn_factor, beta_fast, beta_slow
  7635. );
  7636. cb(Qcur, "Qcur", il);
  7637. Kcur = ggml_rope_custom(
  7638. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7639. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7640. ext_factor, attn_factor, beta_fast, beta_slow
  7641. );
  7642. cb(Kcur, "Kcur", il);
  7643. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7644. model.layers[il].wo, model.layers[il].bo,
  7645. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7646. }
  7647. if (il == n_layer - 1) {
  7648. // skip computing output for unused tokens
  7649. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7650. n_tokens = n_outputs;
  7651. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7652. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7653. }
  7654. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7655. cb(ffn_inp, "ffn_inp", il);
  7656. // MoE branch
  7657. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7658. model.layers[il].ffn_norm, NULL,
  7659. LLM_NORM_RMS, cb, il);
  7660. cb(cur, "ffn_norm", il);
  7661. ggml_tensor * moe_out =
  7662. llm_build_moe_ffn(ctx0, cur,
  7663. model.layers[il].ffn_gate_inp,
  7664. model.layers[il].ffn_up_exps,
  7665. model.layers[il].ffn_gate_exps,
  7666. model.layers[il].ffn_down_exps,
  7667. n_expert, n_expert_used,
  7668. LLM_FFN_SILU, false,
  7669. cb, il);
  7670. cb(cur, "ffn_moe_out", il);
  7671. // FFN shared expert
  7672. {
  7673. ggml_tensor * cur_gate_inp = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp_shexp, cur);
  7674. cb(cur_gate_inp, "ffn_shexp_gate_inp", il);
  7675. // sigmoid
  7676. ggml_tensor * cur_gate = ggml_div(ctx0, ggml_silu(ctx0, cur_gate_inp), cur_gate_inp);
  7677. cb(cur_gate, "ffn_shexp_gate", il);
  7678. ggml_tensor * cur_ffn = llm_build_ffn(ctx0, cur,
  7679. model.layers[il].ffn_up_shexp, NULL,
  7680. model.layers[il].ffn_gate_shexp, NULL,
  7681. model.layers[il].ffn_down_shexp, NULL,
  7682. NULL,
  7683. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7684. cb(cur_ffn, "ffn_shexp", il);
  7685. ggml_tensor * ffn_shexp_out = ggml_mul(ctx0, cur_ffn, cur_gate);
  7686. cb(ffn_shexp_out, "ffn_shexp_out", il);
  7687. moe_out = ggml_add(ctx0, moe_out, ffn_shexp_out);
  7688. cb(moe_out, "ffn_out", il);
  7689. cur = moe_out;
  7690. }
  7691. cur = ggml_add(ctx0, cur, ffn_inp);
  7692. cb(cur, "l_out", il);
  7693. // input for next layer
  7694. inpL = cur;
  7695. }
  7696. cur = inpL;
  7697. cur = llm_build_norm(ctx0, cur, hparams,
  7698. model.output_norm, NULL,
  7699. LLM_NORM_RMS, cb, -1);
  7700. cb(cur, "result_norm", -1);
  7701. // lm_head
  7702. cur = ggml_mul_mat(ctx0, model.output, cur);
  7703. cb(cur, "result_output", -1);
  7704. ggml_build_forward_expand(gf, cur);
  7705. return gf;
  7706. }
  7707. struct ggml_cgraph * build_phi2() {
  7708. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7709. const int64_t n_embd_head = hparams.n_embd_head_v;
  7710. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7711. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7712. struct ggml_tensor * cur;
  7713. struct ggml_tensor * attn_norm_output;
  7714. struct ggml_tensor * ffn_output;
  7715. struct ggml_tensor * inpL;
  7716. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7717. // inp_pos - contains the positions
  7718. struct ggml_tensor * inp_pos = build_inp_pos();
  7719. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7720. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7721. for (int il = 0; il < n_layer; ++il) {
  7722. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  7723. model.layers[il].attn_norm,
  7724. model.layers[il].attn_norm_b,
  7725. LLM_NORM, cb, il);
  7726. cb(attn_norm_output, "attn_norm", il);
  7727. // self-attention
  7728. {
  7729. struct ggml_tensor * Qcur = nullptr;
  7730. struct ggml_tensor * Kcur = nullptr;
  7731. struct ggml_tensor * Vcur = nullptr;
  7732. if (model.layers[il].wqkv) {
  7733. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  7734. cb(cur, "wqkv", il);
  7735. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7736. cb(cur, "bqkv", il);
  7737. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7738. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7739. 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)));
  7740. } else {
  7741. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  7742. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  7743. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  7744. }
  7745. cb(Qcur, "Qcur", il);
  7746. cb(Kcur, "Kcur", il);
  7747. cb(Vcur, "Vcur", il);
  7748. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7749. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7750. Qcur = ggml_rope_custom(
  7751. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7752. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7753. );
  7754. cb(Qcur, "Qcur", il);
  7755. // with phi2, we scale the Q to avoid precision issues
  7756. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  7757. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  7758. cb(Qcur, "Qcur", il);
  7759. Kcur = ggml_rope_custom(
  7760. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7761. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7762. );
  7763. cb(Kcur, "Kcur", il);
  7764. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7765. model.layers[il].wo, model.layers[il].bo,
  7766. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7767. }
  7768. if (il == n_layer - 1) {
  7769. // skip computing output for unused tokens
  7770. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7771. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7772. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7773. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  7774. }
  7775. // FF
  7776. {
  7777. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  7778. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7779. NULL, NULL,
  7780. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7781. NULL,
  7782. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7783. cb(ffn_output, "ffn_out", il);
  7784. }
  7785. cur = ggml_add(ctx0, cur, ffn_output);
  7786. cb(cur, "l_out", il);
  7787. cur = ggml_add(ctx0, cur, inpL);
  7788. cb(cur, "l_out", il);
  7789. inpL = cur;
  7790. }
  7791. cur = llm_build_norm(ctx0, inpL, hparams,
  7792. model.output_norm,
  7793. model.output_norm_b,
  7794. LLM_NORM, cb, -1);
  7795. cb(cur, "result_norm", -1);
  7796. cur = ggml_mul_mat(ctx0, model.output, cur);
  7797. cb(cur, "result_output_no_bias", -1);
  7798. cur = ggml_add(ctx0, cur, model.output_b);
  7799. cb(cur, "result_output", -1);
  7800. ggml_build_forward_expand(gf, cur);
  7801. return gf;
  7802. }
  7803. struct ggml_cgraph * build_phi3() {
  7804. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7805. const int64_t n_embd_head = hparams.n_embd_head_v;
  7806. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7807. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7808. struct ggml_tensor * cur;
  7809. struct ggml_tensor * inpL;
  7810. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7811. // inp_pos - contains the positions
  7812. struct ggml_tensor * inp_pos = build_inp_pos();
  7813. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7814. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7815. for (int il = 0; il < n_layer; ++il) {
  7816. auto residual = inpL;
  7817. // self-attention
  7818. {
  7819. struct ggml_tensor* attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  7820. model.layers[il].attn_norm,
  7821. NULL,
  7822. LLM_NORM_RMS, cb, il);
  7823. cb(attn_norm_output, "attn_norm", il);
  7824. struct ggml_tensor * Qcur = nullptr;
  7825. struct ggml_tensor * Kcur = nullptr;
  7826. struct ggml_tensor * Vcur = nullptr;
  7827. if (model.layers[il].wqkv) {
  7828. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  7829. cb(cur, "wqkv", il);
  7830. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0 * sizeof(float) * (n_embd)));
  7831. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1 * sizeof(float) * (n_embd)));
  7832. 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)));
  7833. }
  7834. else {
  7835. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  7836. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  7837. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  7838. }
  7839. cb(Qcur, "Qcur", il);
  7840. cb(Kcur, "Kcur", il);
  7841. cb(Vcur, "Vcur", il);
  7842. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7843. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7844. Qcur = ggml_rope_custom(
  7845. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7846. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7847. );
  7848. cb(Qcur, "Qcur", il);
  7849. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head)));
  7850. cb(Qcur, "Qcur", il);
  7851. Kcur = ggml_rope_custom(
  7852. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7853. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7854. );
  7855. cb(Kcur, "Kcur", il);
  7856. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7857. model.layers[il].wo, model.layers[il].bo,
  7858. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7859. }
  7860. if (il == n_layer - 1) {
  7861. // skip computing output for unused tokens
  7862. struct ggml_tensor* inp_out_ids = build_inp_out_ids();
  7863. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7864. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  7865. }
  7866. cur = ggml_add(ctx0, cur, residual);
  7867. residual = cur;
  7868. cur = llm_build_norm(ctx0, cur, hparams,
  7869. model.layers[il].ffn_norm, NULL,
  7870. LLM_NORM_RMS, cb, il);
  7871. cb(cur, "ffn_norm", il);
  7872. // FF
  7873. // special-case: the up and gate tensors are merged into a single tensor
  7874. // TOOD: support into llm_build_ffn
  7875. {
  7876. struct ggml_tensor* up = ggml_mul_mat(ctx0, model.layers[il].ffn_up, cur);
  7877. cb(up, "ffn_up", il);
  7878. 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));
  7879. 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));
  7880. y = ggml_mul(ctx0, y, ggml_silu(ctx0, g));
  7881. cb(y, "ffn_gate", il);
  7882. auto down = ggml_mul_mat(ctx0, model.layers[il].ffn_down, y);
  7883. cb(down, "ffn_down", il);
  7884. cur = down;
  7885. cb(cur, "ffn_out", il);
  7886. }
  7887. cur = ggml_add(ctx0, residual, cur);
  7888. cb(cur, "l_out", il);
  7889. inpL = cur;
  7890. }
  7891. cur = llm_build_norm(ctx0, inpL, hparams,
  7892. model.output_norm,
  7893. NULL,
  7894. LLM_NORM_RMS, cb, -1);
  7895. cb(cur, "result_norm", -1);
  7896. cur = ggml_mul_mat(ctx0, model.output, cur);
  7897. cb(cur, "result_output", -1);
  7898. ggml_build_forward_expand(gf, cur);
  7899. return gf;
  7900. }
  7901. struct ggml_cgraph * build_plamo() {
  7902. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  7903. const int64_t n_embd_head = hparams.n_embd_head_v;
  7904. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7905. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7906. struct ggml_tensor * cur;
  7907. struct ggml_tensor * inpL;
  7908. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7909. // inp_pos - contains the positions
  7910. struct ggml_tensor * inp_pos = build_inp_pos();
  7911. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7912. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7913. for (int il = 0; il < n_layer; ++il) {
  7914. // norm
  7915. cur = llm_build_norm(ctx0, inpL, hparams,
  7916. model.layers[il].attn_norm, NULL,
  7917. LLM_NORM_RMS, cb, il);
  7918. cb(cur, "attn_norm", il);
  7919. struct ggml_tensor * attention_norm = cur;
  7920. // self-attention
  7921. {
  7922. // compute Q and K and RoPE them
  7923. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7924. cb(Qcur, "Qcur", il);
  7925. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7926. cb(Kcur, "Kcur", il);
  7927. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7928. cb(Vcur, "Vcur", il);
  7929. Qcur = ggml_rope_custom(
  7930. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  7931. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7932. ext_factor, attn_factor, beta_fast, beta_slow);
  7933. cb(Qcur, "Qcur", il);
  7934. Kcur = ggml_rope_custom(
  7935. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  7936. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7937. ext_factor, attn_factor, beta_fast, beta_slow);
  7938. cb(Kcur, "Kcur", il);
  7939. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  7940. model.layers[il].wo, NULL,
  7941. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7942. }
  7943. struct ggml_tensor * sa_out = cur;
  7944. cur = attention_norm;
  7945. if (il == n_layer - 1) {
  7946. // skip computing output for unused tokens
  7947. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7948. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7949. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  7950. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7951. }
  7952. // feed-forward network
  7953. {
  7954. cur = llm_build_ffn(ctx0, cur,
  7955. model.layers[il].ffn_up, NULL,
  7956. model.layers[il].ffn_gate, NULL,
  7957. model.layers[il].ffn_down, NULL,
  7958. NULL,
  7959. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7960. cb(cur, "ffn_out", il);
  7961. }
  7962. cur = ggml_add(ctx0, cur, sa_out);
  7963. cb(cur, "l_out", il);
  7964. cur = ggml_add(ctx0, cur, inpL);
  7965. cb(cur, "l_out", il);
  7966. // input for next layer
  7967. inpL = cur;
  7968. }
  7969. cur = inpL;
  7970. cur = llm_build_norm(ctx0, cur, hparams,
  7971. model.output_norm, NULL,
  7972. LLM_NORM_RMS, cb, -1);
  7973. cb(cur, "result_norm", -1);
  7974. // lm_head
  7975. cur = ggml_mul_mat(ctx0, model.output, cur);
  7976. cb(cur, "result_output", -1);
  7977. ggml_build_forward_expand(gf, cur);
  7978. return gf;
  7979. }
  7980. struct ggml_cgraph * build_gpt2() {
  7981. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7982. const int64_t n_embd_head = hparams.n_embd_head_v;
  7983. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7984. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7985. struct ggml_tensor * cur;
  7986. struct ggml_tensor * pos;
  7987. struct ggml_tensor * inpL;
  7988. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7989. // inp_pos - contains the positions
  7990. struct ggml_tensor * inp_pos = build_inp_pos();
  7991. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7992. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7993. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7994. cb(pos, "pos_embd", -1);
  7995. inpL = ggml_add(ctx0, inpL, pos);
  7996. cb(inpL, "inpL", -1);
  7997. for (int il = 0; il < n_layer; ++il) {
  7998. cur = llm_build_norm(ctx0, inpL, hparams,
  7999. model.layers[il].attn_norm,
  8000. model.layers[il].attn_norm_b,
  8001. LLM_NORM, cb, il);
  8002. cb(cur, "attn_norm", il);
  8003. // self-attention
  8004. {
  8005. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  8006. cb(cur, "wqkv", il);
  8007. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8008. cb(cur, "bqkv", il);
  8009. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8010. 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)));
  8011. 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)));
  8012. cb(Qcur, "Qcur", il);
  8013. cb(Kcur, "Kcur", il);
  8014. cb(Vcur, "Vcur", il);
  8015. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  8016. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8017. model.layers[il].wo, model.layers[il].bo,
  8018. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8019. }
  8020. if (il == n_layer - 1) {
  8021. // skip computing output for unused tokens
  8022. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8023. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8024. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8025. }
  8026. // add the input
  8027. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8028. cb(ffn_inp, "ffn_inp", il);
  8029. // FF
  8030. {
  8031. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8032. model.layers[il].ffn_norm,
  8033. model.layers[il].ffn_norm_b,
  8034. LLM_NORM, cb, il);
  8035. cb(cur, "ffn_norm", il);
  8036. cur = llm_build_ffn(ctx0, cur,
  8037. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8038. NULL, NULL,
  8039. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8040. NULL,
  8041. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8042. cb(cur, "ffn_out", il);
  8043. }
  8044. inpL = ggml_add(ctx0, cur, ffn_inp);
  8045. cb(inpL, "l_out", il);
  8046. }
  8047. cur = llm_build_norm(ctx0, inpL, hparams,
  8048. model.output_norm,
  8049. model.output_norm_b,
  8050. LLM_NORM, cb, -1);
  8051. cb(cur, "result_norm", -1);
  8052. cur = ggml_mul_mat(ctx0, model.output, cur);
  8053. cb(cur, "result_output", -1);
  8054. ggml_build_forward_expand(gf, cur);
  8055. return gf;
  8056. }
  8057. struct ggml_cgraph * build_codeshell() {
  8058. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8059. const int64_t n_embd_head = hparams.n_embd_head_v;
  8060. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  8061. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8062. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8063. struct ggml_tensor * cur;
  8064. struct ggml_tensor * inpL;
  8065. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8066. // inp_pos - contains the positions
  8067. struct ggml_tensor * inp_pos = build_inp_pos();
  8068. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8069. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8070. for (int il = 0; il < n_layer; ++il) {
  8071. cur = llm_build_norm(ctx0, inpL, hparams,
  8072. model.layers[il].attn_norm,
  8073. model.layers[il].attn_norm_b,
  8074. LLM_NORM, cb, il);
  8075. cb(cur, "attn_norm", il);
  8076. // self-attention
  8077. {
  8078. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  8079. cb(cur, "wqkv", il);
  8080. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  8081. cb(cur, "bqkv", il);
  8082. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  8083. 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)));
  8084. 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)));
  8085. cb(tmpq, "tmpq", il);
  8086. cb(tmpk, "tmpk", il);
  8087. cb(Vcur, "Vcur", il);
  8088. struct ggml_tensor * Qcur = ggml_rope_custom(
  8089. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  8090. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8091. ext_factor, attn_factor, beta_fast, beta_slow
  8092. );
  8093. cb(Qcur, "Qcur", il);
  8094. struct ggml_tensor * Kcur = ggml_rope_custom(
  8095. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8096. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8097. ext_factor, attn_factor, beta_fast, beta_slow
  8098. );
  8099. cb(Kcur, "Kcur", il);
  8100. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8101. model.layers[il].wo, model.layers[il].bo,
  8102. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8103. }
  8104. if (il == n_layer - 1) {
  8105. // skip computing output for unused tokens
  8106. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8107. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8108. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8109. }
  8110. // add the input
  8111. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  8112. cb(ffn_inp, "ffn_inp", il);
  8113. // FF
  8114. {
  8115. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8116. model.layers[il].ffn_norm,
  8117. model.layers[il].ffn_norm_b,
  8118. LLM_NORM, cb, il);
  8119. cb(cur, "ffn_norm", il);
  8120. cur = llm_build_ffn(ctx0, cur,
  8121. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8122. NULL, NULL,
  8123. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8124. NULL,
  8125. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8126. cb(cur, "ffn_out", il);
  8127. }
  8128. inpL = ggml_add(ctx0, cur, ffn_inp);
  8129. cb(inpL, "l_out", il);
  8130. }
  8131. cur = llm_build_norm(ctx0, inpL, hparams,
  8132. model.output_norm,
  8133. model.output_norm_b,
  8134. LLM_NORM, cb, -1);
  8135. cb(cur, "result_norm", -1);
  8136. cur = ggml_mul_mat(ctx0, model.output, cur);
  8137. cb(cur, "result_output", -1);
  8138. ggml_build_forward_expand(gf, cur);
  8139. return gf;
  8140. }
  8141. struct ggml_cgraph * build_orion() {
  8142. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8143. const int64_t n_embd_head = hparams.n_embd_head_v;
  8144. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8145. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8146. struct ggml_tensor * cur;
  8147. struct ggml_tensor * inpL;
  8148. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8149. // inp_pos - contains the positions
  8150. struct ggml_tensor * inp_pos = build_inp_pos();
  8151. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8152. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8153. for (int il = 0; il < n_layer; ++il) {
  8154. struct ggml_tensor * inpSA = inpL;
  8155. // norm
  8156. cur = llm_build_norm(ctx0, inpL, hparams,
  8157. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  8158. LLM_NORM, cb, il);
  8159. cb(cur, "attn_norm", il);
  8160. // self-attention
  8161. {
  8162. // compute Q and K and RoPE them
  8163. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8164. cb(Qcur, "Qcur", il);
  8165. // if (model.layers[il].bq) {
  8166. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8167. // cb(Qcur, "Qcur", il);
  8168. // }
  8169. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8170. cb(Kcur, "Kcur", il);
  8171. // if (model.layers[il].bk) {
  8172. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8173. // cb(Kcur, "Kcur", il);
  8174. // }
  8175. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8176. cb(Vcur, "Vcur", il);
  8177. // if (model.layers[il].bv) {
  8178. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8179. // cb(Vcur, "Vcur", il);
  8180. // }
  8181. Qcur = ggml_rope_custom(
  8182. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8183. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8184. ext_factor, attn_factor, beta_fast, beta_slow
  8185. );
  8186. cb(Qcur, "Qcur", il);
  8187. Kcur = ggml_rope_custom(
  8188. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8189. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8190. ext_factor, attn_factor, beta_fast, beta_slow
  8191. );
  8192. cb(Kcur, "Kcur", il);
  8193. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8194. model.layers[il].wo, NULL,
  8195. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8196. }
  8197. if (il == n_layer - 1) {
  8198. // skip computing output for unused tokens
  8199. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8200. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8201. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8202. }
  8203. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8204. cb(ffn_inp, "ffn_inp", il);
  8205. // feed-forward network
  8206. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8207. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  8208. LLM_NORM, cb, il);
  8209. cb(cur, "ffn_norm", il);
  8210. cur = llm_build_ffn(ctx0, cur,
  8211. model.layers[il].ffn_up, NULL,
  8212. model.layers[il].ffn_gate, NULL,
  8213. model.layers[il].ffn_down, NULL,
  8214. NULL,
  8215. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8216. cb(cur, "ffn_out", il);
  8217. cur = ggml_add(ctx0, cur, ffn_inp);
  8218. cb(cur, "l_out", il);
  8219. // input for next layer
  8220. inpL = cur;
  8221. }
  8222. cur = inpL;
  8223. cur = llm_build_norm(ctx0, cur, hparams,
  8224. model.output_norm, model.output_norm_b,
  8225. LLM_NORM, cb, -1);
  8226. cb(cur, "result_norm", -1);
  8227. // lm_head
  8228. cur = ggml_mul_mat(ctx0, model.output, cur);
  8229. cb(cur, "result_output", -1);
  8230. ggml_build_forward_expand(gf, cur);
  8231. return gf;
  8232. }
  8233. struct ggml_cgraph * build_internlm2() {
  8234. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8235. const int64_t n_embd_head = hparams.n_embd_head_v;
  8236. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8237. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8238. struct ggml_tensor * cur;
  8239. struct ggml_tensor * inpL;
  8240. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8241. // inp_pos - contains the positions
  8242. struct ggml_tensor * inp_pos = build_inp_pos();
  8243. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8244. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8245. for (int il = 0; il < n_layer; ++il) {
  8246. struct ggml_tensor * inpSA = inpL;
  8247. // norm
  8248. cur = llm_build_norm(ctx0, inpL, hparams,
  8249. model.layers[il].attn_norm, NULL,
  8250. LLM_NORM_RMS, cb, il);
  8251. cb(cur, "attn_norm", il);
  8252. // self-attention
  8253. {
  8254. // compute Q and K and RoPE them
  8255. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8256. cb(Qcur, "Qcur", il);
  8257. if (model.layers[il].bq) {
  8258. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8259. cb(Qcur, "Qcur", il);
  8260. }
  8261. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8262. cb(Kcur, "Kcur", il);
  8263. if (model.layers[il].bk) {
  8264. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8265. cb(Kcur, "Kcur", il);
  8266. }
  8267. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8268. cb(Vcur, "Vcur", il);
  8269. if (model.layers[il].bv) {
  8270. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8271. cb(Vcur, "Vcur", il);
  8272. }
  8273. Qcur = ggml_rope_custom(
  8274. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8275. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8276. ext_factor, attn_factor, beta_fast, beta_slow
  8277. );
  8278. cb(Qcur, "Qcur", il);
  8279. Kcur = ggml_rope_custom(
  8280. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8281. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8282. ext_factor, attn_factor, beta_fast, beta_slow
  8283. );
  8284. cb(Kcur, "Kcur", il);
  8285. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8286. model.layers[il].wo, model.layers[il].bo,
  8287. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8288. }
  8289. if (il == n_layer - 1) {
  8290. // skip computing output for unused tokens
  8291. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8292. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8293. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8294. }
  8295. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8296. cb(ffn_inp, "ffn_inp", il);
  8297. // feed-forward network
  8298. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8299. model.layers[il].ffn_norm, NULL,
  8300. LLM_NORM_RMS, cb, il);
  8301. cb(cur, "ffn_norm", il);
  8302. cur = llm_build_ffn(ctx0, cur,
  8303. model.layers[il].ffn_up, NULL,
  8304. model.layers[il].ffn_gate, NULL,
  8305. model.layers[il].ffn_down, NULL,
  8306. NULL,
  8307. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8308. cb(cur, "ffn_out", il);
  8309. cur = ggml_add(ctx0, cur, ffn_inp);
  8310. cb(cur, "l_out", il);
  8311. // input for next layer
  8312. inpL = cur;
  8313. }
  8314. cur = inpL;
  8315. cur = llm_build_norm(ctx0, cur, hparams,
  8316. model.output_norm, NULL,
  8317. LLM_NORM_RMS, cb, -1);
  8318. cb(cur, "result_norm", -1);
  8319. // lm_head
  8320. cur = ggml_mul_mat(ctx0, model.output, cur);
  8321. cb(cur, "result_output", -1);
  8322. ggml_build_forward_expand(gf, cur);
  8323. return gf;
  8324. }
  8325. // ref: https://arxiv.org/abs/2203.03466
  8326. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  8327. // based on the original build_llama() function
  8328. struct ggml_cgraph * build_minicpm() {
  8329. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8330. const int64_t n_embd_head = hparams.n_embd_head_v;
  8331. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8332. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8333. const int64_t n_embd = hparams.n_embd;
  8334. //TODO: if the model varies, these parameters need to be read from the model
  8335. const int64_t n_embd_base = 256;
  8336. const float scale_embd = 12.0f;
  8337. const float scale_depth = 1.4f;
  8338. struct ggml_tensor * cur;
  8339. struct ggml_tensor * inpL;
  8340. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8341. // scale the input embeddings
  8342. inpL = ggml_scale(ctx0, inpL, scale_embd);
  8343. cb(inpL, "inp_scaled", -1);
  8344. // inp_pos - contains the positions
  8345. struct ggml_tensor * inp_pos = build_inp_pos();
  8346. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8347. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8348. for (int il = 0; il < n_layer; ++il) {
  8349. struct ggml_tensor * inpSA = inpL;
  8350. // norm
  8351. cur = llm_build_norm(ctx0, inpL, hparams,
  8352. model.layers[il].attn_norm, NULL,
  8353. LLM_NORM_RMS, cb, il);
  8354. cb(cur, "attn_norm", il);
  8355. // self-attention
  8356. {
  8357. // compute Q and K and RoPE them
  8358. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8359. cb(Qcur, "Qcur", il);
  8360. if (model.layers[il].bq) {
  8361. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8362. cb(Qcur, "Qcur", il);
  8363. }
  8364. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8365. cb(Kcur, "Kcur", il);
  8366. if (model.layers[il].bk) {
  8367. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8368. cb(Kcur, "Kcur", il);
  8369. }
  8370. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8371. cb(Vcur, "Vcur", il);
  8372. if (model.layers[il].bv) {
  8373. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8374. cb(Vcur, "Vcur", il);
  8375. }
  8376. Qcur = ggml_rope_custom(
  8377. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8378. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8379. ext_factor, attn_factor, beta_fast, beta_slow
  8380. );
  8381. cb(Qcur, "Qcur", il);
  8382. Kcur = ggml_rope_custom(
  8383. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8384. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8385. ext_factor, attn_factor, beta_fast, beta_slow
  8386. );
  8387. cb(Kcur, "Kcur", il);
  8388. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8389. model.layers[il].wo, model.layers[il].bo,
  8390. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8391. }
  8392. if (il == n_layer - 1) {
  8393. // skip computing output for unused tokens
  8394. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8395. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8396. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8397. }
  8398. // scale_res - scale the hidden states for residual connection
  8399. const float scale_res = scale_depth/sqrtf(float(n_layer));
  8400. cur = ggml_scale(ctx0, cur, scale_res);
  8401. cb(cur, "hidden_scaled", -1);
  8402. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8403. cb(ffn_inp, "ffn_inp", il);
  8404. // feed-forward network
  8405. {
  8406. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8407. model.layers[il].ffn_norm, NULL,
  8408. LLM_NORM_RMS, cb, il);
  8409. cb(cur, "ffn_norm", il);
  8410. cur = llm_build_ffn(ctx0, cur,
  8411. model.layers[il].ffn_up, NULL,
  8412. model.layers[il].ffn_gate, NULL,
  8413. model.layers[il].ffn_down, NULL,
  8414. NULL,
  8415. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8416. cb(cur, "ffn_out", il);
  8417. }
  8418. // scale the hidden states for residual connection
  8419. cur = ggml_scale(ctx0, cur, scale_res);
  8420. cb(cur, "hidden_scaled_ffn", -1);
  8421. cur = ggml_add(ctx0, cur, ffn_inp);
  8422. cb(cur, "l_out", il);
  8423. // input for next layer
  8424. inpL = cur;
  8425. }
  8426. cur = inpL;
  8427. cur = llm_build_norm(ctx0, cur, hparams,
  8428. model.output_norm, NULL,
  8429. LLM_NORM_RMS, cb, -1);
  8430. cb(cur, "result_norm", -1);
  8431. // lm_head scaling
  8432. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  8433. cur = ggml_scale(ctx0, cur, scale_lmhead);
  8434. cb(cur, "lmhead_scaling", -1);
  8435. // lm_head
  8436. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  8437. cb(cur, "result_output", -1);
  8438. ggml_build_forward_expand(gf, cur);
  8439. return gf;
  8440. }
  8441. struct ggml_cgraph * build_gemma() {
  8442. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8443. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  8444. struct ggml_tensor * cur;
  8445. struct ggml_tensor * inpL;
  8446. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8447. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  8448. cb(inpL, "inp_scaled", -1);
  8449. // inp_pos - contains the positions
  8450. struct ggml_tensor * inp_pos = build_inp_pos();
  8451. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8452. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8453. for (int il = 0; il < n_layer; ++il) {
  8454. // norm
  8455. cur = llm_build_norm(ctx0, inpL, hparams,
  8456. model.layers[il].attn_norm, NULL,
  8457. LLM_NORM_RMS, cb, il);
  8458. cb(cur, "attn_norm", il);
  8459. // self-attention
  8460. {
  8461. // compute Q and K and RoPE them
  8462. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8463. cb(Qcur, "Qcur", il);
  8464. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8465. cb(Kcur, "Kcur", il);
  8466. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8467. cb(Vcur, "Vcur", il);
  8468. Qcur = ggml_rope_custom(
  8469. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  8470. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8471. ext_factor, attn_factor, beta_fast, beta_slow);
  8472. cb(Qcur, "Qcur", il);
  8473. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  8474. cb(Qcur, "Qcur_scaled", il);
  8475. Kcur = ggml_rope_custom(
  8476. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  8477. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8478. ext_factor, attn_factor, beta_fast, beta_slow);
  8479. cb(Kcur, "Kcur", il);
  8480. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8481. model.layers[il].wo, NULL,
  8482. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  8483. }
  8484. if (il == n_layer - 1) {
  8485. // skip computing output for unused tokens
  8486. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8487. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8488. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8489. }
  8490. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  8491. cb(sa_out, "sa_out", il);
  8492. cur = llm_build_norm(ctx0, sa_out, hparams,
  8493. model.layers[il].ffn_norm, NULL,
  8494. LLM_NORM_RMS, cb, il);
  8495. cb(cur, "ffn_norm", il);
  8496. // feed-forward network
  8497. {
  8498. cur = llm_build_ffn(ctx0, cur,
  8499. model.layers[il].ffn_up, NULL,
  8500. model.layers[il].ffn_gate, NULL,
  8501. model.layers[il].ffn_down, NULL,
  8502. NULL,
  8503. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  8504. cb(cur, "ffn_out", il);
  8505. }
  8506. cur = ggml_add(ctx0, cur, sa_out);
  8507. cb(cur, "l_out", il);
  8508. // input for next layer
  8509. inpL = cur;
  8510. }
  8511. cur = inpL;
  8512. cur = llm_build_norm(ctx0, cur, hparams,
  8513. model.output_norm, NULL,
  8514. LLM_NORM_RMS, cb, -1);
  8515. cb(cur, "result_norm", -1);
  8516. // lm_head
  8517. cur = ggml_mul_mat(ctx0, model.output, cur);
  8518. cb(cur, "result_output", -1);
  8519. ggml_build_forward_expand(gf, cur);
  8520. return gf;
  8521. }
  8522. struct ggml_cgraph * build_starcoder2() {
  8523. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8524. const int64_t n_embd_head = hparams.n_embd_head_v;
  8525. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8526. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8527. struct ggml_tensor * cur;
  8528. struct ggml_tensor * inpL;
  8529. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8530. // inp_pos - contains the positions
  8531. struct ggml_tensor * inp_pos = build_inp_pos();
  8532. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8533. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8534. for (int il = 0; il < n_layer; ++il) {
  8535. struct ggml_tensor * inpSA = inpL;
  8536. // norm
  8537. cur = llm_build_norm(ctx0, inpL, hparams,
  8538. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  8539. LLM_NORM, cb, il);
  8540. cb(cur, "attn_norm", il);
  8541. // self-attention
  8542. {
  8543. // compute Q and K and RoPE them
  8544. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8545. cb(Qcur, "Qcur", il);
  8546. if (model.layers[il].bq) {
  8547. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8548. cb(Qcur, "Qcur", il);
  8549. }
  8550. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8551. cb(Kcur, "Kcur", il);
  8552. if (model.layers[il].bk) {
  8553. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8554. cb(Kcur, "Kcur", il);
  8555. }
  8556. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8557. cb(Vcur, "Vcur", il);
  8558. if (model.layers[il].bv) {
  8559. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8560. cb(Vcur, "Vcur", il);
  8561. }
  8562. Qcur = ggml_rope_custom(
  8563. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8564. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8565. ext_factor, attn_factor, beta_fast, beta_slow
  8566. );
  8567. cb(Qcur, "Qcur", il);
  8568. Kcur = ggml_rope_custom(
  8569. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8570. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8571. ext_factor, attn_factor, beta_fast, beta_slow
  8572. );
  8573. cb(Kcur, "Kcur", il);
  8574. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8575. model.layers[il].wo, model.layers[il].bo,
  8576. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8577. }
  8578. if (il == n_layer - 1) {
  8579. // skip computing output for unused tokens
  8580. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8581. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8582. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8583. }
  8584. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8585. cb(ffn_inp, "ffn_inp", il);
  8586. // feed-forward network
  8587. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8588. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  8589. LLM_NORM, cb, il);
  8590. cb(cur, "ffn_norm", il);
  8591. cur = llm_build_ffn(ctx0, cur,
  8592. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  8593. NULL, NULL,
  8594. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  8595. NULL,
  8596. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  8597. cb(cur, "ffn_out", il);
  8598. cur = ggml_add(ctx0, cur, ffn_inp);
  8599. cb(cur, "l_out", il);
  8600. // input for next layer
  8601. inpL = cur;
  8602. }
  8603. cur = inpL;
  8604. cur = llm_build_norm(ctx0, cur, hparams,
  8605. model.output_norm, model.output_norm_b,
  8606. LLM_NORM, cb, -1);
  8607. cb(cur, "result_norm", -1);
  8608. // lm_head
  8609. cur = ggml_mul_mat(ctx0, model.output, cur);
  8610. cb(cur, "result_output", -1);
  8611. ggml_build_forward_expand(gf, cur);
  8612. return gf;
  8613. }
  8614. struct ggml_cgraph * build_mamba() {
  8615. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8616. const int64_t d_model = n_embd;
  8617. const int64_t d_conv = hparams.ssm_d_conv;
  8618. const int64_t d_inner = hparams.ssm_d_inner;
  8619. GGML_ASSERT(2 * d_model == d_inner);
  8620. const int64_t d_state = hparams.ssm_d_state;
  8621. const int64_t dt_rank = hparams.ssm_dt_rank;
  8622. struct ggml_tensor * cur;
  8623. struct ggml_tensor * inpL;
  8624. // {n_embd, n_tokens}
  8625. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8626. struct ggml_tensor * state_mask = build_inp_s_mask();
  8627. struct ggml_tensor * state_seq = build_inp_s_seq();
  8628. for (int il = 0; il < n_layer; ++il) {
  8629. // (ab)using the KV cache to store the states
  8630. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  8631. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  8632. // clear states of sequences which are starting at the beginning of this batch
  8633. {
  8634. conv_states = ggml_mul(ctx0,
  8635. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  8636. state_mask);
  8637. ssm_states = ggml_mul(ctx0,
  8638. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  8639. state_mask);
  8640. }
  8641. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  8642. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  8643. // norm
  8644. cur = llm_build_norm(ctx0, inpL, hparams,
  8645. model.layers[il].attn_norm, NULL,
  8646. LLM_NORM_RMS, cb, il);
  8647. cb(cur, "attn_norm", il);
  8648. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  8649. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  8650. // split the above in two
  8651. // => {d_inner, n_tokens}
  8652. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  8653. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  8654. // conv
  8655. {
  8656. // Custom operator which is needed only to ease simultaneous sequence processing.
  8657. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  8658. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  8659. // then element-wise multiply that with the conv1d weigth,
  8660. // then sum the elements of each row,
  8661. // (the last two steps are a dot product over rows (also doable with mul_mat))
  8662. // then permute away the ne[0] dimension,
  8663. // and then you're left with the resulting x tensor.
  8664. // The new conv_states is the last (d_conv - 1) columns
  8665. // of the last 3rd dimensional "layer" of the self-overlapping view.
  8666. // For simultaneous sequences, it's more complicated.
  8667. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  8668. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  8669. ggml_build_forward_expand(gf,
  8670. ggml_cpy(ctx0,
  8671. 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)),
  8672. 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))));
  8673. // extract x from x_conv
  8674. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  8675. // bias
  8676. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  8677. x = ggml_silu(ctx0, x);
  8678. }
  8679. // ssm
  8680. {
  8681. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  8682. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  8683. // split
  8684. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  8685. 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);
  8686. 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));
  8687. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  8688. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  8689. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  8690. // Custom operator to optimize the parallel associative scan
  8691. // as described in the Annex D of the Mamba paper.
  8692. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  8693. // because only a single tensor can be returned.
  8694. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  8695. // store last states (the second part of y_ssm_states)
  8696. ggml_build_forward_expand(gf,
  8697. ggml_cpy(ctx0,
  8698. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  8699. 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))));
  8700. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  8701. if (il == n_layer - 1) {
  8702. // skip computing output for unused tokens
  8703. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8704. x = ggml_get_rows(ctx0, x, inp_out_ids);
  8705. y = ggml_get_rows(ctx0, y, inp_out_ids);
  8706. z = ggml_get_rows(ctx0, z, inp_out_ids);
  8707. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8708. }
  8709. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  8710. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  8711. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  8712. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  8713. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  8714. }
  8715. // residual
  8716. cur = ggml_add(ctx0, cur, inpL);
  8717. cb(cur, "l_out", il);
  8718. // input for next layer
  8719. inpL = cur;
  8720. }
  8721. // final rmsnorm
  8722. cur = llm_build_norm(ctx0, inpL, hparams,
  8723. model.output_norm, NULL,
  8724. LLM_NORM_RMS, cb, -1);
  8725. cb(cur, "result_norm", -1);
  8726. // lm_head
  8727. cur = ggml_mul_mat(ctx0, model.output, cur);
  8728. cb(cur, "result_output", -1);
  8729. ggml_build_forward_expand(gf, cur);
  8730. return gf;
  8731. }
  8732. struct ggml_cgraph * build_command_r() {
  8733. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8734. const int64_t n_embd_head = hparams.n_embd_head_v;
  8735. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8736. const float f_logit_scale = hparams.f_logit_scale;
  8737. struct ggml_tensor * cur;
  8738. struct ggml_tensor * inpL;
  8739. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8740. // inp_pos - contains the positions
  8741. struct ggml_tensor * inp_pos = build_inp_pos();
  8742. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8743. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8744. for (int il = 0; il < n_layer; ++il) {
  8745. // norm
  8746. cur = llm_build_norm(ctx0, inpL, hparams,
  8747. model.layers[il].attn_norm, NULL,
  8748. LLM_NORM, cb, il);
  8749. cb(cur, "attn_norm", il);
  8750. struct ggml_tensor * ffn_inp = cur;
  8751. // self-attention
  8752. {
  8753. // compute Q and K and RoPE them
  8754. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8755. cb(Qcur, "Qcur", il);
  8756. if (model.layers[il].bq) {
  8757. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  8758. cb(Qcur, "Qcur", il);
  8759. }
  8760. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8761. cb(Kcur, "Kcur", il);
  8762. if (model.layers[il].bk) {
  8763. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  8764. cb(Kcur, "Kcur", il);
  8765. }
  8766. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8767. cb(Vcur, "Vcur", il);
  8768. if (model.layers[il].bv) {
  8769. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  8770. cb(Vcur, "Vcur", il);
  8771. }
  8772. if (model.layers[il].attn_q_norm) {
  8773. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  8774. ggml_element_size(Qcur) * n_embd_head,
  8775. ggml_element_size(Qcur) * n_embd_head * n_head,
  8776. 0);
  8777. cb(Qcur, "Qcur", il);
  8778. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  8779. ggml_element_size(Kcur) * n_embd_head,
  8780. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  8781. 0);
  8782. cb(Kcur, "Kcur", il);
  8783. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  8784. model.layers[il].attn_q_norm,
  8785. NULL,
  8786. LLM_NORM, cb, il);
  8787. cb(Qcur, "Qcur", il);
  8788. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8789. model.layers[il].attn_k_norm,
  8790. NULL,
  8791. LLM_NORM, cb, il);
  8792. cb(Kcur, "Kcur", il);
  8793. }
  8794. Qcur = ggml_rope_custom(
  8795. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8796. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8797. ext_factor, attn_factor, beta_fast, beta_slow
  8798. );
  8799. cb(Qcur, "Qcur", il);
  8800. Kcur = ggml_rope_custom(
  8801. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8802. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8803. ext_factor, attn_factor, beta_fast, beta_slow
  8804. );
  8805. cb(Kcur, "Kcur", il);
  8806. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8807. model.layers[il].wo, model.layers[il].bo,
  8808. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8809. }
  8810. if (il == n_layer - 1) {
  8811. // skip computing output for unused tokens
  8812. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8813. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8814. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8815. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  8816. }
  8817. struct ggml_tensor * attn_out = cur;
  8818. // feed-forward network
  8819. {
  8820. cur = llm_build_ffn(ctx0, ffn_inp,
  8821. model.layers[il].ffn_up, NULL,
  8822. model.layers[il].ffn_gate, NULL,
  8823. model.layers[il].ffn_down, NULL,
  8824. NULL,
  8825. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8826. cb(cur, "ffn_out", il);
  8827. }
  8828. // add together residual + FFN + self-attention
  8829. cur = ggml_add(ctx0, cur, inpL);
  8830. cur = ggml_add(ctx0, cur, attn_out);
  8831. cb(cur, "l_out", il);
  8832. // input for next layer
  8833. inpL = cur;
  8834. }
  8835. cur = inpL;
  8836. cur = llm_build_norm(ctx0, cur, hparams,
  8837. model.output_norm, NULL,
  8838. LLM_NORM, cb, -1);
  8839. cb(cur, "result_norm", -1);
  8840. // lm_head
  8841. cur = ggml_mul_mat(ctx0, model.output, cur);
  8842. if (f_logit_scale) {
  8843. cur = ggml_scale(ctx0, cur, f_logit_scale);
  8844. }
  8845. cb(cur, "result_output", -1);
  8846. ggml_build_forward_expand(gf, cur);
  8847. return gf;
  8848. }
  8849. // ref: https://allenai.org/olmo
  8850. // based on the original build_llama() function, changes:
  8851. // * non-parametric layer norm
  8852. // * clamp qkv
  8853. // * removed bias
  8854. // * removed MoE
  8855. struct ggml_cgraph * build_olmo() {
  8856. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  8857. // mutable variable, needed during the last layer of the computation to skip unused tokens
  8858. int32_t n_tokens = this->n_tokens;
  8859. const int64_t n_embd_head = hparams.n_embd_head_v;
  8860. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  8861. GGML_ASSERT(n_embd_head == hparams.n_rot);
  8862. struct ggml_tensor * cur;
  8863. struct ggml_tensor * inpL;
  8864. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  8865. // inp_pos - contains the positions
  8866. struct ggml_tensor * inp_pos = build_inp_pos();
  8867. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  8868. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  8869. for (int il = 0; il < n_layer; ++il) {
  8870. struct ggml_tensor * inpSA = inpL;
  8871. // norm
  8872. cur = llm_build_norm(ctx0, inpL, hparams,
  8873. NULL, NULL,
  8874. LLM_NORM, cb, il);
  8875. cb(cur, "attn_norm", il);
  8876. // self-attention
  8877. {
  8878. // compute Q and K and RoPE them
  8879. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  8880. cb(Qcur, "Qcur", il);
  8881. if (hparams.f_clamp_kqv > 0.0f) {
  8882. Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8883. cb(Qcur, "Qcur", il);
  8884. }
  8885. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  8886. cb(Kcur, "Kcur", il);
  8887. if (hparams.f_clamp_kqv > 0.0f) {
  8888. Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8889. cb(Kcur, "Kcur", il);
  8890. }
  8891. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  8892. cb(Vcur, "Vcur", il);
  8893. if (hparams.f_clamp_kqv > 0.0f) {
  8894. Vcur = ggml_clamp(ctx0, Vcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  8895. cb(Vcur, "Vcur", il);
  8896. }
  8897. Qcur = ggml_rope_custom(
  8898. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8899. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8900. ext_factor, attn_factor, beta_fast, beta_slow
  8901. );
  8902. cb(Qcur, "Qcur", il);
  8903. Kcur = ggml_rope_custom(
  8904. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8905. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8906. ext_factor, attn_factor, beta_fast, beta_slow
  8907. );
  8908. cb(Kcur, "Kcur", il);
  8909. cur = llm_build_kv(ctx0, model, hparams, cparams, kv_self, gf,
  8910. model.layers[il].wo, nullptr,
  8911. Kcur, Vcur, Qcur, KQ_mask, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8912. }
  8913. if (il == n_layer - 1) {
  8914. // skip computing output for unused tokens
  8915. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8916. n_tokens = n_outputs;
  8917. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8918. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  8919. }
  8920. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  8921. cb(ffn_inp, "ffn_inp", il);
  8922. // feed-forward network
  8923. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  8924. NULL, NULL,
  8925. LLM_NORM, cb, il);
  8926. cb(cur, "ffn_norm", il);
  8927. cur = llm_build_ffn(ctx0, cur,
  8928. model.layers[il].ffn_up, NULL,
  8929. model.layers[il].ffn_gate, NULL,
  8930. model.layers[il].ffn_down, NULL,
  8931. NULL,
  8932. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8933. cb(cur, "ffn_out", il);
  8934. cur = ggml_add(ctx0, cur, ffn_inp);
  8935. cb(cur, "ffn_out", il);
  8936. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  8937. if (layer_dir != nullptr) {
  8938. cur = ggml_add(ctx0, cur, layer_dir);
  8939. }
  8940. cb(cur, "l_out", il);
  8941. // input for next layer
  8942. inpL = cur;
  8943. }
  8944. cur = inpL;
  8945. cur = llm_build_norm(ctx0, cur, hparams,
  8946. NULL, NULL,
  8947. LLM_NORM, cb, -1);
  8948. cb(cur, "result_norm", -1);
  8949. // lm_head
  8950. cur = ggml_mul_mat(ctx0, model.output, cur);
  8951. cb(cur, "result_output", -1);
  8952. ggml_build_forward_expand(gf, cur);
  8953. return gf;
  8954. }
  8955. };
  8956. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  8957. llama_batch dummy;
  8958. dummy.n_tokens = 0;
  8959. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8960. struct llm_build_context llm(lctx, dummy, cb, false);
  8961. llm.init();
  8962. struct ggml_cgraph * result = llm.build_defrag(ids);
  8963. llm.free();
  8964. return result;
  8965. }
  8966. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  8967. llama_batch dummy;
  8968. dummy.n_tokens = 0;
  8969. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8970. struct llm_build_context llm(lctx, dummy, cb, false);
  8971. llm.init();
  8972. struct ggml_cgraph * result = llm.build_k_shift();
  8973. llm.free();
  8974. return result;
  8975. }
  8976. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  8977. llama_batch dummy;
  8978. dummy.n_tokens = 0;
  8979. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8980. struct llm_build_context llm(lctx, dummy, cb, false);
  8981. llm.init();
  8982. struct ggml_cgraph * result = llm.build_s_copy();
  8983. llm.free();
  8984. return result;
  8985. }
  8986. static struct ggml_cgraph * llama_build_graph(
  8987. llama_context & lctx,
  8988. const llama_batch & batch,
  8989. bool worst_case) {
  8990. const auto & model = lctx.model;
  8991. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  8992. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  8993. if (il >= 0) {
  8994. ggml_format_name(cur, "%s-%d", name, il);
  8995. } else {
  8996. ggml_set_name(cur, name);
  8997. }
  8998. if (!lctx.cparams.offload_kqv) {
  8999. if (strcmp(name, "kqv_merged_cont") == 0) {
  9000. // all nodes between the KV store and the attention output are run on the CPU
  9001. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  9002. }
  9003. }
  9004. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  9005. // FIXME: fix in ggml_backend_sched
  9006. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  9007. if (batch.n_tokens < 32 || full_offload) {
  9008. if (il != -1 && strcmp(name, "norm") == 0) {
  9009. for (auto * backend : lctx.backends) {
  9010. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  9011. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  9012. break;
  9013. }
  9014. }
  9015. }
  9016. }
  9017. };
  9018. struct ggml_cgraph * result = NULL;
  9019. struct llm_build_context llm(lctx, batch, cb, worst_case);
  9020. llm.init();
  9021. switch (model.arch) {
  9022. case LLM_ARCH_LLAMA:
  9023. {
  9024. result = llm.build_llama();
  9025. } break;
  9026. case LLM_ARCH_BAICHUAN:
  9027. {
  9028. result = llm.build_baichuan();
  9029. } break;
  9030. case LLM_ARCH_FALCON:
  9031. {
  9032. result = llm.build_falcon();
  9033. } break;
  9034. case LLM_ARCH_GROK:
  9035. {
  9036. result = llm.build_grok();
  9037. } break;
  9038. case LLM_ARCH_STARCODER:
  9039. {
  9040. result = llm.build_starcoder();
  9041. } break;
  9042. case LLM_ARCH_PERSIMMON:
  9043. {
  9044. result = llm.build_persimmon();
  9045. } break;
  9046. case LLM_ARCH_REFACT:
  9047. {
  9048. result = llm.build_refact();
  9049. } break;
  9050. case LLM_ARCH_BERT:
  9051. case LLM_ARCH_JINA_BERT_V2:
  9052. case LLM_ARCH_NOMIC_BERT:
  9053. {
  9054. result = llm.build_bert();
  9055. } break;
  9056. case LLM_ARCH_BLOOM:
  9057. {
  9058. result = llm.build_bloom();
  9059. } break;
  9060. case LLM_ARCH_MPT:
  9061. {
  9062. result = llm.build_mpt();
  9063. } break;
  9064. case LLM_ARCH_STABLELM:
  9065. {
  9066. result = llm.build_stablelm();
  9067. } break;
  9068. case LLM_ARCH_QWEN:
  9069. {
  9070. result = llm.build_qwen();
  9071. } break;
  9072. case LLM_ARCH_QWEN2:
  9073. {
  9074. result = llm.build_qwen2();
  9075. } break;
  9076. case LLM_ARCH_QWEN2MOE:
  9077. {
  9078. result = llm.build_qwen2moe();
  9079. } break;
  9080. case LLM_ARCH_PHI2:
  9081. {
  9082. result = llm.build_phi2();
  9083. } break;
  9084. case LLM_ARCH_PHI3:
  9085. {
  9086. result = llm.build_phi3();
  9087. } break;
  9088. case LLM_ARCH_PLAMO:
  9089. {
  9090. result = llm.build_plamo();
  9091. } break;
  9092. case LLM_ARCH_GPT2:
  9093. {
  9094. result = llm.build_gpt2();
  9095. } break;
  9096. case LLM_ARCH_CODESHELL:
  9097. {
  9098. result = llm.build_codeshell();
  9099. } break;
  9100. case LLM_ARCH_ORION:
  9101. {
  9102. result = llm.build_orion();
  9103. } break;
  9104. case LLM_ARCH_INTERNLM2:
  9105. {
  9106. result = llm.build_internlm2();
  9107. } break;
  9108. case LLM_ARCH_MINICPM:
  9109. {
  9110. result = llm.build_minicpm();
  9111. } break;
  9112. case LLM_ARCH_GEMMA:
  9113. {
  9114. result = llm.build_gemma();
  9115. } break;
  9116. case LLM_ARCH_STARCODER2:
  9117. {
  9118. result = llm.build_starcoder2();
  9119. } break;
  9120. case LLM_ARCH_MAMBA:
  9121. {
  9122. result = llm.build_mamba();
  9123. } break;
  9124. case LLM_ARCH_XVERSE:
  9125. {
  9126. result = llm.build_xverse();
  9127. } break;
  9128. case LLM_ARCH_COMMAND_R:
  9129. {
  9130. result = llm.build_command_r();
  9131. } break;
  9132. case LLM_ARCH_DBRX:
  9133. {
  9134. result = llm.build_dbrx();
  9135. } break;
  9136. case LLM_ARCH_OLMO:
  9137. {
  9138. result = llm.build_olmo();
  9139. } break;
  9140. default:
  9141. GGML_ASSERT(false);
  9142. }
  9143. llm.free();
  9144. return result;
  9145. }
  9146. static void llama_set_k_shift(llama_context & lctx) {
  9147. const int64_t kv_size = lctx.kv_self.size;
  9148. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  9149. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  9150. for (int i = 0; i < kv_size; ++i) {
  9151. data[i] = lctx.kv_self.cells[i].delta;
  9152. }
  9153. }
  9154. static void llama_set_s_copy(llama_context & lctx) {
  9155. const int64_t kv_size = lctx.kv_self.size;
  9156. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  9157. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  9158. for (int i = 0; i < kv_size; ++i) {
  9159. data[i] = lctx.kv_self.cells[i].src;
  9160. }
  9161. }
  9162. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  9163. //
  9164. // set input data
  9165. //
  9166. const auto & hparams = lctx.model.hparams;
  9167. const auto & cparams = lctx.cparams;
  9168. const auto & kv_self = lctx.kv_self;
  9169. if (batch.token) {
  9170. const int64_t n_tokens = batch.n_tokens;
  9171. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  9172. }
  9173. if (batch.embd) {
  9174. const int64_t n_embd = hparams.n_embd;
  9175. const int64_t n_tokens = batch.n_tokens;
  9176. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  9177. }
  9178. if (batch.pos && lctx.inp_pos) {
  9179. const int64_t n_tokens = batch.n_tokens;
  9180. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  9181. }
  9182. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  9183. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  9184. const int64_t n_tokens = batch.n_tokens;
  9185. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  9186. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  9187. if (lctx.n_outputs == n_tokens) {
  9188. for (int i = 0; i < n_tokens; ++i) {
  9189. data[i] = i;
  9190. }
  9191. } else if (batch.logits) {
  9192. int32_t n_outputs = 0;
  9193. for (int i = 0; i < n_tokens; ++i) {
  9194. if (batch.logits[i]) {
  9195. data[n_outputs++] = i;
  9196. }
  9197. }
  9198. // the graph needs to have been passed the correct number of outputs
  9199. GGML_ASSERT(lctx.n_outputs == n_outputs);
  9200. } else if (lctx.n_outputs == 1) {
  9201. // only keep last output
  9202. data[0] = n_tokens - 1;
  9203. } else {
  9204. GGML_ASSERT(lctx.n_outputs == 0);
  9205. }
  9206. }
  9207. GGML_ASSERT(
  9208. // (!a || b) is a logical implication (a -> b)
  9209. // !hparams.causal_attn -> !cparams.causal_attn
  9210. (hparams.causal_attn || !cparams.causal_attn) &&
  9211. "causal attention with embedding models is not supported"
  9212. );
  9213. if (lctx.inp_KQ_mask) {
  9214. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  9215. if (cparams.causal_attn) {
  9216. const int64_t n_kv = kv_self.n;
  9217. const int64_t n_tokens = batch.n_tokens;
  9218. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  9219. float * data = (float *) lctx.inp_KQ_mask->data;
  9220. // For causal attention, use only the previous KV cells
  9221. // of the correct sequence for each token of the batch.
  9222. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  9223. for (int h = 0; h < 1; ++h) {
  9224. for (int j = 0; j < n_tokens; ++j) {
  9225. const llama_pos pos = batch.pos[j];
  9226. const llama_seq_id seq_id = batch.seq_id[j][0];
  9227. for (int i = 0; i < n_kv; ++i) {
  9228. float f;
  9229. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  9230. f = -INFINITY;
  9231. } else {
  9232. if (hparams.use_alibi) {
  9233. f = -fabs(lctx.kv_self.cells[i].pos - pos);
  9234. } else {
  9235. f = 0.0f;
  9236. }
  9237. }
  9238. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  9239. }
  9240. }
  9241. for (int i = n_tokens; i < GGML_PAD(n_tokens, GGML_KQ_MASK_PAD); ++i) {
  9242. for (int j = 0; j < n_kv; ++j) {
  9243. data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
  9244. }
  9245. }
  9246. }
  9247. } else {
  9248. // when using kv cache, the mask needs to match the kv cache size
  9249. const int64_t n_tokens = batch.n_tokens;
  9250. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  9251. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  9252. float * data = (float *) lctx.inp_KQ_mask->data;
  9253. for (int h = 0; h < 1; ++h) {
  9254. for (int j = 0; j < n_tokens; ++j) {
  9255. const llama_seq_id seq_id = batch.seq_id[j][0];
  9256. for (int i = 0; i < n_tokens; ++i) {
  9257. float f = -INFINITY;
  9258. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  9259. if (batch.seq_id[i][s] == seq_id) {
  9260. if (hparams.use_alibi) {
  9261. f = -fabs(batch.pos[i] - batch.pos[j]);
  9262. } else {
  9263. f = 0.0f;
  9264. }
  9265. break;
  9266. }
  9267. }
  9268. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  9269. }
  9270. for (int i = n_tokens; i < n_stride; ++i) {
  9271. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  9272. }
  9273. }
  9274. }
  9275. }
  9276. }
  9277. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  9278. const int64_t n_tokens = batch.n_tokens;
  9279. GGML_ASSERT(lctx.inp_mean);
  9280. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  9281. float * data = (float *) lctx.inp_mean->data;
  9282. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  9283. std::vector<uint64_t> sum(n_tokens, 0);
  9284. for (int i = 0; i < n_tokens; ++i) {
  9285. const llama_seq_id seq_id = batch.seq_id[i][0];
  9286. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  9287. sum[seq_id] += 1;
  9288. }
  9289. std::vector<float> div(n_tokens, 0.0f);
  9290. for (int i = 0; i < n_tokens; ++i) {
  9291. const uint64_t s = sum[i];
  9292. if (s > 0) {
  9293. div[i] = 1.0f/float(s);
  9294. }
  9295. }
  9296. for (int i = 0; i < n_tokens; ++i) {
  9297. const llama_seq_id seq_id = batch.seq_id[i][0];
  9298. data[seq_id*n_tokens + i] = div[seq_id];
  9299. }
  9300. }
  9301. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  9302. const int64_t n_tokens = batch.n_tokens;
  9303. GGML_ASSERT(lctx.inp_cls);
  9304. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  9305. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  9306. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  9307. for (int i = 0; i < n_tokens; ++i) {
  9308. const llama_seq_id seq_id = batch.seq_id[i][0];
  9309. const llama_pos pos = batch.pos[i];
  9310. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  9311. if (pos == 0) {
  9312. data[seq_id] = i;
  9313. }
  9314. }
  9315. }
  9316. if (kv_self.recurrent) {
  9317. const int64_t n_kv = kv_self.n;
  9318. if (lctx.inp_s_mask) {
  9319. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  9320. float * data = (float *) lctx.inp_s_mask->data;
  9321. // states which are not affected by the current batch are left untouched
  9322. for (int i = 0; i < n_kv; ++i) {
  9323. llama_seq_id seq_id = i + lctx.kv_self.head;
  9324. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  9325. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  9326. data[i] = (float) has_self_seq;
  9327. // ensure current sequences will be kept
  9328. if (!has_self_seq && kv_cell.pos >= 0) {
  9329. kv_cell.seq_id.insert(seq_id);
  9330. }
  9331. }
  9332. }
  9333. // For Mamba (and other recurrent architectures),
  9334. // update the correct state(s)/sequence(s) for each token of the batch.
  9335. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  9336. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  9337. if (lctx.inp_s_seq) {
  9338. const int64_t n_tokens = batch.n_tokens;
  9339. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  9340. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  9341. for (int j = 0; j < n_tokens; ++j) {
  9342. const int32_t n_seq = batch.n_seq_id[j];
  9343. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  9344. for (int i = 0; i < n_kv; ++i) {
  9345. if (i < n_seq) {
  9346. // for this type of model, the head is the minimum seq_id of the batch
  9347. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  9348. } else {
  9349. data[j*n_kv + i] = -1;
  9350. }
  9351. }
  9352. }
  9353. }
  9354. }
  9355. }
  9356. // Make sure enough space is available for outputs.
  9357. // Returns max number of outputs for which space was reserved.
  9358. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  9359. const auto & cparams = lctx.cparams;
  9360. const auto & hparams = lctx.model.hparams;
  9361. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  9362. const auto n_batch = cparams.n_batch;
  9363. const auto n_vocab = hparams.n_vocab;
  9364. const auto n_embd = hparams.n_embd;
  9365. // TODO: use a per-batch flag for logits presence instead
  9366. const bool has_logits = cparams.causal_attn;
  9367. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  9368. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  9369. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  9370. if (lctx.output_ids.empty()) {
  9371. // init, never resized afterwards
  9372. lctx.output_ids.resize(n_batch);
  9373. }
  9374. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  9375. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  9376. // alloc only when more than the current capacity is required
  9377. // TODO: also consider shrinking the buffer
  9378. if (!lctx.buf_output || prev_size < new_size) {
  9379. if (lctx.buf_output) {
  9380. #ifndef NDEBUG
  9381. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  9382. 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);
  9383. #endif
  9384. ggml_backend_buffer_free(lctx.buf_output);
  9385. lctx.buf_output = nullptr;
  9386. lctx.logits = nullptr;
  9387. lctx.embd = nullptr;
  9388. }
  9389. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  9390. if (lctx.buf_output == nullptr) {
  9391. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  9392. return 0;
  9393. }
  9394. }
  9395. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  9396. lctx.logits = has_logits ? output_base : nullptr;
  9397. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  9398. lctx.output_size = n_outputs_max;
  9399. lctx.logits_size = logits_size;
  9400. lctx.embd_size = embd_size;
  9401. // set all ids as invalid (negative)
  9402. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  9403. ggml_backend_buffer_clear(lctx.buf_output, 0);
  9404. lctx.n_outputs = 0;
  9405. return n_outputs_max;
  9406. }
  9407. static void llama_graph_compute(
  9408. llama_context & lctx,
  9409. ggml_cgraph * gf,
  9410. int n_threads) {
  9411. #ifdef GGML_USE_METAL
  9412. if (ggml_backend_is_metal(lctx.backend_metal)) {
  9413. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  9414. }
  9415. #endif
  9416. if (lctx.backend_cpu != nullptr) {
  9417. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  9418. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  9419. }
  9420. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  9421. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  9422. }
  9423. // decode a batch of tokens by evaluating the transformer
  9424. //
  9425. // - lctx: llama context
  9426. // - batch: batch to evaluate
  9427. //
  9428. // return 0 on success
  9429. // return positive int on warning
  9430. // return negative int on error
  9431. //
  9432. static int llama_decode_internal(
  9433. llama_context & lctx,
  9434. llama_batch batch_all) { // TODO: rename back to batch
  9435. const uint32_t n_tokens_all = batch_all.n_tokens;
  9436. if (n_tokens_all == 0) {
  9437. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  9438. return -1;
  9439. }
  9440. const auto & model = lctx.model;
  9441. const auto & hparams = model.hparams;
  9442. const auto & cparams = lctx.cparams;
  9443. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  9444. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  9445. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  9446. if (lctx.t_compute_start_us == 0) {
  9447. lctx.t_compute_start_us = ggml_time_us();
  9448. }
  9449. lctx.n_queued_tokens += n_tokens_all;
  9450. auto & kv_self = lctx.kv_self;
  9451. const int64_t n_embd = hparams.n_embd;
  9452. const int64_t n_vocab = hparams.n_vocab;
  9453. uint32_t n_outputs = 0;
  9454. uint32_t n_outputs_prev = 0;
  9455. const auto n_ubatch = cparams.n_ubatch;
  9456. std::vector<llama_pos> pos;
  9457. std::vector<int32_t> n_seq_id;
  9458. std::vector<llama_seq_id *> seq_id_arr;
  9459. std::vector<std::vector<llama_seq_id>> seq_id;
  9460. // count outputs
  9461. if (batch_all.logits) {
  9462. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  9463. n_outputs += batch_all.logits[i] != 0;
  9464. }
  9465. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  9466. n_outputs = n_tokens_all;
  9467. } else {
  9468. // keep last output only
  9469. n_outputs = 1;
  9470. }
  9471. // reserve output buffer
  9472. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  9473. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  9474. return -2;
  9475. };
  9476. // set output mappings
  9477. if (batch_all.logits) {
  9478. int32_t i_logits = 0;
  9479. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  9480. if (batch_all.logits[i]) {
  9481. lctx.output_ids[i] = i_logits++;
  9482. }
  9483. }
  9484. } else {
  9485. for (uint32_t i = 0; i < n_outputs; ++i) {
  9486. lctx.output_ids[i] = i;
  9487. }
  9488. }
  9489. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  9490. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  9491. llama_batch u_batch = {
  9492. /* .n_tokens = */ (int32_t) n_tokens,
  9493. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  9494. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  9495. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  9496. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  9497. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  9498. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  9499. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  9500. /* .all_pos_1 = */ batch_all.all_pos_1,
  9501. /* .all_seq_id = */ batch_all.all_seq_id,
  9502. };
  9503. // count the outputs in this u_batch
  9504. {
  9505. int32_t n_outputs_new = 0;
  9506. if (u_batch.logits) {
  9507. for (uint32_t i = 0; i < n_tokens; i++) {
  9508. n_outputs_new += u_batch.logits[i] != 0;
  9509. }
  9510. } else if (n_outputs == n_tokens_all) {
  9511. n_outputs_new = n_tokens;
  9512. } else {
  9513. // keep last output only
  9514. if (cur_token + n_tokens >= n_tokens_all) {
  9515. n_outputs_new = 1;
  9516. }
  9517. }
  9518. // needs to happen before the graph is built
  9519. lctx.n_outputs = n_outputs_new;
  9520. }
  9521. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  9522. GGML_ASSERT(n_threads > 0);
  9523. // helpers for smoother batch API transition
  9524. // after deprecating the llama_eval calls, these will be removed
  9525. if (u_batch.pos == nullptr) {
  9526. pos.resize(n_tokens);
  9527. for (uint32_t i = 0; i < n_tokens; i++) {
  9528. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  9529. }
  9530. u_batch.pos = pos.data();
  9531. }
  9532. if (u_batch.seq_id == nullptr) {
  9533. n_seq_id.resize(n_tokens);
  9534. seq_id.resize(n_tokens);
  9535. seq_id_arr.resize(n_tokens);
  9536. for (uint32_t i = 0; i < n_tokens; i++) {
  9537. n_seq_id[i] = 1;
  9538. seq_id[i].resize(1);
  9539. seq_id[i][0] = u_batch.all_seq_id;
  9540. seq_id_arr[i] = seq_id[i].data();
  9541. }
  9542. u_batch.n_seq_id = n_seq_id.data();
  9543. u_batch.seq_id = seq_id_arr.data();
  9544. }
  9545. // non-causal masks do not use the KV cache
  9546. if (hparams.causal_attn) {
  9547. llama_kv_cache_update(&lctx);
  9548. // if we have enough unused cells before the current head ->
  9549. // better to start searching from the beginning of the cache, hoping to fill it
  9550. if (kv_self.head > kv_self.used + 2*n_tokens) {
  9551. kv_self.head = 0;
  9552. }
  9553. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  9554. return 1;
  9555. }
  9556. if (!kv_self.recurrent) {
  9557. // a heuristic, to avoid attending the full cache if it is not yet utilized
  9558. // after enough generations, the benefit from this heuristic disappears
  9559. // if we start defragmenting the cache, the benefit from this will be more important
  9560. const uint32_t pad = llama_kv_cache_get_padding(cparams);
  9561. kv_self.n = std::min(kv_self.size, std::max(pad, GGML_PAD(llama_kv_cache_cell_max(kv_self), pad)));
  9562. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  9563. }
  9564. }
  9565. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  9566. ggml_backend_sched_reset(lctx.sched);
  9567. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  9568. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  9569. // the output is always the last tensor in the graph
  9570. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  9571. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  9572. if (lctx.n_outputs == 0) {
  9573. // no output
  9574. res = nullptr;
  9575. embd = nullptr;
  9576. } else if (!hparams.causal_attn) {
  9577. res = nullptr; // do not extract logits for embedding models such as BERT
  9578. // token or sequence embeddings
  9579. embd = gf->nodes[gf->n_nodes - 1];
  9580. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  9581. } else if (cparams.embeddings) {
  9582. // the embeddings could be in the second to last tensor, or any of the previous tensors
  9583. int i_embd = gf->n_nodes - 2;
  9584. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  9585. i_embd = gf->n_nodes - i;
  9586. if (i_embd < 0) { break; }
  9587. embd = gf->nodes[i_embd];
  9588. }
  9589. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  9590. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  9591. if (!cparams.causal_attn) {
  9592. res = nullptr; // do not extract logits when not needed
  9593. // skip computing logits
  9594. // TODO: is this safe?
  9595. gf->n_nodes = i_embd + 1;
  9596. }
  9597. } else {
  9598. embd = nullptr; // do not extract embeddings when not needed
  9599. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  9600. }
  9601. // 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);
  9602. // for big prompts, if BLAS is enabled, it is better to use only one thread
  9603. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  9604. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  9605. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  9606. // with the BLAS calls. need a better solution
  9607. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  9608. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  9609. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  9610. n_threads = std::min(4, n_threads);
  9611. }
  9612. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  9613. llama_set_inputs(lctx, u_batch);
  9614. llama_graph_compute(lctx, gf, n_threads);
  9615. // update the kv ring buffer
  9616. {
  9617. kv_self.head += n_tokens;
  9618. // Ensure kv cache head points to a valid index.
  9619. if (kv_self.head >= kv_self.size) {
  9620. kv_self.head = 0;
  9621. }
  9622. }
  9623. #ifdef GGML_PERF
  9624. // print timing information per ggml operation (for debugging purposes)
  9625. // requires GGML_PERF to be defined
  9626. ggml_graph_print(gf);
  9627. #endif
  9628. // plot the computation graph in dot format (for debugging purposes)
  9629. //if (n_past%100 == 0) {
  9630. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  9631. //}
  9632. // extract logits
  9633. if (res) {
  9634. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  9635. GGML_ASSERT(backend_res != nullptr);
  9636. GGML_ASSERT(lctx.logits != nullptr);
  9637. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  9638. const int32_t n_outputs_new = lctx.n_outputs;
  9639. if (n_outputs_new) {
  9640. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  9641. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  9642. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  9643. }
  9644. }
  9645. // extract embeddings
  9646. if (embd) {
  9647. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  9648. GGML_ASSERT(backend_embd != nullptr);
  9649. switch (cparams.pooling_type) {
  9650. case LLAMA_POOLING_TYPE_NONE:
  9651. {
  9652. // extract token embeddings
  9653. GGML_ASSERT(lctx.embd != nullptr);
  9654. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  9655. const int32_t n_outputs_new = lctx.n_outputs;
  9656. if (n_outputs_new) {
  9657. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  9658. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  9659. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  9660. }
  9661. } break;
  9662. case LLAMA_POOLING_TYPE_CLS:
  9663. case LLAMA_POOLING_TYPE_MEAN:
  9664. {
  9665. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  9666. // extract sequence embeddings
  9667. auto & embd_seq_out = lctx.embd_seq;
  9668. embd_seq_out.clear();
  9669. for (uint32_t i = 0; i < n_tokens; i++) {
  9670. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  9671. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  9672. continue;
  9673. }
  9674. embd_seq_out[seq_id].resize(n_embd);
  9675. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  9676. }
  9677. } break;
  9678. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  9679. {
  9680. GGML_ASSERT(false && "unknown pooling type");
  9681. } break;
  9682. }
  9683. }
  9684. n_outputs_prev += lctx.n_outputs;
  9685. }
  9686. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  9687. lctx.n_outputs = n_outputs;
  9688. // wait for the computation to finish (automatically done when obtaining the model output)
  9689. //llama_synchronize(&lctx);
  9690. // decide if we need to defrag the kv cache
  9691. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  9692. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  9693. // queue defragmentation for next llama_kv_cache_update
  9694. if (fragmentation > cparams.defrag_thold) {
  9695. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  9696. llama_kv_cache_defrag(kv_self);
  9697. }
  9698. }
  9699. // Reset state for the next token before backend sync, to allow the CPU activities in the reset to
  9700. // overlap with device computation.
  9701. ggml_backend_sched_reset(lctx.sched);
  9702. return 0;
  9703. }
  9704. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  9705. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  9706. auto & kv_self = lctx.kv_self;
  9707. const auto & hparams = lctx.model.hparams;
  9708. const uint32_t n_layer = hparams.n_layer;
  9709. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  9710. const uint32_t n_used = kv_self.used;
  9711. assert(n_used <= n_kv);
  9712. //const int64_t t_start = ggml_time_us();
  9713. // number of cells moved
  9714. uint32_t n_moves = 0;
  9715. // each move requires 6*n_layer tensors (see build_defrag)
  9716. // - source view, destination view, copy operation
  9717. // - x2 for keys and values
  9718. //const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  9719. // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516
  9720. const uint32_t max_moves = (LLAMA_MAX_NODES - 2*n_layer)/(6*n_layer);
  9721. // determine which KV cells to move where
  9722. //
  9723. // cell i moves to ids[i]
  9724. //
  9725. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  9726. //
  9727. std::vector<uint32_t> ids(n_kv, n_kv);
  9728. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  9729. const auto & cell0 = kv_self.cells[i0];
  9730. if (!cell0.is_empty()) {
  9731. ids[i0] = i0;
  9732. continue;
  9733. }
  9734. // found a hole - fill it with data from the end of the cache
  9735. uint32_t nh = 1;
  9736. // determine the size of the hole
  9737. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  9738. nh++;
  9739. }
  9740. uint32_t nf = 0;
  9741. uint32_t is = n_kv - 1;
  9742. // starting from the end, find nh non-empty cells
  9743. for (; is > i0; --is) {
  9744. const auto & cell1 = kv_self.cells[is];
  9745. if (cell1.is_empty() || ids[is] != n_kv) {
  9746. continue;
  9747. }
  9748. // non-empty cell which is not yet moved
  9749. nf++;
  9750. if (nf == nh) {
  9751. break;
  9752. }
  9753. }
  9754. // this can only happen if `n_used` is not accurate, which would be a bug
  9755. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  9756. nf = 0;
  9757. uint32_t i1 = is;
  9758. // are we moving a continuous block of memory?
  9759. bool cont = false;
  9760. // should we stop searching for the next move?
  9761. bool stop = false;
  9762. // go back and move the nf cells to the hole
  9763. for (; i1 < n_kv; ++i1) {
  9764. auto & cell1 = kv_self.cells[i1];
  9765. if (cell1.is_empty() || ids[i1] != n_kv) {
  9766. if (n_moves == max_moves) {
  9767. stop = true;
  9768. break;
  9769. }
  9770. cont = false;
  9771. continue;
  9772. }
  9773. // this cell goes to (i0 + nf)
  9774. ids[i1] = i0 + nf;
  9775. // move the cell meta data
  9776. kv_self.cells[i0 + nf] = cell1;
  9777. // clear the old cell and move the head there
  9778. cell1 = llama_kv_cell();
  9779. kv_self.head = n_used;
  9780. if (!cont) {
  9781. n_moves++;
  9782. cont = true;
  9783. }
  9784. nf++;
  9785. if (nf == nh) {
  9786. break;
  9787. }
  9788. }
  9789. if (stop || n_moves == max_moves) {
  9790. break;
  9791. }
  9792. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  9793. i0 += nh - 1;
  9794. }
  9795. if (n_moves == 0) {
  9796. return;
  9797. }
  9798. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  9799. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  9800. #if 0
  9801. // CPU defrag
  9802. //
  9803. // TODO: optimizations are possible:
  9804. // - multiple threads
  9805. // - avoid copying to the host memory when already there
  9806. //
  9807. // likely not worth the effort, as we have ggml_graph based defrag
  9808. //
  9809. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  9810. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  9811. const uint32_t kv_size = kv_self.size;
  9812. std::vector<uint8_t> buf_k;
  9813. std::vector<uint8_t> buf_v;
  9814. for (uint32_t il = 0; il < n_layer; ++il) {
  9815. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  9816. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  9817. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  9818. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  9819. buf_k.resize(k_size);
  9820. buf_v.resize(v_size);
  9821. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  9822. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  9823. // batch move [i, i+nm) to [id, id+nm)
  9824. // note: cells can move only to a lower index
  9825. for (uint32_t i = 0; i < n_kv; ++i) {
  9826. const uint32_t id = ids[i];
  9827. if (i == id || id == n_kv) {
  9828. continue;
  9829. }
  9830. uint32_t nm = 1;
  9831. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  9832. nm++;
  9833. }
  9834. // move keys
  9835. {
  9836. const int64_t os = i*k_size_row;
  9837. const int64_t od = id*k_size_row;
  9838. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  9839. }
  9840. // move values (note: they are transposed)
  9841. {
  9842. const int64_t os = i;
  9843. const int64_t od = id;
  9844. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  9845. 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);
  9846. }
  9847. }
  9848. i += nm - 1;
  9849. }
  9850. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  9851. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  9852. }
  9853. #else
  9854. // ggml_graph defrag
  9855. ggml_backend_sched_reset(lctx.sched);
  9856. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  9857. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  9858. #endif
  9859. //const int64_t t_end = ggml_time_us();
  9860. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  9861. }
  9862. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  9863. bool need_reserve = false;
  9864. // apply K-shift if needed
  9865. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  9866. {
  9867. ggml_backend_sched_reset(lctx.sched);
  9868. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  9869. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  9870. llama_set_k_shift(lctx);
  9871. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  9872. need_reserve = true;
  9873. }
  9874. {
  9875. auto & kv_self = lctx.kv_self;
  9876. kv_self.has_shift = false;
  9877. for (uint32_t i = 0; i < kv_self.size; ++i) {
  9878. kv_self.cells[i].delta = 0;
  9879. }
  9880. }
  9881. }
  9882. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  9883. {
  9884. ggml_backend_sched_reset(lctx.sched);
  9885. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  9886. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  9887. llama_set_s_copy(lctx);
  9888. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  9889. need_reserve = true;
  9890. }
  9891. {
  9892. auto & kv_self = lctx.kv_self;
  9893. kv_self.do_copy = false;
  9894. for (uint32_t i = 0; i < kv_self.size; ++i) {
  9895. kv_self.cells[i].src = i;
  9896. }
  9897. }
  9898. }
  9899. // defragment the KV cache if needed
  9900. if (lctx.kv_self.do_defrag) {
  9901. llama_kv_cache_defrag_internal(lctx);
  9902. need_reserve = true;
  9903. lctx.kv_self.do_defrag = false;
  9904. }
  9905. // reserve a worst case graph again
  9906. if (need_reserve) {
  9907. // TODO: extract to a function
  9908. // build worst-case graph
  9909. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  9910. int n_past = lctx.cparams.n_ctx - n_tokens;
  9911. 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
  9912. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9913. // initialize scheduler with the worst-case graph
  9914. ggml_backend_sched_reset(lctx.sched);
  9915. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  9916. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9917. }
  9918. }
  9919. }
  9920. //
  9921. // tokenizer
  9922. //
  9923. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  9924. return vocab.type;
  9925. }
  9926. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  9927. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9928. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  9929. }
  9930. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  9931. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9932. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  9933. }
  9934. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  9935. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9936. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  9937. }
  9938. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  9939. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9940. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  9941. }
  9942. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  9943. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9944. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  9945. }
  9946. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  9947. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  9948. GGML_ASSERT(llama_is_byte_token(vocab, id));
  9949. const auto & token_data = vocab.id_to_token.at(id);
  9950. switch (llama_vocab_get_type(vocab)) {
  9951. case LLAMA_VOCAB_TYPE_SPM: {
  9952. auto buf = token_data.text.substr(3, 2);
  9953. return strtol(buf.c_str(), NULL, 16);
  9954. }
  9955. case LLAMA_VOCAB_TYPE_BPE: {
  9956. GGML_ASSERT(false);
  9957. return unicode_utf8_to_byte(token_data.text); // TODO: why is this here after GGML_ASSERT?
  9958. }
  9959. case LLAMA_VOCAB_TYPE_WPM: {
  9960. GGML_ASSERT(false);
  9961. }
  9962. default:
  9963. GGML_ASSERT(false);
  9964. }
  9965. }
  9966. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  9967. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  9968. static const char * hex = "0123456789ABCDEF";
  9969. switch (llama_vocab_get_type(vocab)) {
  9970. case LLAMA_VOCAB_TYPE_SPM: {
  9971. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  9972. auto token = vocab.token_to_id.find(buf);
  9973. if (token != vocab.token_to_id.end()) {
  9974. return (*token).second;
  9975. }
  9976. // Try to fall back to just the byte as a string
  9977. const char buf2[2] = { (char)ch, 0 };
  9978. return vocab.token_to_id.at(buf2);
  9979. }
  9980. case LLAMA_VOCAB_TYPE_WPM:
  9981. case LLAMA_VOCAB_TYPE_BPE: {
  9982. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  9983. }
  9984. default:
  9985. GGML_ASSERT(false);
  9986. }
  9987. }
  9988. static void llama_escape_whitespace(std::string & text) {
  9989. replace_all(text, " ", "\xe2\x96\x81");
  9990. }
  9991. static void llama_unescape_whitespace(std::string & word) {
  9992. replace_all(word, "\xe2\x96\x81", " ");
  9993. }
  9994. struct llm_symbol {
  9995. using index = int;
  9996. index prev;
  9997. index next;
  9998. const char * text;
  9999. size_t n;
  10000. };
  10001. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  10002. // SPM tokenizer
  10003. // original implementation:
  10004. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  10005. struct llm_bigram_spm {
  10006. struct comparator {
  10007. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  10008. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  10009. }
  10010. };
  10011. using queue_storage = std::vector<llm_bigram_spm>;
  10012. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  10013. llm_symbol::index left;
  10014. llm_symbol::index right;
  10015. float score;
  10016. size_t size;
  10017. };
  10018. struct llm_tokenizer_spm {
  10019. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  10020. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10021. // split string into utf8 chars
  10022. int index = 0;
  10023. size_t offs = 0;
  10024. while (offs < text.size()) {
  10025. llm_symbol sym;
  10026. size_t len = utf8_len(text[offs]);
  10027. sym.text = text.c_str() + offs;
  10028. sym.n = std::min(len, text.size() - offs);
  10029. offs += sym.n;
  10030. sym.prev = index - 1;
  10031. sym.next = offs == text.size() ? -1 : index + 1;
  10032. index++;
  10033. symbols.emplace_back(sym);
  10034. }
  10035. // seed the work queue with all possible 2-character tokens.
  10036. for (size_t i = 1; i < symbols.size(); ++i) {
  10037. try_add_bigram(i - 1, i);
  10038. }
  10039. // keep substituting the highest frequency pairs for as long as we can.
  10040. while (!work_queue.empty()) {
  10041. auto bigram = work_queue.top();
  10042. work_queue.pop();
  10043. auto & left_sym = symbols[bigram.left];
  10044. auto & right_sym = symbols[bigram.right];
  10045. // if one of the symbols already got merged, skip it.
  10046. if (left_sym.n == 0 || right_sym.n == 0 ||
  10047. left_sym.n + right_sym.n != bigram.size) {
  10048. continue;
  10049. }
  10050. // merge the right sym into the left one
  10051. left_sym.n += right_sym.n;
  10052. right_sym.n = 0;
  10053. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  10054. // remove the right sym from the chain
  10055. left_sym.next = right_sym.next;
  10056. if (right_sym.next >= 0) {
  10057. symbols[right_sym.next].prev = bigram.left;
  10058. }
  10059. // find more substitutions
  10060. try_add_bigram(left_sym.prev, bigram.left);
  10061. try_add_bigram(bigram.left, left_sym.next);
  10062. }
  10063. for (int i = 0; i != -1; i = symbols[i].next) {
  10064. auto & symbol = symbols[i];
  10065. resegment(symbol, output);
  10066. }
  10067. }
  10068. private:
  10069. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  10070. auto text = std::string(symbol.text, symbol.n);
  10071. auto token = vocab.token_to_id.find(text);
  10072. // Do we need to support is_unused?
  10073. if (token != vocab.token_to_id.end()) {
  10074. output.push_back((*token).second);
  10075. return;
  10076. }
  10077. const auto p = rev_merge.find(text);
  10078. if (p == rev_merge.end()) {
  10079. // output any symbols that did not form tokens as bytes.
  10080. output.reserve(output.size() + symbol.n);
  10081. for (int j = 0; j < (int)symbol.n; ++j) {
  10082. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  10083. output.push_back(token_id);
  10084. }
  10085. return;
  10086. }
  10087. resegment(symbols[p->second.first], output);
  10088. resegment(symbols[p->second.second], output);
  10089. }
  10090. void try_add_bigram(int left, int right) {
  10091. if (left == -1 || right == -1) {
  10092. return;
  10093. }
  10094. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  10095. auto token = vocab.token_to_id.find(text);
  10096. if (token == vocab.token_to_id.end()) {
  10097. return;
  10098. }
  10099. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  10100. return;
  10101. }
  10102. const auto & tok_data = vocab.id_to_token[(*token).second];
  10103. llm_bigram_spm bigram;
  10104. bigram.left = left;
  10105. bigram.right = right;
  10106. bigram.score = tok_data.score;
  10107. bigram.size = text.size();
  10108. work_queue.push(bigram);
  10109. // Do we need to support is_unused?
  10110. rev_merge[text] = std::make_pair(left, right);
  10111. }
  10112. const llama_vocab & vocab;
  10113. std::vector<llm_symbol> symbols;
  10114. llm_bigram_spm::queue work_queue;
  10115. std::map<std::string, std::pair<int, int>> rev_merge;
  10116. };
  10117. // BPE tokenizer
  10118. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  10119. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  10120. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  10121. struct llm_bigram_bpe {
  10122. struct comparator {
  10123. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  10124. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  10125. }
  10126. };
  10127. using queue_storage = std::vector<llm_bigram_bpe>;
  10128. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  10129. llm_symbol::index left;
  10130. llm_symbol::index right;
  10131. std::string text;
  10132. int rank;
  10133. size_t size;
  10134. };
  10135. struct llm_tokenizer_bpe {
  10136. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  10137. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10138. int final_prev_index = -1;
  10139. bool ignore_merges = false;
  10140. std::vector<std::string> word_collection;
  10141. switch (vocab.type) {
  10142. case LLAMA_VOCAB_TYPE_BPE:
  10143. switch (vocab.type_pre) {
  10144. case LLAMA_VOCAB_PRE_TYPE_LLAMA3:
  10145. ignore_merges = true;
  10146. word_collection = unicode_regex_split(text, {
  10147. // original regex from tokenizer.json
  10148. //"(?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+",
  10149. // adapted: https://github.com/ggerganov/llama.cpp/pull/6920#issuecomment-2080233989
  10150. "(?:'[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+",
  10151. });
  10152. break;
  10153. case LLAMA_VOCAB_PRE_TYPE_DBRX:
  10154. word_collection = unicode_regex_split(text, {
  10155. // same as llama3
  10156. "(?:'[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+",
  10157. });
  10158. break;
  10159. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_LLM:
  10160. word_collection = unicode_regex_split(text, {
  10161. "[\r\n]",
  10162. "\\s?[A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-ՖႠ-ჅᎠ-Ᏽᏸ-ᏽᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꭰ-ꮿff-stﬓ-ﬗA-Za-z𐐀-𐑏𐒰-𐓓𐓘-𐓻𐲀-𐲲𐳀-𐳲𑢠-𑣟𞤀-𞥃]+",
  10163. "\\s?[!-/:-~!-/:-~‘-‟ -。]+",
  10164. "\\s+$",
  10165. "[一-龥ࠀ-一가-퟿]+",
  10166. "\\p{N}+",
  10167. });
  10168. break;
  10169. case LLAMA_VOCAB_PRE_TYPE_DEEPSEEK_CODER:
  10170. word_collection = unicode_regex_split(text, {
  10171. "[\r\n]",
  10172. "\\s?\\p{L}+",
  10173. "\\s?\\p{P}+",
  10174. "[一-龥ࠀ-一가-퟿]+",
  10175. "\\p{N}",
  10176. });
  10177. break;
  10178. case LLAMA_VOCAB_PRE_TYPE_FALCON:
  10179. word_collection = unicode_regex_split(text, {
  10180. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  10181. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10182. "[0-9][0-9][0-9]",
  10183. });
  10184. break;
  10185. case LLAMA_VOCAB_PRE_TYPE_MPT:
  10186. // TODO: MPT pre-tokenization regexes are unknown
  10187. // the following are close, but not exact. run the following:
  10188. // ./bin/test-tokenizer-0 ../models/ggml-vocab-mpt.gguf
  10189. GGML_ASSERT("MPT pre-tokenization regexes are unknown - fixes needed");
  10190. word_collection = unicode_regex_split(text, {
  10191. "\\s?\\p{L}+",
  10192. "\\s?\\p{P}+",
  10193. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10194. });
  10195. break;
  10196. case LLAMA_VOCAB_PRE_TYPE_STARCODER:
  10197. case LLAMA_VOCAB_PRE_TYPE_REFACT:
  10198. case LLAMA_VOCAB_PRE_TYPE_COMMAND_R:
  10199. word_collection = unicode_regex_split(text, {
  10200. "\\p{N}",
  10201. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10202. });
  10203. break;
  10204. case LLAMA_VOCAB_PRE_TYPE_GPT2:
  10205. case LLAMA_VOCAB_PRE_TYPE_OLMO:
  10206. word_collection = unicode_regex_split(text, {
  10207. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10208. });
  10209. break;
  10210. case LLAMA_VOCAB_PRE_TYPE_STABLELM2:
  10211. case LLAMA_VOCAB_PRE_TYPE_QWEN2:
  10212. word_collection = unicode_regex_split(text, {
  10213. // original regex from tokenizer.json
  10214. // "(?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+"
  10215. "(?:'[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+",
  10216. });
  10217. break;
  10218. default:
  10219. // default regex for BPE tokenization pre-processing
  10220. word_collection = unicode_regex_split(text, {
  10221. "[\\p{P}\\$\\+<=>\\^~\\|]+",
  10222. "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)",
  10223. "\\p{N}+",
  10224. "[0-9][0-9][0-9]",
  10225. });
  10226. break;
  10227. }
  10228. break;
  10229. default:
  10230. GGML_ASSERT(false);
  10231. break;
  10232. }
  10233. symbols_final.clear();
  10234. for (auto & word : word_collection) {
  10235. work_queue = llm_bigram_bpe::queue();
  10236. symbols.clear();
  10237. int index = 0;
  10238. size_t offset = 0;
  10239. if (ignore_merges && vocab.token_to_id.find(word) != vocab.token_to_id.end()) {
  10240. symbols.emplace_back(llm_symbol{-1, -1, word.c_str(), word.size()});
  10241. offset = word.size();
  10242. }
  10243. while (offset < word.size()) {
  10244. llm_symbol sym;
  10245. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  10246. sym.text = word.c_str() + offset;
  10247. sym.n = char_len;
  10248. offset += sym.n;
  10249. sym.prev = index - 1;
  10250. sym.next = offset == word.size() ? -1 : index + 1;
  10251. index++;
  10252. symbols.emplace_back(sym);
  10253. }
  10254. for (size_t i = 1; i < symbols.size(); ++i) {
  10255. add_new_bigram(i - 1, i);
  10256. }
  10257. // build token(s)
  10258. while (!work_queue.empty()) {
  10259. auto bigram = work_queue.top();
  10260. work_queue.pop();
  10261. auto & left_symbol = symbols[bigram.left];
  10262. auto & right_symbol = symbols[bigram.right];
  10263. if (left_symbol.n == 0 || right_symbol.n == 0) {
  10264. continue;
  10265. }
  10266. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  10267. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  10268. if (left_token + right_token != bigram.text) {
  10269. continue; // Skip this bigram if it's outdated
  10270. }
  10271. // merge the right sym into the left one
  10272. left_symbol.n += right_symbol.n;
  10273. right_symbol.n = 0;
  10274. // remove the right sym from the chain
  10275. left_symbol.next = right_symbol.next;
  10276. if (right_symbol.next >= 0) {
  10277. symbols[right_symbol.next].prev = bigram.left;
  10278. }
  10279. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  10280. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  10281. }
  10282. // add the finished tokens to the final list keeping correct order for next and prev
  10283. for (auto & sym : symbols) {
  10284. if (sym.n > 0) {
  10285. sym.prev = final_prev_index;
  10286. sym.next = -1;
  10287. if (final_prev_index != -1) {
  10288. symbols_final[final_prev_index].next = symbols_final.size();
  10289. }
  10290. symbols_final.emplace_back(sym);
  10291. final_prev_index = symbols_final.size() - 1;
  10292. }
  10293. }
  10294. }
  10295. symbols = symbols_final;
  10296. if (!symbols.empty()) {
  10297. for (int i = 0; i != -1; i = symbols[i].next) {
  10298. auto & symbol = symbols[i];
  10299. if (symbol.n == 0) {
  10300. continue;
  10301. }
  10302. const std::string str = std::string(symbol.text, symbol.n);
  10303. const auto token = vocab.token_to_id.find(str);
  10304. if (token == vocab.token_to_id.end()) {
  10305. for (auto j = str.begin(); j != str.end(); ++j) {
  10306. std::string byte_str(1, *j);
  10307. auto token_multibyte = vocab.token_to_id.find(byte_str);
  10308. if (token_multibyte == vocab.token_to_id.end()) {
  10309. throw std::runtime_error("ERROR: byte not found in vocab");
  10310. }
  10311. output.push_back((*token_multibyte).second);
  10312. }
  10313. } else {
  10314. output.push_back((*token).second);
  10315. }
  10316. }
  10317. }
  10318. }
  10319. private:
  10320. void add_new_bigram(int left, int right) {
  10321. if (left == -1 || right == -1) {
  10322. return;
  10323. }
  10324. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  10325. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  10326. int rank_found = -1;
  10327. rank_found = vocab.find_bpe_rank(left_token, right_token);
  10328. if (rank_found < 0) {
  10329. return;
  10330. }
  10331. llm_bigram_bpe bigram;
  10332. bigram.left = left;
  10333. bigram.right = right;
  10334. bigram.text = left_token + right_token;
  10335. bigram.size = left_token.size() + right_token.size();
  10336. bigram.rank = rank_found;
  10337. work_queue.push(bigram);
  10338. }
  10339. const llama_vocab & vocab;
  10340. std::vector<llm_symbol> symbols;
  10341. std::vector<llm_symbol> symbols_final;
  10342. llm_bigram_bpe::queue work_queue;
  10343. };
  10344. struct llm_tokenizer_wpm {
  10345. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  10346. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  10347. auto * token_map = &vocab.token_to_id;
  10348. // normalize and split by whitespace
  10349. std::vector<std::string> words = preprocess(text);
  10350. // bos token prepended already
  10351. // find the longest tokens that form the words
  10352. for (const std::string &word : words) {
  10353. // skip empty words
  10354. if (word.size() == 0) {
  10355. continue;
  10356. }
  10357. // prepend phantom space
  10358. std::string word1 = "\xe2\x96\x81" + word;
  10359. int n = word1.size();
  10360. // we're at the start of a new word
  10361. int i = 0;
  10362. bool match_any = false;
  10363. // move through character position in word
  10364. while (i < n) {
  10365. // loop through possible match length
  10366. bool match = false;
  10367. for (int j = n; j > i; j--) {
  10368. auto it = token_map->find(word1.substr(i, j - i));
  10369. if (it != token_map->end()) {
  10370. output.push_back(it->second);
  10371. match = true;
  10372. match_any = true;
  10373. i = j;
  10374. break;
  10375. }
  10376. }
  10377. // must be an unknown character
  10378. if (!match) {
  10379. i++;
  10380. }
  10381. }
  10382. // we didn't find any matches for this word
  10383. if (!match_any) {
  10384. output.push_back(vocab.special_unk_id);
  10385. }
  10386. }
  10387. }
  10388. std::vector<std::string> preprocess(const std::string & text) {
  10389. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  10390. // strip accents, strip control, uniformize whitespace,
  10391. // to lowercase, pad chinese characters, pad punctuation
  10392. std::string new_str = "";
  10393. for (uint32_t code : cpts_nfd) {
  10394. const codepoint_flags flags = unicode_cpt_flags(code);
  10395. if (flags.is_accent_mark || flags.is_control) {
  10396. continue;
  10397. }
  10398. code = unicode_tolower(code);
  10399. if (flags.is_separator || flags.is_whitespace) { //####FIXME: is_separator ?
  10400. code = ' ';
  10401. }
  10402. std::string s = unicode_cpt_to_utf8(code);
  10403. if (flags.is_punctuation || is_ascii_punct(code) || is_chinese_char(code)) {
  10404. new_str += " ";
  10405. new_str += s;
  10406. new_str += " ";
  10407. } else {
  10408. new_str += s;
  10409. }
  10410. }
  10411. // split by whitespace
  10412. uint64_t l = 0;
  10413. uint64_t r = 0;
  10414. std::vector<std::string> words;
  10415. while (r < new_str.size()) {
  10416. // if is whitespace
  10417. if (isspace(new_str[r], std::locale::classic())) {
  10418. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  10419. l = r + 1;
  10420. r = l;
  10421. } else {
  10422. r += 1;
  10423. }
  10424. }
  10425. if (r > l) {
  10426. words.push_back(new_str.substr(l, (r - l)));
  10427. }
  10428. return words;
  10429. }
  10430. bool is_ascii_punct(uint32_t code) {
  10431. if (code > 0xFF) {
  10432. return false;
  10433. }
  10434. auto c = char(static_cast<unsigned char>(code));
  10435. return ispunct(c, std::locale::classic());
  10436. }
  10437. bool is_chinese_char(uint32_t cpt) {
  10438. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  10439. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  10440. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  10441. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  10442. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  10443. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  10444. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  10445. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  10446. (cpt >= 0x3000 && cpt <= 0x303F) ||
  10447. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  10448. return true; // NOLINT
  10449. }
  10450. return false;
  10451. }
  10452. const llama_vocab & vocab;
  10453. };
  10454. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  10455. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  10456. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  10457. } FRAGMENT_BUFFER_VARIANT_TYPE;
  10458. struct fragment_buffer_variant {
  10459. fragment_buffer_variant(llama_vocab::id _token)
  10460. :
  10461. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  10462. token(_token),
  10463. raw_text(_dummy),
  10464. offset(0),
  10465. length(0) {}
  10466. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  10467. :
  10468. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  10469. token((llama_vocab::id) - 1),
  10470. raw_text(_raw_text),
  10471. offset(_offset),
  10472. length(_length){
  10473. GGML_ASSERT(_offset >= 0);
  10474. GGML_ASSERT(_length >= 1);
  10475. GGML_ASSERT(offset + length <= raw_text.length());
  10476. }
  10477. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  10478. const llama_vocab::id token;
  10479. const std::string _dummy;
  10480. const std::string & raw_text;
  10481. const uint64_t offset;
  10482. const uint64_t length;
  10483. };
  10484. // #define PRETOKENIZERDEBUG
  10485. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  10486. // for each special token
  10487. for (const auto & st: vocab.special_tokens_cache) {
  10488. const auto & special_token = st.first;
  10489. const auto & special_id = st.second;
  10490. // for each text fragment
  10491. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  10492. while (it != buffer.end()) {
  10493. auto & fragment = (*it);
  10494. // if a fragment is text ( not yet processed )
  10495. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  10496. auto * raw_text = &(fragment.raw_text);
  10497. auto raw_text_base_offset = fragment.offset;
  10498. auto raw_text_base_length = fragment.length;
  10499. // loop over the text
  10500. while (true) {
  10501. // find the first occurrence of a given special token in this fragment
  10502. // passing offset argument only limit the "search area" but match coordinates
  10503. // are still relative to the source full raw_text
  10504. auto match = raw_text->find(special_token, raw_text_base_offset);
  10505. // no occurrences found, stop processing this fragment for a given special token
  10506. if (match == std::string::npos) break;
  10507. // check if match is within bounds of offset <-> length
  10508. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  10509. #ifdef PRETOKENIZERDEBUG
  10510. 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());
  10511. #endif
  10512. auto source = std::distance(buffer.begin(), it);
  10513. // if match is further than base offset
  10514. // then we have some text to the left of it
  10515. if (match > raw_text_base_offset) {
  10516. // left
  10517. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  10518. const int64_t left_reminder_length = match - raw_text_base_offset;
  10519. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  10520. #ifdef PRETOKENIZERDEBUG
  10521. 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());
  10522. #endif
  10523. it++;
  10524. }
  10525. // special token
  10526. buffer.emplace_after(it, special_id);
  10527. it++;
  10528. // right
  10529. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  10530. const int64_t right_reminder_offset = match + special_token.length();
  10531. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  10532. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  10533. #ifdef PRETOKENIZERDEBUG
  10534. 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());
  10535. #endif
  10536. it++;
  10537. if (source == 0) {
  10538. buffer.erase_after(buffer.before_begin());
  10539. } else {
  10540. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  10541. }
  10542. // repeat for the right side
  10543. raw_text_base_offset = right_reminder_offset;
  10544. raw_text_base_length = right_reminder_length;
  10545. #ifdef PRETOKENIZERDEBUG
  10546. 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());
  10547. #endif
  10548. } else {
  10549. if (source == 0) {
  10550. buffer.erase_after(buffer.before_begin());
  10551. } else {
  10552. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  10553. }
  10554. break;
  10555. }
  10556. }
  10557. }
  10558. it++;
  10559. }
  10560. }
  10561. }
  10562. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special) {
  10563. std::vector<llama_vocab::id> output;
  10564. std::forward_list<fragment_buffer_variant> fragment_buffer;
  10565. if (!raw_text.empty()) {
  10566. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  10567. if (parse_special) tokenizer_st_partition(vocab, fragment_buffer);
  10568. }
  10569. switch (vocab.type) {
  10570. case LLAMA_VOCAB_TYPE_SPM:
  10571. {
  10572. // OG tokenizer behavior:
  10573. //
  10574. // tokenizer.encode('', add_special_tokens=True) returns [1]
  10575. // tokenizer.encode('', add_special_tokens=False) returns []
  10576. if (add_special && vocab.special_add_bos != 0) {
  10577. GGML_ASSERT(vocab.special_bos_id != -1);
  10578. output.push_back(vocab.special_bos_id);
  10579. }
  10580. for (const auto & fragment : fragment_buffer) {
  10581. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  10582. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  10583. // TODO: It's likely possible to get rid of this string copy entirely
  10584. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  10585. // and passing 'add space prefix' as bool argument
  10586. //
  10587. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  10588. if (&fragment == &fragment_buffer.front()) {
  10589. if (vocab.add_space_prefix) {
  10590. raw_text = " " + raw_text; // prefix with space if the first token is not special
  10591. }
  10592. }
  10593. #ifdef PRETOKENIZERDEBUG
  10594. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  10595. #endif
  10596. llm_tokenizer_spm tokenizer(vocab);
  10597. llama_escape_whitespace(raw_text);
  10598. tokenizer.tokenize(raw_text, output);
  10599. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  10600. output.push_back(fragment.token);
  10601. }
  10602. }
  10603. if (add_special && vocab.special_add_bos != 0 && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  10604. LLAMA_LOG_WARN(
  10605. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  10606. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  10607. "Are you sure this is what you want?\n", __FUNCTION__);
  10608. }
  10609. if (add_special && vocab.special_add_eos == 1) {
  10610. GGML_ASSERT(vocab.special_eos_id != -1);
  10611. output.push_back(vocab.special_eos_id);
  10612. }
  10613. } break;
  10614. case LLAMA_VOCAB_TYPE_BPE:
  10615. {
  10616. if (add_special && vocab.special_add_bos != 0) {
  10617. GGML_ASSERT(vocab.special_bos_id != -1);
  10618. output.push_back(vocab.special_bos_id);
  10619. }
  10620. for (const auto & fragment : fragment_buffer) {
  10621. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  10622. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  10623. #ifdef PRETOKENIZERDEBUG
  10624. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  10625. #endif
  10626. llm_tokenizer_bpe tokenizer(vocab);
  10627. tokenizer.tokenize(raw_text, output);
  10628. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  10629. output.push_back(fragment.token);
  10630. }
  10631. }
  10632. if (add_special && vocab.special_add_bos != 0 && output.size() >= 2 && output[1] == vocab.special_bos_id) {
  10633. LLAMA_LOG_WARN(
  10634. "%s: Added a BOS token to the prompt as specified by the model but the prompt "
  10635. "also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. "
  10636. "Are you sure this is what you want?\n", __FUNCTION__);
  10637. }
  10638. if (add_special && vocab.special_add_eos == 1) {
  10639. GGML_ASSERT(vocab.special_add_eos != -1);
  10640. output.push_back(vocab.special_eos_id);
  10641. }
  10642. } break;
  10643. case LLAMA_VOCAB_TYPE_WPM:
  10644. {
  10645. if (add_special) {
  10646. GGML_ASSERT(vocab.special_cls_id != -1);
  10647. output.push_back(vocab.special_cls_id);
  10648. }
  10649. for (const auto & fragment : fragment_buffer) {
  10650. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  10651. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  10652. #ifdef PRETOKENIZERDEBUG
  10653. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  10654. #endif
  10655. llm_tokenizer_wpm tokenizer(vocab);
  10656. tokenizer.tokenize(raw_text, output);
  10657. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  10658. output.push_back(fragment.token);
  10659. }
  10660. }
  10661. if (add_special) {
  10662. GGML_ASSERT(vocab.special_sep_id != -1);
  10663. output.push_back(vocab.special_sep_id);
  10664. }
  10665. } break;
  10666. case LLAMA_VOCAB_TYPE_NONE:
  10667. GGML_ASSERT(false);
  10668. }
  10669. return output;
  10670. }
  10671. //
  10672. // grammar - internal
  10673. //
  10674. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  10675. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  10676. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  10677. const std::string & src,
  10678. llama_partial_utf8 partial_start) {
  10679. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  10680. const char * pos = src.c_str();
  10681. std::vector<uint32_t> code_points;
  10682. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  10683. code_points.reserve(src.size() + 1);
  10684. uint32_t value = partial_start.value;
  10685. int n_remain = partial_start.n_remain;
  10686. // continue previous decode, if applicable
  10687. while (*pos != 0 && n_remain > 0) {
  10688. uint8_t next_byte = static_cast<uint8_t>(*pos);
  10689. if ((next_byte >> 6) != 2) {
  10690. // invalid sequence, abort
  10691. code_points.push_back(0);
  10692. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  10693. }
  10694. value = (value << 6) + (next_byte & 0x3F);
  10695. ++pos;
  10696. --n_remain;
  10697. }
  10698. if (partial_start.n_remain > 0 && n_remain == 0) {
  10699. code_points.push_back(value);
  10700. }
  10701. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  10702. while (*pos != 0) {
  10703. uint8_t first_byte = static_cast<uint8_t>(*pos);
  10704. uint8_t highbits = first_byte >> 4;
  10705. n_remain = lookup[highbits] - 1;
  10706. if (n_remain < 0) {
  10707. // invalid sequence, abort
  10708. code_points.clear();
  10709. code_points.push_back(0);
  10710. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  10711. }
  10712. uint8_t mask = (1 << (7 - n_remain)) - 1;
  10713. value = first_byte & mask;
  10714. ++pos;
  10715. while (*pos != 0 && n_remain > 0) {
  10716. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  10717. ++pos;
  10718. --n_remain;
  10719. }
  10720. if (n_remain == 0) {
  10721. code_points.push_back(value);
  10722. }
  10723. }
  10724. code_points.push_back(0);
  10725. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  10726. }
  10727. // returns true iff pos points to the end of one of the definitions of a rule
  10728. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  10729. switch (pos->type) {
  10730. case LLAMA_GRETYPE_END: return true; // NOLINT
  10731. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  10732. default: return false;
  10733. }
  10734. }
  10735. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  10736. // asserts that pos is pointing to a char range element
  10737. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  10738. const llama_grammar_element * pos,
  10739. const uint32_t chr) {
  10740. bool found = false;
  10741. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  10742. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  10743. do {
  10744. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  10745. // inclusive range, e.g. [a-z]
  10746. found = found || (pos->value <= chr && chr <= pos[1].value);
  10747. pos += 2;
  10748. } else {
  10749. // exact char match, e.g. [a] or "a"
  10750. found = found || pos->value == chr;
  10751. pos += 1;
  10752. }
  10753. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  10754. return std::make_pair(found == is_positive_char, pos);
  10755. }
  10756. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  10757. // range at pos (regular or inverse range)
  10758. // asserts that pos is pointing to a char range element
  10759. static bool llama_grammar_match_partial_char(
  10760. const llama_grammar_element * pos,
  10761. const llama_partial_utf8 partial_utf8) {
  10762. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  10763. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  10764. uint32_t partial_value = partial_utf8.value;
  10765. int n_remain = partial_utf8.n_remain;
  10766. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  10767. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  10768. return false;
  10769. }
  10770. // range of possible code points this partial UTF-8 sequence could complete to
  10771. uint32_t low = partial_value << (n_remain * 6);
  10772. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  10773. if (low == 0) {
  10774. if (n_remain == 2) {
  10775. low = 1 << 11;
  10776. } else if (n_remain == 3) {
  10777. low = 1 << 16;
  10778. }
  10779. }
  10780. do {
  10781. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  10782. // inclusive range, e.g. [a-z]
  10783. if (pos->value <= high && low <= pos[1].value) {
  10784. return is_positive_char;
  10785. }
  10786. pos += 2;
  10787. } else {
  10788. // exact char match, e.g. [a] or "a"
  10789. if (low <= pos->value && pos->value <= high) {
  10790. return is_positive_char;
  10791. }
  10792. pos += 1;
  10793. }
  10794. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  10795. return !is_positive_char;
  10796. }
  10797. // transforms a grammar pushdown stack into N possible stacks, all ending
  10798. // at a character range (terminal element)
  10799. static void llama_grammar_advance_stack(
  10800. const std::vector<std::vector<llama_grammar_element>> & rules,
  10801. const std::vector<const llama_grammar_element *> & stack,
  10802. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  10803. if (stack.empty()) {
  10804. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  10805. new_stacks.emplace_back(stack);
  10806. }
  10807. return;
  10808. }
  10809. const llama_grammar_element * pos = stack.back();
  10810. switch (pos->type) {
  10811. case LLAMA_GRETYPE_RULE_REF: {
  10812. const size_t rule_id = static_cast<size_t>(pos->value);
  10813. const llama_grammar_element * subpos = rules[rule_id].data();
  10814. do {
  10815. // init new stack without the top (pos)
  10816. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  10817. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  10818. // if this rule ref is followed by another element, add that to stack
  10819. new_stack.push_back(pos + 1);
  10820. }
  10821. if (!llama_grammar_is_end_of_sequence(subpos)) {
  10822. // if alternate is nonempty, add to stack
  10823. new_stack.push_back(subpos);
  10824. }
  10825. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  10826. while (!llama_grammar_is_end_of_sequence(subpos)) {
  10827. // scan to end of alternate def
  10828. subpos++;
  10829. }
  10830. if (subpos->type == LLAMA_GRETYPE_ALT) {
  10831. // there's another alternate def of this rule to process
  10832. subpos++;
  10833. } else {
  10834. break;
  10835. }
  10836. } while (true);
  10837. break;
  10838. }
  10839. case LLAMA_GRETYPE_CHAR:
  10840. case LLAMA_GRETYPE_CHAR_NOT:
  10841. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  10842. // only add the stack if it's not a duplicate of one we already have
  10843. new_stacks.emplace_back(stack);
  10844. }
  10845. break;
  10846. default:
  10847. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  10848. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  10849. // those
  10850. GGML_ASSERT(false);
  10851. }
  10852. }
  10853. // takes a set of possible pushdown stacks on a grammar, which are required to
  10854. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  10855. // produces the N possible stacks if the given char is accepted at those
  10856. // positions
  10857. void llama_grammar_accept(
  10858. const std::vector<std::vector<llama_grammar_element>> & rules,
  10859. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  10860. const uint32_t chr,
  10861. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  10862. new_stacks.clear();
  10863. for (const auto & stack : stacks) {
  10864. if (stack.empty()) {
  10865. continue;
  10866. }
  10867. auto match = llama_grammar_match_char(stack.back(), chr);
  10868. if (match.first) {
  10869. const llama_grammar_element * pos = match.second;
  10870. // update top of stack to next element, if any
  10871. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  10872. if (!llama_grammar_is_end_of_sequence(pos)) {
  10873. new_stack.push_back(pos);
  10874. }
  10875. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  10876. }
  10877. }
  10878. }
  10879. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  10880. const std::vector<std::vector<llama_grammar_element>> & rules,
  10881. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  10882. const std::vector<llama_grammar_candidate> & candidates);
  10883. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  10884. const std::vector<std::vector<llama_grammar_element>> & rules,
  10885. const std::vector<const llama_grammar_element *> & stack,
  10886. const std::vector<llama_grammar_candidate> & candidates) {
  10887. std::vector<llama_grammar_candidate> rejects;
  10888. rejects.reserve(candidates.size());
  10889. if (stack.empty()) {
  10890. for (const auto & tok : candidates) {
  10891. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  10892. rejects.push_back(tok);
  10893. }
  10894. }
  10895. return rejects;
  10896. }
  10897. const llama_grammar_element * stack_pos = stack.back();
  10898. std::vector<llama_grammar_candidate> next_candidates;
  10899. next_candidates.reserve(candidates.size());
  10900. for (const auto & tok : candidates) {
  10901. if (*tok.code_points == 0) {
  10902. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  10903. // that cannot satisfy this position in grammar
  10904. if (tok.partial_utf8.n_remain != 0 &&
  10905. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  10906. rejects.push_back(tok);
  10907. }
  10908. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  10909. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  10910. } else {
  10911. rejects.push_back(tok);
  10912. }
  10913. }
  10914. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  10915. // update top of stack to next element, if any
  10916. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  10917. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  10918. stack_after.push_back(stack_pos_after);
  10919. }
  10920. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  10921. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  10922. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  10923. for (const auto & tok : next_rejects) {
  10924. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  10925. }
  10926. return rejects;
  10927. }
  10928. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  10929. const std::vector<std::vector<llama_grammar_element>> & rules,
  10930. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  10931. const std::vector<llama_grammar_candidate> & candidates) {
  10932. GGML_ASSERT(!stacks.empty()); // REVIEW
  10933. if (candidates.empty()) {
  10934. return std::vector<llama_grammar_candidate>();
  10935. }
  10936. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  10937. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  10938. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  10939. }
  10940. return rejects;
  10941. }
  10942. static bool llama_grammar_detect_left_recursion(
  10943. const std::vector<std::vector<llama_grammar_element>> & rules,
  10944. size_t rule_index,
  10945. std::vector<bool> * rules_visited,
  10946. std::vector<bool> * rules_in_progress,
  10947. std::vector<bool> * rules_may_be_empty) {
  10948. if ((*rules_in_progress)[rule_index]) {
  10949. return true;
  10950. }
  10951. (*rules_in_progress)[rule_index] = true;
  10952. const std::vector<llama_grammar_element> & rule = rules[rule_index];
  10953. // First check if the rule might produce the empty string. This could be done combined with the second
  10954. // step but it's more readable as two steps.
  10955. bool at_rule_start = true;
  10956. for (size_t i = 0; i < rule.size(); i++) {
  10957. if (llama_grammar_is_end_of_sequence(&rule[i])) {
  10958. if (at_rule_start) {
  10959. (*rules_may_be_empty)[rule_index] = true;
  10960. break;
  10961. }
  10962. at_rule_start = true;
  10963. } else {
  10964. at_rule_start = false;
  10965. }
  10966. }
  10967. // Second, recurse into leftmost nonterminals (or next-leftmost as long as the previous nonterminal may
  10968. // be empty)
  10969. bool recurse_into_nonterminal = true;
  10970. for (size_t i = 0; i < rule.size(); i++) {
  10971. if (rule[i].type == LLAMA_GRETYPE_RULE_REF && recurse_into_nonterminal) {
  10972. if (llama_grammar_detect_left_recursion(rules, (size_t)rule[i].value, rules_visited, rules_in_progress, rules_may_be_empty)) {
  10973. return true;
  10974. }
  10975. if (!((*rules_may_be_empty)[(size_t)rule[i].value])) {
  10976. recurse_into_nonterminal = false;
  10977. }
  10978. } else if (llama_grammar_is_end_of_sequence(&rule[i])) {
  10979. recurse_into_nonterminal = true;
  10980. } else {
  10981. recurse_into_nonterminal = false;
  10982. }
  10983. }
  10984. (*rules_in_progress)[rule_index] = false;
  10985. (*rules_visited)[rule_index] = true;
  10986. return false;
  10987. }
  10988. //
  10989. // grammar - external
  10990. //
  10991. struct llama_grammar * llama_grammar_init(
  10992. const llama_grammar_element ** rules,
  10993. size_t n_rules,
  10994. size_t start_rule_index) {
  10995. const llama_grammar_element * pos;
  10996. // copy rule definitions into vectors
  10997. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  10998. for (size_t i = 0; i < n_rules; i++) {
  10999. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  11000. vec_rules[i].push_back(*pos);
  11001. }
  11002. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  11003. }
  11004. // Check for left recursion
  11005. std::vector<bool> rules_visited(n_rules);
  11006. std::vector<bool> rules_in_progress(n_rules);
  11007. std::vector<bool> rules_may_be_empty(n_rules);
  11008. for (size_t i = 0; i < n_rules; i++) {
  11009. if (rules_visited[i]) {
  11010. continue;
  11011. }
  11012. if (llama_grammar_detect_left_recursion(vec_rules, i, &rules_visited, &rules_in_progress, &rules_may_be_empty)) {
  11013. throw std::runtime_error(format("unsupported grammar, left recursion detected for nonterminal at index %zu", i));
  11014. }
  11015. }
  11016. // loop over alternates of start rule to build initial stacks
  11017. std::vector<std::vector<const llama_grammar_element *>> stacks;
  11018. pos = vec_rules[start_rule_index].data();
  11019. do {
  11020. std::vector<const llama_grammar_element *> stack;
  11021. if (!llama_grammar_is_end_of_sequence(pos)) {
  11022. // if alternate is nonempty, add to stack
  11023. stack.push_back(pos);
  11024. }
  11025. llama_grammar_advance_stack(vec_rules, stack, stacks);
  11026. while (!llama_grammar_is_end_of_sequence(pos)) {
  11027. // scan to end of alternate def
  11028. pos++;
  11029. }
  11030. if (pos->type == LLAMA_GRETYPE_ALT) {
  11031. // there's another alternate def of this rule to process
  11032. pos++;
  11033. } else {
  11034. break;
  11035. }
  11036. } while (true);
  11037. // Important: vec_rules has to be moved here, not copied, because stacks contains
  11038. // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar
  11039. // then the pointers would be invalidated when the local vec_rules goes out of scope.
  11040. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  11041. }
  11042. void llama_grammar_free(struct llama_grammar * grammar) {
  11043. delete grammar;
  11044. }
  11045. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  11046. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  11047. // redirect elements in stacks to point to new rules
  11048. for (size_t is = 0; is < result->stacks.size(); is++) {
  11049. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  11050. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  11051. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  11052. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  11053. result->stacks[is][ie] = &result->rules[ir0][ir1];
  11054. }
  11055. }
  11056. }
  11057. }
  11058. }
  11059. return result;
  11060. }
  11061. //
  11062. // sampling
  11063. //
  11064. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  11065. if (seed == LLAMA_DEFAULT_SEED) {
  11066. seed = time(NULL);
  11067. }
  11068. ctx->rng.seed(seed);
  11069. }
  11070. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  11071. GGML_ASSERT(candidates->size > 0);
  11072. const int64_t t_start_sample_us = ggml_time_us();
  11073. // Sort the logits in descending order
  11074. if (!candidates->sorted) {
  11075. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  11076. return a.logit > b.logit;
  11077. });
  11078. candidates->sorted = true;
  11079. }
  11080. float max_l = candidates->data[0].logit;
  11081. float cum_sum = 0.0f;
  11082. for (size_t i = 0; i < candidates->size; ++i) {
  11083. float p = expf(candidates->data[i].logit - max_l);
  11084. candidates->data[i].p = p;
  11085. cum_sum += p;
  11086. }
  11087. for (size_t i = 0; i < candidates->size; ++i) {
  11088. candidates->data[i].p /= cum_sum;
  11089. }
  11090. if (ctx) {
  11091. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11092. }
  11093. }
  11094. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  11095. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  11096. // if (k >= (int32_t)candidates->size) {
  11097. // return;
  11098. // }
  11099. const int64_t t_start_sample_us = ggml_time_us();
  11100. if (k <= 0) {
  11101. k = candidates->size;
  11102. }
  11103. k = std::max(k, (int) min_keep);
  11104. k = std::min(k, (int) candidates->size);
  11105. // Sort scores in descending order
  11106. if (!candidates->sorted) {
  11107. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  11108. return a.logit > b.logit;
  11109. };
  11110. if (k <= 128) {
  11111. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  11112. } else {
  11113. constexpr int nbuckets = 128;
  11114. constexpr float bucket_low = -10.0f;
  11115. constexpr float bucket_high = 10.0f;
  11116. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  11117. constexpr float bucker_inter = -bucket_low * bucket_scale;
  11118. std::vector<int> bucket_idx(candidates->size);
  11119. std::vector<int> histo(nbuckets, 0);
  11120. for (int i = 0; i < (int)candidates->size; ++i) {
  11121. const float val = candidates->data[i].logit;
  11122. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  11123. ib = std::max(0, std::min(nbuckets-1, ib));
  11124. bucket_idx[i] = ib;
  11125. ++histo[ib];
  11126. }
  11127. int nhave = 0;
  11128. int ib = nbuckets - 1;
  11129. for ( ; ib >= 0; --ib) {
  11130. nhave += histo[ib];
  11131. if (nhave >= k) break;
  11132. }
  11133. std::vector<llama_token_data> tmp_tokens(nhave);
  11134. auto ptr = tmp_tokens.data();
  11135. std::vector<llama_token_data*> bucket_ptrs;
  11136. bucket_ptrs.reserve(nbuckets - ib);
  11137. for (int j = nbuckets - 1; j >= ib; --j) {
  11138. bucket_ptrs.push_back(ptr);
  11139. ptr += histo[j];
  11140. }
  11141. for (int i = 0; i < (int)candidates->size; ++i) {
  11142. int j = bucket_idx[i];
  11143. if (j >= ib) {
  11144. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  11145. }
  11146. }
  11147. ptr = tmp_tokens.data();
  11148. int ndone = 0;
  11149. for (int j = nbuckets-1; j > ib; --j) {
  11150. std::sort(ptr, ptr + histo[j], comp);
  11151. ptr += histo[j];
  11152. ndone += histo[j];
  11153. }
  11154. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  11155. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  11156. }
  11157. candidates->sorted = true;
  11158. }
  11159. candidates->size = k;
  11160. if (ctx) {
  11161. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11162. }
  11163. }
  11164. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11165. if (p >= 1.0f) {
  11166. return;
  11167. }
  11168. llama_sample_softmax(ctx, candidates);
  11169. const int64_t t_start_sample_us = ggml_time_us();
  11170. // Compute the cumulative probabilities
  11171. float cum_sum = 0.0f;
  11172. size_t last_idx = candidates->size;
  11173. for (size_t i = 0; i < candidates->size; ++i) {
  11174. cum_sum += candidates->data[i].p;
  11175. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  11176. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  11177. if (cum_sum >= p && i + 1 >= min_keep) {
  11178. last_idx = i + 1;
  11179. break;
  11180. }
  11181. }
  11182. // Resize the output vector to keep only the top-p tokens
  11183. candidates->size = last_idx;
  11184. if (ctx) {
  11185. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11186. }
  11187. }
  11188. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11189. if (p <= 0.0f || !candidates->size) {
  11190. return;
  11191. }
  11192. const int64_t t_start_sample_us = ggml_time_us();
  11193. bool min_p_applied = false;
  11194. // if the candidates aren't sorted, try the unsorted implementation first
  11195. if (!candidates->sorted) {
  11196. std::vector<llama_token_data> filtered_tokens;
  11197. float max_logit = -FLT_MAX;
  11198. for (size_t i = 0; i < candidates->size; ++i) {
  11199. max_logit = std::max(max_logit, candidates->data[i].logit);
  11200. }
  11201. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  11202. for (size_t i = 0; i < candidates->size; ++i) {
  11203. if (candidates->data[i].logit >= min_logit) {
  11204. filtered_tokens.push_back(candidates->data[i]);
  11205. }
  11206. }
  11207. // if we have enough values the operation was a success
  11208. if (filtered_tokens.size() >= min_keep) {
  11209. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  11210. candidates->size = filtered_tokens.size();
  11211. min_p_applied = true;
  11212. }
  11213. }
  11214. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  11215. if (!min_p_applied) {
  11216. // Sort the logits in descending order
  11217. if (!candidates->sorted) {
  11218. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  11219. return a.logit > b.logit;
  11220. });
  11221. candidates->sorted = true;
  11222. }
  11223. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  11224. size_t i = 1; // first token always matches
  11225. for (; i < candidates->size; ++i) {
  11226. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  11227. break; // prob too small
  11228. }
  11229. }
  11230. // Resize the output vector to keep only the matching tokens
  11231. candidates->size = i;
  11232. }
  11233. if (ctx) {
  11234. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11235. }
  11236. }
  11237. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  11238. if (z >= 1.0f || candidates->size <= 2) {
  11239. return;
  11240. }
  11241. llama_sample_softmax(nullptr, candidates);
  11242. const int64_t t_start_sample_us = ggml_time_us();
  11243. // Compute the first and second derivatives
  11244. std::vector<float> first_derivatives(candidates->size - 1);
  11245. std::vector<float> second_derivatives(candidates->size - 2);
  11246. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  11247. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  11248. }
  11249. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11250. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  11251. }
  11252. // Calculate absolute value of second derivatives
  11253. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11254. second_derivatives[i] = std::abs(second_derivatives[i]);
  11255. }
  11256. // Normalize the second derivatives
  11257. {
  11258. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  11259. if (second_derivatives_sum > 1e-6f) {
  11260. for (float & value : second_derivatives) {
  11261. value /= second_derivatives_sum;
  11262. }
  11263. } else {
  11264. for (float & value : second_derivatives) {
  11265. value = 1.0f / second_derivatives.size();
  11266. }
  11267. }
  11268. }
  11269. float cum_sum = 0.0f;
  11270. size_t last_idx = candidates->size;
  11271. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  11272. cum_sum += second_derivatives[i];
  11273. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  11274. if (cum_sum > z && i >= min_keep) {
  11275. last_idx = i;
  11276. break;
  11277. }
  11278. }
  11279. // Resize the output vector to keep only the tokens above the tail location
  11280. candidates->size = last_idx;
  11281. if (ctx) {
  11282. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11283. }
  11284. }
  11285. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  11286. // Reference implementation:
  11287. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  11288. if (p >= 1.0f) {
  11289. return;
  11290. }
  11291. // Compute the softmax of logits and calculate entropy
  11292. llama_sample_softmax(nullptr, candidates);
  11293. const int64_t t_start_sample_us = ggml_time_us();
  11294. float entropy = 0.0f;
  11295. for (size_t i = 0; i < candidates->size; ++i) {
  11296. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  11297. }
  11298. // Compute the absolute difference between negative log probability and entropy for each candidate
  11299. std::vector<float> shifted_scores;
  11300. for (size_t i = 0; i < candidates->size; ++i) {
  11301. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  11302. shifted_scores.push_back(shifted_score);
  11303. }
  11304. // Sort tokens based on the shifted_scores and their corresponding indices
  11305. std::vector<size_t> indices(candidates->size);
  11306. std::iota(indices.begin(), indices.end(), 0);
  11307. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  11308. return shifted_scores[a] < shifted_scores[b];
  11309. });
  11310. // Compute the cumulative probabilities
  11311. float cum_sum = 0.0f;
  11312. size_t last_idx = indices.size();
  11313. for (size_t i = 0; i < indices.size(); ++i) {
  11314. size_t idx = indices[i];
  11315. cum_sum += candidates->data[idx].p;
  11316. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  11317. if (cum_sum > p && i >= min_keep - 1) {
  11318. last_idx = i + 1;
  11319. break;
  11320. }
  11321. }
  11322. // Resize the output vector to keep only the locally typical tokens
  11323. std::vector<llama_token_data> new_candidates;
  11324. for (size_t i = 0; i < last_idx; ++i) {
  11325. size_t idx = indices[i];
  11326. new_candidates.push_back(candidates->data[idx]);
  11327. }
  11328. // Replace the data in candidates with the new_candidates data
  11329. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  11330. candidates->size = new_candidates.size();
  11331. candidates->sorted = false;
  11332. if (ctx) {
  11333. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11334. }
  11335. }
  11336. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  11337. const int64_t t_start_sample_us = ggml_time_us();
  11338. // no need to do anything if there is only one (or zero) candidates
  11339. if(candidates_p->size <= 1) {
  11340. return;
  11341. }
  11342. // Calculate maximum possible entropy
  11343. float max_entropy = -logf(1.0f / candidates_p->size);
  11344. llama_sample_softmax(nullptr, candidates_p);
  11345. // Calculate entropy of the softmax probabilities
  11346. float entropy = 0.0f;
  11347. for (size_t i = 0; i < candidates_p->size; ++i) {
  11348. float prob = candidates_p->data[i].p;
  11349. if (prob > 0.0f) { // Ensure no log(0)
  11350. entropy -= prob * logf(prob);
  11351. }
  11352. }
  11353. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  11354. float normalized_entropy = entropy / max_entropy;
  11355. // Map the normalized entropy to the desired temperature range using the power function
  11356. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  11357. #ifdef DEBUG
  11358. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  11359. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  11360. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  11361. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  11362. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  11363. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  11364. #endif
  11365. // Apply the dynamically calculated temperature scaling
  11366. for (size_t i = 0; i < candidates_p->size; ++i) {
  11367. candidates_p->data[i].logit /= dyn_temp;
  11368. }
  11369. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  11370. double max_l_double = candidates_p->data[0].logit;
  11371. double cum_sum_double = 0.0;
  11372. for (size_t i = 0; i < candidates_p->size; ++i) {
  11373. double p = exp(candidates_p->data[i].logit - max_l_double);
  11374. candidates_p->data[i].p = p; // Store the scaled probability
  11375. cum_sum_double += p;
  11376. }
  11377. for (size_t i = 0; i < candidates_p->size; ++i) {
  11378. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  11379. }
  11380. #ifdef DEBUG
  11381. // Print the updated top 25 probabilities after temperature scaling
  11382. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  11383. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  11384. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  11385. }
  11386. #endif
  11387. if (ctx) {
  11388. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11389. }
  11390. }
  11391. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  11392. const int64_t t_start_sample_us = ggml_time_us();
  11393. for (size_t i = 0; i < candidates_p->size; ++i) {
  11394. candidates_p->data[i].logit /= temp;
  11395. }
  11396. if (ctx) {
  11397. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11398. }
  11399. }
  11400. void llama_sample_repetition_penalties(
  11401. struct llama_context * ctx,
  11402. llama_token_data_array * candidates,
  11403. const llama_token * last_tokens,
  11404. size_t penalty_last_n,
  11405. float penalty_repeat,
  11406. float penalty_freq,
  11407. float penalty_present) {
  11408. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  11409. return;
  11410. }
  11411. const int64_t t_start_sample_us = ggml_time_us();
  11412. // Create a frequency map to count occurrences of each token in last_tokens
  11413. std::unordered_map<llama_token, int> token_count;
  11414. for (size_t i = 0; i < penalty_last_n; ++i) {
  11415. token_count[last_tokens[i]]++;
  11416. }
  11417. // Apply frequency and presence penalties to the candidates
  11418. for (size_t i = 0; i < candidates->size; ++i) {
  11419. const auto token_iter = token_count.find(candidates->data[i].id);
  11420. if (token_iter == token_count.end()) {
  11421. continue;
  11422. }
  11423. const int count = token_iter->second;
  11424. // 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.
  11425. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  11426. if (candidates->data[i].logit <= 0) {
  11427. candidates->data[i].logit *= penalty_repeat;
  11428. } else {
  11429. candidates->data[i].logit /= penalty_repeat;
  11430. }
  11431. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  11432. }
  11433. candidates->sorted = false;
  11434. if (ctx) {
  11435. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11436. }
  11437. }
  11438. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  11439. GGML_ASSERT(ctx);
  11440. const int64_t t_start_sample_us = ggml_time_us();
  11441. bool allow_eog = false;
  11442. for (const auto & stack : grammar->stacks) {
  11443. if (stack.empty()) {
  11444. allow_eog = true;
  11445. break;
  11446. }
  11447. }
  11448. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  11449. candidates_decoded.reserve(candidates->size);
  11450. std::vector<llama_grammar_candidate> candidates_grammar;
  11451. candidates_grammar.reserve(candidates->size);
  11452. for (size_t i = 0; i < candidates->size; ++i) {
  11453. const llama_token id = candidates->data[i].id;
  11454. const std::string piece = llama_token_to_piece(ctx, id, false);
  11455. if (llama_token_is_eog(&ctx->model, id)) {
  11456. if (!allow_eog) {
  11457. candidates->data[i].logit = -INFINITY;
  11458. }
  11459. } else if (piece.empty() || piece[0] == 0) {
  11460. candidates->data[i].logit = -INFINITY;
  11461. } else {
  11462. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  11463. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  11464. }
  11465. }
  11466. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  11467. for (const auto & reject : rejects) {
  11468. candidates->data[reject.index].logit = -INFINITY;
  11469. }
  11470. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11471. }
  11472. static void llama_log_softmax(float * array, size_t size) {
  11473. float max_l = *std::max_element(array, array + size);
  11474. float sum = 0.f;
  11475. for (size_t i = 0; i < size; ++i) {
  11476. float p = expf(array[i] - max_l);
  11477. sum += p;
  11478. array[i] = p;
  11479. }
  11480. for (size_t i = 0; i < size; ++i) {
  11481. array[i] = logf(array[i] / sum);
  11482. }
  11483. }
  11484. void llama_sample_apply_guidance(
  11485. struct llama_context * ctx,
  11486. float * logits,
  11487. float * logits_guidance,
  11488. float scale) {
  11489. GGML_ASSERT(ctx);
  11490. const auto t_start_sample_us = ggml_time_us();
  11491. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  11492. llama_log_softmax(logits, n_vocab);
  11493. llama_log_softmax(logits_guidance, n_vocab);
  11494. for (int i = 0; i < n_vocab; ++i) {
  11495. auto & l = logits[i];
  11496. const auto & g = logits_guidance[i];
  11497. l = scale * (l - g) + g;
  11498. }
  11499. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11500. }
  11501. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  11502. GGML_ASSERT(ctx);
  11503. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  11504. int64_t t_start_sample_us;
  11505. t_start_sample_us = ggml_time_us();
  11506. llama_sample_softmax(nullptr, candidates);
  11507. // Estimate s_hat using the most probable m tokens
  11508. float s_hat = 0.0;
  11509. float sum_ti_bi = 0.0;
  11510. float sum_ti_sq = 0.0;
  11511. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  11512. float t_i = logf(float(i + 2) / float(i + 1));
  11513. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  11514. sum_ti_bi += t_i * b_i;
  11515. sum_ti_sq += t_i * t_i;
  11516. }
  11517. s_hat = sum_ti_bi / sum_ti_sq;
  11518. // Compute k from the estimated s_hat and target surprise value
  11519. float epsilon_hat = s_hat - 1;
  11520. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  11521. // Sample the next word X using top-k sampling
  11522. llama_sample_top_k(nullptr, candidates, int(k), 1);
  11523. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11524. llama_token X = llama_sample_token(ctx, candidates);
  11525. t_start_sample_us = ggml_time_us();
  11526. // Compute error as the difference between observed surprise and target surprise value
  11527. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  11528. return candidate.id == X;
  11529. }));
  11530. float observed_surprise = -log2f(candidates->data[X_idx].p);
  11531. float e = observed_surprise - tau;
  11532. // Update mu using the learning rate and error
  11533. *mu = *mu - eta * e;
  11534. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11535. return X;
  11536. }
  11537. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  11538. int64_t t_start_sample_us;
  11539. t_start_sample_us = ggml_time_us();
  11540. llama_sample_softmax(ctx, candidates);
  11541. // Truncate the words with surprise values greater than mu
  11542. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  11543. return -log2f(candidate.p) > *mu;
  11544. }));
  11545. if (candidates->size == 0) {
  11546. candidates->size = 1;
  11547. }
  11548. if (ctx) {
  11549. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11550. }
  11551. // Normalize the probabilities of the remaining words
  11552. llama_sample_softmax(ctx, candidates);
  11553. // Sample the next word X from the remaining words
  11554. llama_token X = llama_sample_token(ctx, candidates);
  11555. t_start_sample_us = ggml_time_us();
  11556. // Compute error as the difference between observed surprise and target surprise value
  11557. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  11558. return candidate.id == X;
  11559. }));
  11560. float observed_surprise = -log2f(candidates->data[X_idx].p);
  11561. float e = observed_surprise - tau;
  11562. // Update mu using the learning rate and error
  11563. *mu = *mu - eta * e;
  11564. if (ctx) {
  11565. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11566. }
  11567. return X;
  11568. }
  11569. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  11570. const int64_t t_start_sample_us = ggml_time_us();
  11571. // Find max element
  11572. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  11573. return a.logit < b.logit;
  11574. });
  11575. llama_token result = max_iter->id;
  11576. if (ctx) {
  11577. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11578. ctx->n_sample++;
  11579. }
  11580. return result;
  11581. }
  11582. llama_token llama_sample_token_with_rng(struct llama_context * ctx, llama_token_data_array * candidates, std::mt19937 & rng) {
  11583. GGML_ASSERT(ctx);
  11584. const int64_t t_start_sample_us = ggml_time_us();
  11585. llama_sample_softmax(nullptr, candidates);
  11586. std::vector<float> probs;
  11587. probs.reserve(candidates->size);
  11588. for (size_t i = 0; i < candidates->size; ++i) {
  11589. probs.push_back(candidates->data[i].p);
  11590. }
  11591. std::discrete_distribution<> dist(probs.begin(), probs.end());
  11592. int idx = dist(rng);
  11593. llama_token result = candidates->data[idx].id;
  11594. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11595. ctx->n_sample++;
  11596. return result;
  11597. }
  11598. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  11599. return llama_sample_token_with_rng(ctx, candidates, ctx->rng);
  11600. }
  11601. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  11602. const int64_t t_start_sample_us = ggml_time_us();
  11603. if (llama_token_is_eog(&ctx->model, token)) {
  11604. for (const auto & stack : grammar->stacks) {
  11605. if (stack.empty()) {
  11606. return;
  11607. }
  11608. }
  11609. GGML_ASSERT(false);
  11610. }
  11611. const std::string piece = llama_token_to_piece(ctx, token, false);
  11612. // Note terminating 0 in decoded string
  11613. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  11614. const auto & code_points = decoded.first;
  11615. std::vector<std::vector<const llama_grammar_element *>> tmp_new_stacks;
  11616. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  11617. llama_grammar_accept(grammar->rules, grammar->stacks, *it, tmp_new_stacks);
  11618. grammar->stacks = tmp_new_stacks;
  11619. }
  11620. grammar->partial_utf8 = decoded.second;
  11621. GGML_ASSERT(!grammar->stacks.empty());
  11622. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11623. }
  11624. //
  11625. // Beam search
  11626. //
  11627. struct llama_beam {
  11628. std::vector<llama_token> tokens;
  11629. float p; // Cumulative beam probability (renormalized relative to all beams)
  11630. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  11631. // Sort beams by probability. In case of ties, prefer beams at eob.
  11632. bool operator<(const llama_beam & rhs) const {
  11633. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  11634. }
  11635. // Shift off first n tokens and discard them.
  11636. void shift_tokens(const size_t n) {
  11637. if (n) {
  11638. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  11639. tokens.resize(tokens.size() - n);
  11640. }
  11641. }
  11642. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  11643. };
  11644. // A struct for calculating logit-related info.
  11645. struct llama_logit_info {
  11646. const float * const logits;
  11647. const int n_vocab;
  11648. const float max_l;
  11649. const float normalizer;
  11650. struct sum_exp {
  11651. float max_l;
  11652. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  11653. };
  11654. llama_logit_info(llama_context * ctx)
  11655. : logits(llama_get_logits(ctx))
  11656. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  11657. , max_l(*std::max_element(logits, logits + n_vocab))
  11658. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  11659. { }
  11660. llama_token_data get_token_data(const llama_token token_id) const {
  11661. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  11662. return {token_id, logits[token_id], p};
  11663. }
  11664. // Return top k token_data by logit.
  11665. std::vector<llama_token_data> top_k(size_t k) {
  11666. std::vector<llama_token_data> min_heap; // min-heap by logit
  11667. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  11668. min_heap.reserve(k_min);
  11669. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  11670. min_heap.push_back(get_token_data(token_id));
  11671. }
  11672. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  11673. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  11674. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  11675. if (min_heap.front().logit < logits[token_id]) {
  11676. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  11677. min_heap.back().id = token_id;
  11678. min_heap.back().logit = logits[token_id];
  11679. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  11680. }
  11681. }
  11682. return min_heap;
  11683. }
  11684. float probability_from_logit(float logit) const {
  11685. return normalizer * std::exp(logit - max_l);
  11686. }
  11687. };
  11688. struct llama_beam_search_data {
  11689. llama_context * ctx;
  11690. size_t n_beams;
  11691. int n_past;
  11692. int n_predict;
  11693. std::vector<llama_beam> beams;
  11694. std::vector<llama_beam> next_beams;
  11695. // Re-calculated on each loop iteration
  11696. size_t common_prefix_length;
  11697. // Used to communicate to/from callback on beams state.
  11698. std::vector<llama_beam_view> beam_views;
  11699. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  11700. : ctx(ctx)
  11701. , n_beams(n_beams)
  11702. , n_past(n_past)
  11703. , n_predict(n_predict)
  11704. , beam_views(n_beams) {
  11705. beams.reserve(n_beams);
  11706. next_beams.reserve(n_beams);
  11707. }
  11708. // Collapse beams to a single beam given by index.
  11709. void collapse_beams(const size_t beam_idx) {
  11710. if (0u < beam_idx) {
  11711. std::swap(beams[0], beams[beam_idx]);
  11712. }
  11713. beams.resize(1);
  11714. }
  11715. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  11716. // The repetitive patterns below reflect the 2 stages of heaps:
  11717. // * Gather elements until the vector is full, then call std::make_heap() on it.
  11718. // * If the heap is full and a new element is found that should be included, pop the
  11719. // least element to the back(), replace it with the new, then push it into the heap.
  11720. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  11721. // Min-heaps use a greater-than comparator.
  11722. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  11723. if (beam.eob) {
  11724. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  11725. if (next_beams.size() < n_beams) {
  11726. next_beams.push_back(std::move(beam));
  11727. if (next_beams.size() == n_beams) {
  11728. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  11729. }
  11730. } else if (next_beams.front().p < beam.p) {
  11731. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  11732. next_beams.back() = std::move(beam);
  11733. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  11734. }
  11735. } else {
  11736. // beam is not at end-of-sentence, so branch with next top_k tokens.
  11737. if (!beam.tokens.empty()) {
  11738. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  11739. }
  11740. llama_logit_info logit_info(ctx);
  11741. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  11742. // Clear the kv slot so that other beams may try different tokens at this position. The llama_decode()
  11743. // call in loop() will conclusively fill in the kv slot once the beams converge at this position.
  11744. llama_kv_cache_seq_rm(ctx, 0, n_past, -1);
  11745. size_t i=0;
  11746. if (next_beams.size() < n_beams) {
  11747. for (; next_beams.size() < n_beams ; ++i) {
  11748. llama_beam next_beam = beam;
  11749. next_beam.tokens.push_back(next_tokens[i].id);
  11750. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  11751. next_beams.push_back(std::move(next_beam));
  11752. }
  11753. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  11754. } else {
  11755. for (; next_beams.front().p == 0.0f ; ++i) {
  11756. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  11757. next_beams.back() = beam;
  11758. next_beams.back().tokens.push_back(next_tokens[i].id);
  11759. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  11760. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  11761. }
  11762. }
  11763. for (; i < n_beams ; ++i) {
  11764. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  11765. if (next_beams.front().p < next_p) {
  11766. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  11767. next_beams.back() = beam;
  11768. next_beams.back().tokens.push_back(next_tokens[i].id);
  11769. next_beams.back().p = next_p;
  11770. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  11771. }
  11772. }
  11773. }
  11774. }
  11775. // Find common_prefix_length based on beams.
  11776. // Requires beams is not empty.
  11777. size_t find_common_prefix_length() {
  11778. size_t common_prefix_length = beams[0].tokens.size();
  11779. for (size_t i = 1 ; i < beams.size() ; ++i) {
  11780. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  11781. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  11782. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  11783. common_prefix_length = j;
  11784. break;
  11785. }
  11786. }
  11787. }
  11788. return common_prefix_length;
  11789. }
  11790. // Construct beams_state to send back to caller via the callback function.
  11791. // Side effect: set common_prefix_length = find_common_prefix_length();
  11792. llama_beams_state get_beams_state(const bool last_call) {
  11793. for (size_t i = 0 ; i < beams.size() ; ++i) {
  11794. beam_views[i] = beams[i].view();
  11795. }
  11796. common_prefix_length = find_common_prefix_length();
  11797. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  11798. }
  11799. // Loop:
  11800. // * while i < n_predict, AND
  11801. // * any of the beams have not yet reached end-of-beam (eob), AND
  11802. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  11803. // (since all other beam probabilities can only decrease)
  11804. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  11805. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  11806. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  11807. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  11808. !beams[top_beam_index()].eob ; ++i) {
  11809. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  11810. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  11811. if (common_prefix_length) {
  11812. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  11813. n_past += common_prefix_length;
  11814. }
  11815. // Zero-out next_beam probabilities to place them last in following min-heap.
  11816. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  11817. for (llama_beam & beam : beams) {
  11818. beam.shift_tokens(common_prefix_length);
  11819. fill_next_beams_by_top_probabilities(beam);
  11820. }
  11821. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  11822. beams.swap(next_beams);
  11823. renormalize_beam_probabilities(beams);
  11824. }
  11825. collapse_beams(top_beam_index());
  11826. callback(callback_data, get_beams_state(true));
  11827. }
  11828. // As beams grow, the cumulative probabilities decrease.
  11829. // Renormalize them to avoid floating point underflow.
  11830. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  11831. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  11832. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  11833. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  11834. }
  11835. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  11836. size_t top_beam_index() {
  11837. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  11838. }
  11839. // Copy (p,eob) for each beam which may have been changed by the callback.
  11840. void update_beams_from_beam_views() {
  11841. for (size_t i = 0 ; i < beams.size() ; ++i) {
  11842. beams[i].p = beam_views[i].p;
  11843. beams[i].eob = beam_views[i].eob;
  11844. }
  11845. }
  11846. };
  11847. void llama_beam_search(llama_context * ctx,
  11848. llama_beam_search_callback_fn_t callback, void * callback_data,
  11849. size_t n_beams, int n_past, int n_predict) {
  11850. assert(ctx);
  11851. const int64_t t_start_sample_us = ggml_time_us();
  11852. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  11853. beam_search_data.loop(callback, callback_data);
  11854. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  11855. ctx->n_sample++;
  11856. }
  11857. //
  11858. // quantization
  11859. //
  11860. struct quantize_state_internal {
  11861. const llama_model & model;
  11862. const llama_model_quantize_params * params;
  11863. int n_attention_wv = 0;
  11864. int n_ffn_down = 0;
  11865. int n_ffn_gate = 0;
  11866. int n_ffn_up = 0;
  11867. int i_attention_wv = 0;
  11868. int i_ffn_down = 0;
  11869. int i_ffn_gate = 0;
  11870. int i_ffn_up = 0;
  11871. int n_k_quantized = 0;
  11872. int n_fallback = 0;
  11873. bool has_imatrix = false;
  11874. // used to figure out if a model shares tok_embd with the output weight
  11875. bool has_output = false;
  11876. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  11877. : model(model)
  11878. , params(params)
  11879. {}
  11880. };
  11881. static void llama_tensor_dequantize_internal(
  11882. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  11883. const size_t nelements, const int nthread
  11884. ) {
  11885. if (output.size() < nelements) {
  11886. output.resize(nelements);
  11887. }
  11888. float * f32_output = (float *) output.data();
  11889. ggml_type_traits_t qtype;
  11890. if (ggml_is_quantized(tensor->type)) {
  11891. qtype = ggml_internal_get_type_traits(tensor->type);
  11892. if (qtype.to_float == NULL) {
  11893. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  11894. }
  11895. } else if (tensor->type != GGML_TYPE_F16 &&
  11896. tensor->type != GGML_TYPE_BF16) {
  11897. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  11898. }
  11899. if (nthread < 2) {
  11900. if (tensor->type == GGML_TYPE_F16) {
  11901. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  11902. } else if (tensor->type == GGML_TYPE_BF16) {
  11903. ggml_bf16_to_fp32_row((ggml_bf16_t *)tensor->data, f32_output, nelements);
  11904. } else if (ggml_is_quantized(tensor->type)) {
  11905. qtype.to_float(tensor->data, f32_output, nelements);
  11906. } else {
  11907. GGML_ASSERT(false); // unreachable
  11908. }
  11909. return;
  11910. }
  11911. size_t block_size;
  11912. if (tensor->type == GGML_TYPE_F16 ||
  11913. tensor->type == GGML_TYPE_BF16) {
  11914. block_size = 1;
  11915. } else {
  11916. block_size = (size_t)ggml_blck_size(tensor->type);
  11917. }
  11918. size_t block_size_bytes = ggml_type_size(tensor->type);
  11919. GGML_ASSERT(nelements % block_size == 0);
  11920. size_t nblocks = nelements / block_size;
  11921. size_t blocks_per_thread = nblocks / nthread;
  11922. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  11923. size_t in_buff_offs = 0;
  11924. size_t out_buff_offs = 0;
  11925. for (int tnum = 0; tnum < nthread; tnum++) {
  11926. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  11927. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  11928. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  11929. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  11930. if (typ == GGML_TYPE_F16) {
  11931. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  11932. } else if (typ == GGML_TYPE_BF16) {
  11933. ggml_bf16_to_fp32_row((ggml_bf16_t *)inbuf, outbuf, nels);
  11934. } else {
  11935. qtype.to_float(inbuf, outbuf, nels);
  11936. }
  11937. };
  11938. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  11939. in_buff_offs += thr_block_bytes;
  11940. out_buff_offs += thr_elems;
  11941. }
  11942. for (auto & w : workers) { w.join(); }
  11943. workers.clear();
  11944. }
  11945. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  11946. const std::string name = ggml_get_name(tensor);
  11947. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11948. const llm_arch arch = qs.model.arch;
  11949. const auto tn = LLM_TN(arch);
  11950. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  11951. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  11952. };
  11953. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  11954. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  11955. if (n_expert > 1) {
  11956. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  11957. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  11958. // for getting the current layer as I initially thought, and we need to resort to parsing the
  11959. // tensor name.
  11960. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  11961. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  11962. }
  11963. if (i_layer < 0 || i_layer >= n_layer) {
  11964. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  11965. }
  11966. }
  11967. return std::make_pair(i_layer, n_layer);
  11968. };
  11969. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  11970. // with the quantization of the output tensor
  11971. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  11972. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  11973. new_type = qs.params->output_tensor_type;
  11974. } else {
  11975. int nx = tensor->ne[0];
  11976. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  11977. new_type = GGML_TYPE_Q8_0;
  11978. }
  11979. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  11980. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  11981. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  11982. new_type = GGML_TYPE_Q5_K;
  11983. }
  11984. else if (new_type != GGML_TYPE_Q8_0) {
  11985. new_type = GGML_TYPE_Q6_K;
  11986. }
  11987. }
  11988. } else if (name == "token_embd.weight") {
  11989. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  11990. new_type = qs.params->token_embedding_type;
  11991. } else {
  11992. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  11993. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  11994. new_type = GGML_TYPE_Q2_K;
  11995. }
  11996. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  11997. new_type = GGML_TYPE_IQ3_S;
  11998. }
  11999. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12000. new_type = GGML_TYPE_IQ3_S;
  12001. }
  12002. }
  12003. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  12004. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  12005. if (name.find("attn_v.weight") != std::string::npos) {
  12006. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  12007. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12008. ++qs.i_attention_wv;
  12009. }
  12010. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  12011. new_type = GGML_TYPE_Q4_K;
  12012. }
  12013. else if (name.find("ffn_down") != std::string::npos) {
  12014. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  12015. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  12016. }
  12017. ++qs.i_ffn_down;
  12018. }
  12019. else if (name.find("attn_output.weight") != std::string::npos) {
  12020. if (qs.model.hparams.n_expert == 8) {
  12021. new_type = GGML_TYPE_Q5_K;
  12022. } else {
  12023. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  12024. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  12025. }
  12026. }
  12027. } else if (name.find("attn_v.weight") != std::string::npos) {
  12028. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  12029. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12030. }
  12031. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  12032. new_type = GGML_TYPE_Q4_K;
  12033. }
  12034. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12035. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  12036. }
  12037. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  12038. new_type = GGML_TYPE_Q4_K;
  12039. }
  12040. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12041. new_type = GGML_TYPE_Q4_K;
  12042. }
  12043. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12044. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12045. }
  12046. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  12047. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  12048. new_type = GGML_TYPE_Q5_K;
  12049. }
  12050. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  12051. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  12052. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  12053. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  12054. (qs.i_attention_wv < qs.n_attention_wv/8 || qs.i_attention_wv >= 7*qs.n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  12055. if (qs.model.type == MODEL_70B) {
  12056. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  12057. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  12058. // nearly negligible increase in model size by quantizing this tensor with more bits:
  12059. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  12060. }
  12061. if (qs.model.hparams.n_expert == 8) {
  12062. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12063. // TODO: explore better strategies
  12064. new_type = GGML_TYPE_Q8_0;
  12065. }
  12066. ++qs.i_attention_wv;
  12067. } else if (name.find("attn_k.weight") != std::string::npos) {
  12068. if (qs.model.hparams.n_expert == 8) {
  12069. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  12070. // TODO: explore better strategies
  12071. new_type = GGML_TYPE_Q8_0;
  12072. }
  12073. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12074. new_type = GGML_TYPE_IQ3_XXS;
  12075. }
  12076. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12077. new_type = GGML_TYPE_IQ2_S;
  12078. }
  12079. } else if (name.find("attn_q.weight") != std::string::npos) {
  12080. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  12081. new_type = GGML_TYPE_IQ3_XXS;
  12082. }
  12083. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  12084. new_type = GGML_TYPE_IQ2_S;
  12085. }
  12086. } else if (name.find("ffn_down") != std::string::npos) {
  12087. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  12088. int i_layer = info.first, n_layer = info.second;
  12089. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12090. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  12091. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  12092. }
  12093. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  12094. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  12095. }
  12096. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  12097. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  12098. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  12099. : GGML_TYPE_Q3_K;
  12100. }
  12101. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  12102. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  12103. new_type = GGML_TYPE_Q4_K;
  12104. }
  12105. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  12106. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  12107. }
  12108. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  12109. if (arch == LLM_ARCH_FALCON) {
  12110. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  12111. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  12112. } else {
  12113. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12114. }
  12115. }
  12116. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  12117. new_type = GGML_TYPE_Q5_K;
  12118. }
  12119. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  12120. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  12121. new_type = GGML_TYPE_Q5_K;
  12122. }
  12123. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  12124. && qs.has_imatrix && i_layer < n_layer/8) {
  12125. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  12126. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  12127. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  12128. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  12129. }
  12130. ++qs.i_ffn_down;
  12131. } else if (name.find("attn_output.weight") != std::string::npos) {
  12132. if (arch != LLM_ARCH_FALCON) {
  12133. if (qs.model.hparams.n_expert == 8) {
  12134. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  12135. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  12136. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  12137. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  12138. new_type = GGML_TYPE_Q5_K;
  12139. }
  12140. } else {
  12141. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  12142. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  12143. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  12144. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  12145. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  12146. }
  12147. } else {
  12148. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  12149. }
  12150. }
  12151. else if (name.find("attn_qkv.weight") != std::string::npos) {
  12152. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  12153. new_type = GGML_TYPE_Q4_K;
  12154. }
  12155. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  12156. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  12157. }
  12158. else if (name.find("ffn_gate") != std::string::npos) {
  12159. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  12160. int i_layer = info.first, n_layer = info.second;
  12161. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12162. new_type = GGML_TYPE_IQ3_XXS;
  12163. }
  12164. ++qs.i_ffn_gate;
  12165. }
  12166. else if (name.find("ffn_up") != std::string::npos) {
  12167. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  12168. int i_layer = info.first, n_layer = info.second;
  12169. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  12170. new_type = GGML_TYPE_IQ3_XXS;
  12171. }
  12172. ++qs.i_ffn_up;
  12173. }
  12174. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12175. //}
  12176. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  12177. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  12178. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  12179. //}
  12180. // This can be used to reduce the size of the Q5_K_S model.
  12181. // The associated PPL increase is fully in line with the size reduction
  12182. //else {
  12183. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  12184. //}
  12185. bool convert_incompatible_tensor = false;
  12186. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  12187. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  12188. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  12189. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  12190. new_type == GGML_TYPE_IQ1_M) {
  12191. int nx = tensor->ne[0];
  12192. int ny = tensor->ne[1];
  12193. if (nx % QK_K != 0) {
  12194. 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));
  12195. convert_incompatible_tensor = true;
  12196. } else {
  12197. ++qs.n_k_quantized;
  12198. }
  12199. }
  12200. if (convert_incompatible_tensor) {
  12201. switch (new_type) {
  12202. case GGML_TYPE_IQ2_XXS:
  12203. case GGML_TYPE_IQ2_XS:
  12204. case GGML_TYPE_IQ2_S:
  12205. case GGML_TYPE_IQ3_XXS:
  12206. case GGML_TYPE_IQ3_S:
  12207. case GGML_TYPE_IQ1_S:
  12208. case GGML_TYPE_IQ1_M:
  12209. case GGML_TYPE_Q2_K:
  12210. case GGML_TYPE_Q3_K:
  12211. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  12212. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  12213. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  12214. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  12215. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  12216. }
  12217. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  12218. ++qs.n_fallback;
  12219. }
  12220. return new_type;
  12221. }
  12222. 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) {
  12223. if (nthread < 2) {
  12224. // single-thread
  12225. size_t new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  12226. if (!ggml_validate_row_data(new_type, new_data, new_size)) {
  12227. throw std::runtime_error("quantized data validation failed");
  12228. }
  12229. return new_size;
  12230. }
  12231. std::mutex mutex;
  12232. int64_t counter = 0;
  12233. size_t new_size = 0;
  12234. bool valid = true;
  12235. auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size,
  12236. nrows, n_per_row, imatrix]() {
  12237. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  12238. size_t local_size = 0;
  12239. while (true) {
  12240. std::unique_lock<std::mutex> lock(mutex);
  12241. int64_t first_row = counter; counter += nrows_per_chunk;
  12242. if (first_row >= nrows) {
  12243. if (local_size > 0) {
  12244. new_size += local_size;
  12245. }
  12246. break;
  12247. }
  12248. lock.unlock();
  12249. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  12250. size_t this_size = ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  12251. local_size += this_size;
  12252. // validate the quantized data
  12253. const size_t row_size = ggml_row_size(new_type, n_per_row);
  12254. void * this_data = (char *) new_data + first_row * row_size;
  12255. if (!ggml_validate_row_data(new_type, this_data, this_size)) {
  12256. std::unique_lock<std::mutex> lock(mutex);
  12257. valid = false;
  12258. break;
  12259. }
  12260. }
  12261. };
  12262. for (int it = 0; it < nthread - 1; ++it) {
  12263. workers.emplace_back(compute);
  12264. }
  12265. compute();
  12266. for (auto & w : workers) { w.join(); }
  12267. workers.clear();
  12268. if (!valid) {
  12269. throw std::runtime_error("quantized data validation failed");
  12270. }
  12271. return new_size;
  12272. }
  12273. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  12274. ggml_type default_type;
  12275. llama_ftype ftype = params->ftype;
  12276. switch (params->ftype) {
  12277. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  12278. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  12279. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  12280. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  12281. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  12282. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  12283. case LLAMA_FTYPE_MOSTLY_BF16: default_type = GGML_TYPE_BF16; break;
  12284. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  12285. // K-quants
  12286. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  12287. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  12288. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  12289. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  12290. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  12291. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  12292. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  12293. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  12294. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  12295. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  12296. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  12297. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  12298. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  12299. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  12300. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  12301. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  12302. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  12303. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  12304. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  12305. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  12306. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  12307. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  12308. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  12309. }
  12310. int nthread = params->nthread;
  12311. if (nthread <= 0) {
  12312. nthread = std::thread::hardware_concurrency();
  12313. }
  12314. // mmap consistently increases speed Linux, and also increases speed on Windows with
  12315. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  12316. #if defined(__linux__) || defined(_WIN32)
  12317. constexpr bool use_mmap = true;
  12318. #else
  12319. constexpr bool use_mmap = false;
  12320. #endif
  12321. llama_model_kv_override * kv_overrides = nullptr;
  12322. if (params->kv_overrides) {
  12323. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  12324. kv_overrides = v->data();
  12325. }
  12326. llama_model_loader ml(fname_inp, use_mmap, /*check_tensors*/ true, kv_overrides);
  12327. ml.init_mappings(false); // no prefetching
  12328. llama_model model;
  12329. llm_load_arch(ml, model);
  12330. llm_load_hparams(ml, model);
  12331. struct quantize_state_internal qs(model, params);
  12332. if (params->only_copy) {
  12333. ftype = model.ftype;
  12334. }
  12335. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  12336. if (params->imatrix) {
  12337. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  12338. if (imatrix_data) {
  12339. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  12340. qs.has_imatrix = true;
  12341. }
  12342. }
  12343. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  12344. struct gguf_context * ctx_out = gguf_init_empty();
  12345. // copy the KV pairs from the input file
  12346. gguf_set_kv (ctx_out, ml.meta);
  12347. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  12348. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  12349. // Remove split metadata
  12350. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  12351. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  12352. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  12353. if (params->kv_overrides) {
  12354. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  12355. for (auto & o : overrides) {
  12356. if (o.key[0] == 0) break;
  12357. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  12358. gguf_set_val_f32(ctx_out, o.key, o.val_f64);
  12359. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  12360. gguf_set_val_i32(ctx_out, o.key, o.val_i64);
  12361. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  12362. gguf_set_val_bool(ctx_out, o.key, o.val_bool);
  12363. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_STR) {
  12364. gguf_set_val_str(ctx_out, o.key, o.val_str);
  12365. } else {
  12366. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  12367. }
  12368. }
  12369. }
  12370. for (int i = 0; i < ml.n_tensors; ++i) {
  12371. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  12372. const std::string name = ggml_get_name(meta);
  12373. // TODO: avoid hardcoded tensor names - use the TN_* constants
  12374. if (name.find("attn_v.weight") != std::string::npos ||
  12375. name.find("attn_qkv.weight") != std::string::npos) {
  12376. ++qs.n_attention_wv;
  12377. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  12378. qs.has_output = true;
  12379. }
  12380. }
  12381. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  12382. // sanity checks
  12383. //
  12384. // - qs.n_attention_wv == 0 for Mamba models
  12385. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  12386. //
  12387. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  12388. size_t total_size_org = 0;
  12389. size_t total_size_new = 0;
  12390. std::vector<std::thread> workers;
  12391. workers.reserve(nthread);
  12392. int idx = 0;
  12393. std::vector<no_init<uint8_t>> read_data;
  12394. std::vector<no_init<uint8_t>> work;
  12395. std::vector<no_init<float>> f32_conv_buf;
  12396. uint16_t n_split = 1;
  12397. // Assume split index is continuous
  12398. if (params->keep_split) {
  12399. for (int i = 0; i < ml.n_tensors; ++i) {
  12400. n_split = std::max(uint16_t(ml.get_weight(i)->idx+1), n_split);
  12401. }
  12402. }
  12403. std::vector<gguf_context*> ctx_outs(n_split, NULL);
  12404. ctx_outs[0] = ctx_out;
  12405. // populate the original tensors so we get an initial meta data
  12406. for (int i = 0; i < ml.n_tensors; ++i) {
  12407. auto weight = ml.get_weight(i);
  12408. uint16_t i_split = params->keep_split ? weight->idx : 0;
  12409. struct ggml_tensor * tensor = weight->tensor;
  12410. if (ctx_outs[i_split] == NULL) {
  12411. ctx_outs[i_split] = gguf_init_empty();
  12412. }
  12413. gguf_add_tensor(ctx_outs[i_split], tensor);
  12414. }
  12415. // Set split info if needed
  12416. if (n_split > 1) {
  12417. for (size_t i = 0; i < ctx_outs.size(); ++i) {
  12418. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_NO).c_str(), i);
  12419. gguf_set_val_u16(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str(), n_split);
  12420. gguf_set_val_i32(ctx_outs[i], ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str(), ml.n_tensors);
  12421. }
  12422. }
  12423. int cur_split = -1;
  12424. std::ofstream fout;
  12425. auto close_ofstream = [&]() {
  12426. // Write metadata and close file handler
  12427. if (fout.is_open()) {
  12428. fout.seekp(0);
  12429. std::vector<uint8_t> data(gguf_get_meta_size(ctx_outs[cur_split]));
  12430. gguf_get_meta_data(ctx_outs[cur_split], data.data());
  12431. fout.write((const char *) data.data(), data.size());
  12432. fout.close();
  12433. }
  12434. };
  12435. auto new_ofstream = [&](int index) {
  12436. cur_split = index;
  12437. GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context");
  12438. std::string fname = fname_out;
  12439. if (params->keep_split) {
  12440. char split_path[PATH_MAX] = {0};
  12441. llama_split_path(split_path, sizeof(split_path), fname_out.c_str(), cur_split, n_split);
  12442. fname = std::string(split_path);
  12443. }
  12444. fout = std::ofstream(fname, std::ios::binary);
  12445. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  12446. const size_t meta_size = gguf_get_meta_size(ctx_outs[cur_split]);
  12447. // placeholder for the meta data
  12448. ::zeros(fout, meta_size);
  12449. };
  12450. const auto tn = LLM_TN(model.arch);
  12451. new_ofstream(0);
  12452. for (int i = 0; i < ml.n_tensors; ++i) {
  12453. auto weight = ml.get_weight(i);
  12454. struct ggml_tensor * tensor = weight->tensor;
  12455. if (weight->idx != cur_split && params->keep_split) {
  12456. close_ofstream();
  12457. new_ofstream(weight->idx);
  12458. }
  12459. const std::string name = ggml_get_name(tensor);
  12460. if (!ml.use_mmap) {
  12461. if (read_data.size() < ggml_nbytes(tensor)) {
  12462. read_data.resize(ggml_nbytes(tensor));
  12463. }
  12464. tensor->data = read_data.data();
  12465. }
  12466. ml.load_data_for(tensor);
  12467. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  12468. ++idx, ml.n_tensors,
  12469. ggml_get_name(tensor),
  12470. llama_format_tensor_shape(tensor).c_str(),
  12471. ggml_type_name(tensor->type));
  12472. // This used to be a regex, but <regex> has an extreme cost to compile times.
  12473. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  12474. // quantize only 2D and 3D tensors (experts)
  12475. quantize &= (ggml_n_dims(tensor) >= 2);
  12476. // do not quantize norm tensors
  12477. quantize &= name.find("_norm.weight") == std::string::npos;
  12478. quantize &= params->quantize_output_tensor || name != "output.weight";
  12479. quantize &= !params->only_copy;
  12480. // do not quantize expert gating tensors
  12481. // NOTE: can't use LLM_TN here because the layer number is not known
  12482. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  12483. // do not quantize positional embeddings and token types (BERT)
  12484. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  12485. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  12486. // do not quantize Mamba's small yet 2D weights
  12487. // NOTE: can't use LLM_TN here because the layer number is not known
  12488. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  12489. quantize &= name.find("ssm_x.weight") == std::string::npos;
  12490. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  12491. enum ggml_type new_type;
  12492. void * new_data;
  12493. size_t new_size;
  12494. if (quantize) {
  12495. new_type = default_type;
  12496. // get more optimal quantization type based on the tensor shape, layer, etc.
  12497. if (!params->pure && ggml_is_quantized(default_type)) {
  12498. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  12499. }
  12500. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  12501. new_type = params->token_embedding_type;
  12502. }
  12503. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  12504. new_type = params->output_tensor_type;
  12505. }
  12506. // If we've decided to quantize to the same type the tensor is already
  12507. // in then there's nothing to do.
  12508. quantize = tensor->type != new_type;
  12509. }
  12510. if (!quantize) {
  12511. new_type = tensor->type;
  12512. new_data = tensor->data;
  12513. new_size = ggml_nbytes(tensor);
  12514. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  12515. } else {
  12516. const int64_t nelements = ggml_nelements(tensor);
  12517. const float * imatrix = nullptr;
  12518. if (imatrix_data) {
  12519. auto it = imatrix_data->find(tensor->name);
  12520. if (it == imatrix_data->end()) {
  12521. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  12522. } else {
  12523. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  12524. imatrix = it->second.data();
  12525. } else {
  12526. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  12527. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  12528. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  12529. // this is a significant error and it may be good idea to abort the process if this happens,
  12530. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  12531. // tok_embd should be ignored in this case, since it always causes this warning
  12532. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  12533. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  12534. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  12535. }
  12536. }
  12537. }
  12538. }
  12539. if ((new_type == GGML_TYPE_IQ2_XXS ||
  12540. new_type == GGML_TYPE_IQ2_XS ||
  12541. new_type == GGML_TYPE_IQ2_S ||
  12542. new_type == GGML_TYPE_IQ1_S ||
  12543. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  12544. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  12545. LLAMA_LOG_ERROR("\n\n============================================================\n");
  12546. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  12547. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  12548. LLAMA_LOG_ERROR("============================================================\n\n");
  12549. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  12550. }
  12551. float * f32_data;
  12552. if (tensor->type == GGML_TYPE_F32) {
  12553. f32_data = (float *) tensor->data;
  12554. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  12555. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  12556. } else {
  12557. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  12558. f32_data = (float *) f32_conv_buf.data();
  12559. }
  12560. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  12561. fflush(stdout);
  12562. if (work.size() < (size_t)nelements * 4) {
  12563. work.resize(nelements * 4); // upper bound on size
  12564. }
  12565. new_data = work.data();
  12566. const int64_t n_per_row = tensor->ne[0];
  12567. const int64_t nrows = tensor->ne[1];
  12568. static const int64_t min_chunk_size = 32 * 512;
  12569. 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);
  12570. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  12571. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  12572. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  12573. // quantize each expert separately since they have different importance matrices
  12574. new_size = 0;
  12575. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  12576. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  12577. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  12578. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  12579. 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);
  12580. }
  12581. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  12582. }
  12583. total_size_org += ggml_nbytes(tensor);
  12584. total_size_new += new_size;
  12585. // update the gguf meta data as we go
  12586. gguf_set_tensor_type(ctx_outs[cur_split], name.c_str(), new_type);
  12587. gguf_set_tensor_data(ctx_outs[cur_split], name.c_str(), new_data, new_size);
  12588. // write tensor data + padding
  12589. fout.write((const char *) new_data, new_size);
  12590. zeros(fout, GGML_PAD(new_size, align) - new_size);
  12591. }
  12592. close_ofstream();
  12593. for (auto & c:ctx_outs) {
  12594. gguf_free(c);
  12595. }
  12596. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  12597. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  12598. if (qs.n_fallback > 0) {
  12599. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  12600. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  12601. }
  12602. }
  12603. static int llama_apply_lora_from_file_internal(
  12604. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  12605. ) {
  12606. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  12607. const int64_t t_start_lora_us = ggml_time_us();
  12608. llama_file fin(path_lora, "rb");
  12609. // verify magic and version
  12610. {
  12611. uint32_t magic = fin.read_u32();
  12612. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  12613. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  12614. return 1;
  12615. }
  12616. uint32_t format_version = fin.read_u32();
  12617. if (format_version != 1) {
  12618. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  12619. return 1;
  12620. }
  12621. }
  12622. int32_t lora_r = fin.read_u32();
  12623. int32_t lora_alpha = fin.read_u32();
  12624. float scaling = scale * (float)lora_alpha / (float)lora_r;
  12625. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  12626. // load base model
  12627. std::unique_ptr<llama_model_loader> ml;
  12628. if (path_base_model) {
  12629. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  12630. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*check_tensors*/ false, /*kv_overrides*/ nullptr));
  12631. ml->init_mappings(/*prefetch*/ false); // no prefetching
  12632. }
  12633. struct tensor_meta {
  12634. std::string name;
  12635. ggml_type type;
  12636. int32_t ne[2];
  12637. size_t offset;
  12638. };
  12639. std::map<std::string, tensor_meta> tensor_meta_map;
  12640. // load all tensor meta
  12641. while (true) {
  12642. if (fin.tell() == fin.size) {
  12643. // eof
  12644. break;
  12645. }
  12646. int32_t n_dims;
  12647. int32_t name_len;
  12648. int32_t ftype;
  12649. fin.read_raw(&n_dims, sizeof(n_dims));
  12650. fin.read_raw(&name_len, sizeof(name_len));
  12651. fin.read_raw(&ftype, sizeof(ftype));
  12652. if (n_dims != 1 && n_dims != 2) {
  12653. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  12654. return 1;
  12655. }
  12656. int32_t ne[2] = { 1, 1 };
  12657. for (int i = 0; i < n_dims; ++i) {
  12658. fin.read_raw(&ne[i], sizeof(ne[i]));
  12659. }
  12660. std::string name;
  12661. {
  12662. GGML_ASSERT(name_len < GGML_MAX_NAME);
  12663. char buf[GGML_MAX_NAME];
  12664. fin.read_raw(buf, name_len);
  12665. name = std::string(buf, name_len);
  12666. }
  12667. // check for lora suffix
  12668. std::string lora_suffix;
  12669. if (name.length() > 6) {
  12670. lora_suffix = name.substr(name.length() - 6);
  12671. }
  12672. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  12673. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  12674. return 1;
  12675. }
  12676. // tensor type
  12677. ggml_type wtype;
  12678. switch (ftype) {
  12679. case 0: wtype = GGML_TYPE_F32; break;
  12680. case 1: wtype = GGML_TYPE_F16; break;
  12681. default:
  12682. {
  12683. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  12684. __func__, ftype);
  12685. return 1;
  12686. }
  12687. }
  12688. // data offset
  12689. size_t offset = fin.tell();
  12690. offset = (offset + 31) & -32;
  12691. // skip tensor data
  12692. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  12693. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  12694. }
  12695. bool warned = false;
  12696. int n_tensors = 0;
  12697. // apply
  12698. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  12699. if (backend_cpu == nullptr) {
  12700. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  12701. return 1;
  12702. }
  12703. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  12704. std::vector<no_init<uint8_t>> read_buf;
  12705. for (const auto & it : model.tensors_by_name) {
  12706. const std::string & base_name = it.first;
  12707. ggml_tensor * model_t = it.second;
  12708. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  12709. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  12710. continue;
  12711. }
  12712. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  12713. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  12714. ggml_init_params lora_init_params = {
  12715. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  12716. /* .mem_buffer */ nullptr,
  12717. /* .no_alloc */ true,
  12718. };
  12719. ggml_context * lora_ctx = ggml_init(lora_init_params);
  12720. if (lora_ctx == nullptr) {
  12721. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  12722. ggml_backend_free(backend_cpu);
  12723. return 1;
  12724. }
  12725. // create tensors
  12726. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  12727. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  12728. ggml_set_name(loraA, metaA.name.c_str());
  12729. ggml_set_name(loraB, metaB.name.c_str());
  12730. ggml_tensor * base_t;
  12731. if (ml) {
  12732. if (!ml->get_tensor_meta(base_name.c_str())) {
  12733. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  12734. return 1;
  12735. }
  12736. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  12737. } else {
  12738. base_t = ggml_dup_tensor(lora_ctx, model_t);
  12739. }
  12740. ggml_set_name(base_t, base_name.c_str());
  12741. // allocate in backend buffer
  12742. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  12743. if (lora_buf == nullptr) {
  12744. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  12745. return 1;
  12746. }
  12747. // load tensor data
  12748. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  12749. read_buf.resize(ggml_nbytes(tensor));
  12750. fin.seek(tensor_meta.offset, SEEK_SET);
  12751. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  12752. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  12753. };
  12754. load_tensor(metaA, loraA);
  12755. load_tensor(metaB, loraB);
  12756. // load base model tensor data
  12757. if (ml) {
  12758. ml->load_data_for(base_t);
  12759. } else {
  12760. ggml_backend_tensor_copy(model_t, base_t);
  12761. }
  12762. if (ggml_is_quantized(base_t->type) && !warned) {
  12763. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  12764. "use a f16 or f32 base model with --lora-base\n", __func__);
  12765. warned = true;
  12766. }
  12767. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  12768. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  12769. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  12770. ggml_free(lora_ctx);
  12771. ggml_backend_buffer_free(lora_buf);
  12772. ggml_backend_free(backend_cpu);
  12773. return 1;
  12774. }
  12775. auto build_lora_graph = [&]() {
  12776. // w = w + BA*s
  12777. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  12778. ggml_set_name(BA, "BA");
  12779. if (scaling != 1.0f) {
  12780. BA = ggml_scale(lora_ctx, BA, scaling);
  12781. ggml_set_name(BA, "BA_scaled");
  12782. }
  12783. ggml_tensor * r;
  12784. r = ggml_add_inplace(lora_ctx, base_t, BA);
  12785. ggml_set_name(r, "r_add");
  12786. if (base_t->type != model_t->type) {
  12787. // convert the result to the model type
  12788. r = ggml_cast(lora_ctx, r, model_t->type);
  12789. ggml_set_name(r, "r_cast");
  12790. }
  12791. return r;
  12792. };
  12793. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  12794. ggml_tensor * r = build_lora_graph();
  12795. ggml_build_forward_expand(gf, r);
  12796. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  12797. if (graph_buf == nullptr) {
  12798. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  12799. ggml_free(lora_ctx);
  12800. ggml_backend_buffer_free(lora_buf);
  12801. ggml_backend_free(backend_cpu);
  12802. return 1;
  12803. }
  12804. ggml_backend_graph_compute(backend_cpu, gf);
  12805. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  12806. #if 0
  12807. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  12808. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  12809. // sched compute
  12810. ggml_build_forward_expand(gf, build_graph());
  12811. ggml_backend_sched_init_measure(sched, gf);
  12812. // create the graph again, since the previous one was destroyed by the measure
  12813. ggml_graph_clear(gf);
  12814. ggml_build_forward_expand(gf, build_graph());
  12815. ggml_backend_sched_graph_compute(sched, gf);
  12816. ggml_backend_sched_free(sched);
  12817. #endif
  12818. ggml_backend_buffer_free(lora_buf);
  12819. ggml_backend_buffer_free(graph_buf);
  12820. ggml_free(lora_ctx);
  12821. n_tensors++;
  12822. if (n_tensors % 4 == 0) {
  12823. LLAMA_LOG_INFO(".");
  12824. }
  12825. }
  12826. ggml_backend_free(backend_cpu);
  12827. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  12828. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  12829. return 0;
  12830. }
  12831. //
  12832. // interface implementation
  12833. //
  12834. struct llama_model_params llama_model_default_params() {
  12835. struct llama_model_params result = {
  12836. /*.n_gpu_layers =*/ 0,
  12837. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  12838. /*.main_gpu =*/ 0,
  12839. /*.tensor_split =*/ nullptr,
  12840. /*.rpc_servers =*/ nullptr,
  12841. /*.progress_callback =*/ nullptr,
  12842. /*.progress_callback_user_data =*/ nullptr,
  12843. /*.kv_overrides =*/ nullptr,
  12844. /*.vocab_only =*/ false,
  12845. /*.use_mmap =*/ true,
  12846. /*.use_mlock =*/ false,
  12847. /*.check_tensors =*/ false,
  12848. };
  12849. #ifdef GGML_USE_METAL
  12850. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  12851. result.n_gpu_layers = 999;
  12852. #endif
  12853. return result;
  12854. }
  12855. struct llama_context_params llama_context_default_params() {
  12856. struct llama_context_params result = {
  12857. /*.seed =*/ LLAMA_DEFAULT_SEED,
  12858. /*.n_ctx =*/ 512,
  12859. /*.n_batch =*/ 2048,
  12860. /*.n_ubatch =*/ 512,
  12861. /*.n_seq_max =*/ 1,
  12862. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  12863. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  12864. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  12865. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  12866. /*.rope_freq_base =*/ 0.0f,
  12867. /*.rope_freq_scale =*/ 0.0f,
  12868. /*.yarn_ext_factor =*/ -1.0f,
  12869. /*.yarn_attn_factor =*/ 1.0f,
  12870. /*.yarn_beta_fast =*/ 32.0f,
  12871. /*.yarn_beta_slow =*/ 1.0f,
  12872. /*.yarn_orig_ctx =*/ 0,
  12873. /*.defrag_thold =*/ -1.0f,
  12874. /*.cb_eval =*/ nullptr,
  12875. /*.cb_eval_user_data =*/ nullptr,
  12876. /*.type_k =*/ GGML_TYPE_F16,
  12877. /*.type_v =*/ GGML_TYPE_F16,
  12878. /*.logits_all =*/ false,
  12879. /*.embeddings =*/ false,
  12880. /*.offload_kqv =*/ true,
  12881. /*.flash_attn =*/ false,
  12882. /*.abort_callback =*/ nullptr,
  12883. /*.abort_callback_data =*/ nullptr,
  12884. };
  12885. return result;
  12886. }
  12887. struct llama_model_quantize_params llama_model_quantize_default_params() {
  12888. struct llama_model_quantize_params result = {
  12889. /*.nthread =*/ 0,
  12890. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  12891. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  12892. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  12893. /*.allow_requantize =*/ false,
  12894. /*.quantize_output_tensor =*/ true,
  12895. /*.only_copy =*/ false,
  12896. /*.pure =*/ false,
  12897. /*.keep_split =*/ false,
  12898. /*.imatrix =*/ nullptr,
  12899. /*.kv_overrides =*/ nullptr,
  12900. };
  12901. return result;
  12902. }
  12903. size_t llama_max_devices(void) {
  12904. #if defined(GGML_USE_RPC)
  12905. return GGML_RPC_MAX_SERVERS;
  12906. #elif defined(GGML_USE_METAL)
  12907. return 1;
  12908. #elif defined(GGML_USE_CUDA)
  12909. return GGML_CUDA_MAX_DEVICES;
  12910. #elif defined(GGML_USE_SYCL)
  12911. return GGML_SYCL_MAX_DEVICES;
  12912. #elif defined(GGML_USE_VULKAN)
  12913. return GGML_VK_MAX_DEVICES;
  12914. #else
  12915. return 1;
  12916. #endif
  12917. }
  12918. bool llama_supports_mmap(void) {
  12919. return llama_mmap::SUPPORTED;
  12920. }
  12921. bool llama_supports_mlock(void) {
  12922. return llama_mlock::SUPPORTED;
  12923. }
  12924. bool llama_supports_gpu_offload(void) {
  12925. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  12926. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_RPC)
  12927. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  12928. return true;
  12929. #else
  12930. return false;
  12931. #endif
  12932. }
  12933. void llama_backend_init(void) {
  12934. ggml_time_init();
  12935. // needed to initialize f16 tables
  12936. {
  12937. struct ggml_init_params params = { 0, NULL, false };
  12938. struct ggml_context * ctx = ggml_init(params);
  12939. ggml_free(ctx);
  12940. }
  12941. }
  12942. void llama_numa_init(enum ggml_numa_strategy numa) {
  12943. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  12944. ggml_numa_init(numa);
  12945. }
  12946. }
  12947. void llama_backend_free(void) {
  12948. ggml_quantize_free();
  12949. }
  12950. int64_t llama_time_us(void) {
  12951. return ggml_time_us();
  12952. }
  12953. struct llama_model * llama_load_model_from_file(
  12954. const char * path_model,
  12955. struct llama_model_params params) {
  12956. ggml_time_init();
  12957. llama_model * model = new llama_model;
  12958. unsigned cur_percentage = 0;
  12959. if (params.progress_callback == NULL) {
  12960. params.progress_callback_user_data = &cur_percentage;
  12961. params.progress_callback = [](float progress, void * ctx) {
  12962. unsigned * cur_percentage_p = (unsigned *) ctx;
  12963. unsigned percentage = (unsigned) (100 * progress);
  12964. while (percentage > *cur_percentage_p) {
  12965. *cur_percentage_p = percentage;
  12966. LLAMA_LOG_INFO(".");
  12967. if (percentage >= 100) {
  12968. LLAMA_LOG_INFO("\n");
  12969. }
  12970. }
  12971. return true;
  12972. };
  12973. }
  12974. if (params.rpc_servers != nullptr) {
  12975. // split the servers set them into model->rpc_servers
  12976. std::string servers(params.rpc_servers);
  12977. size_t pos = 0;
  12978. while ((pos = servers.find(",")) != std::string::npos) {
  12979. std::string server = servers.substr(0, pos);
  12980. model->rpc_servers.push_back(server);
  12981. servers.erase(0, pos + 1);
  12982. }
  12983. model->rpc_servers.push_back(servers);
  12984. }
  12985. int status = llama_model_load(path_model, *model, params);
  12986. GGML_ASSERT(status <= 0);
  12987. if (status < 0) {
  12988. if (status == -1) {
  12989. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  12990. } else if (status == -2) {
  12991. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  12992. }
  12993. delete model;
  12994. return nullptr;
  12995. }
  12996. return model;
  12997. }
  12998. void llama_free_model(struct llama_model * model) {
  12999. delete model;
  13000. }
  13001. struct llama_context * llama_new_context_with_model(
  13002. struct llama_model * model,
  13003. struct llama_context_params params) {
  13004. if (!model) {
  13005. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  13006. return nullptr;
  13007. }
  13008. if (params.n_batch == 0 && params.n_ubatch == 0) {
  13009. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  13010. return nullptr;
  13011. }
  13012. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  13013. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  13014. return nullptr;
  13015. }
  13016. if (params.flash_attn && model->arch == LLM_ARCH_GROK) {
  13017. LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
  13018. params.flash_attn = false;
  13019. }
  13020. llama_context * ctx = new llama_context(*model);
  13021. const auto & hparams = model->hparams;
  13022. auto & cparams = ctx->cparams;
  13023. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  13024. cparams.n_threads = params.n_threads;
  13025. cparams.n_threads_batch = params.n_threads_batch;
  13026. cparams.yarn_ext_factor = params.yarn_ext_factor;
  13027. cparams.yarn_attn_factor = params.yarn_attn_factor;
  13028. cparams.yarn_beta_fast = params.yarn_beta_fast;
  13029. cparams.yarn_beta_slow = params.yarn_beta_slow;
  13030. cparams.defrag_thold = params.defrag_thold;
  13031. cparams.embeddings = params.embeddings;
  13032. cparams.offload_kqv = params.offload_kqv;
  13033. cparams.flash_attn = params.flash_attn;
  13034. cparams.pooling_type = params.pooling_type;
  13035. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  13036. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  13037. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  13038. // this is necessary due to kv_self.n being padded later during inference
  13039. cparams.n_ctx = GGML_PAD(cparams.n_ctx, llama_kv_cache_get_padding(cparams));
  13040. // with causal attention, the batch size is limited by the context size
  13041. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  13042. // the batch has to be at least GGML_KQ_MASK_PAD because we will be padding the KQ_mask
  13043. // this is required by GPU kernels in order to avoid out-of-bounds accesses (e.g. ggml_flash_attn_ext)
  13044. // ref: https://github.com/ggerganov/llama.cpp/pull/5021
  13045. if (cparams.n_batch < GGML_KQ_MASK_PAD) {
  13046. LLAMA_LOG_WARN("%s: n_batch is less than GGML_KQ_MASK_PAD - increasing to %d\n", __func__, GGML_KQ_MASK_PAD);
  13047. cparams.n_batch = GGML_KQ_MASK_PAD;
  13048. }
  13049. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  13050. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  13051. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  13052. hparams.n_ctx_train;
  13053. cparams.cb_eval = params.cb_eval;
  13054. cparams.cb_eval_user_data = params.cb_eval_user_data;
  13055. auto rope_scaling_type = params.rope_scaling_type;
  13056. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  13057. rope_scaling_type = hparams.rope_scaling_type_train;
  13058. }
  13059. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  13060. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  13061. }
  13062. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  13063. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  13064. }
  13065. cparams.causal_attn = hparams.causal_attn;
  13066. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13067. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  13068. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  13069. } else {
  13070. cparams.pooling_type = hparams.pooling_type;
  13071. }
  13072. }
  13073. if (params.seed == LLAMA_DEFAULT_SEED) {
  13074. params.seed = time(NULL);
  13075. }
  13076. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  13077. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  13078. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  13079. LLAMA_LOG_INFO("%s: flash_attn = %d\n", __func__, cparams.flash_attn);
  13080. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  13081. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  13082. ctx->abort_callback = params.abort_callback;
  13083. ctx->abort_callback_data = params.abort_callback_data;
  13084. ctx->rng = std::mt19937(params.seed);
  13085. ctx->logits_all = params.logits_all;
  13086. uint32_t kv_size = cparams.n_ctx;
  13087. ggml_type type_k = params.type_k;
  13088. ggml_type type_v = params.type_v;
  13089. // Mamba only needs a constant number of KV cache cells per sequence
  13090. if (model->arch == LLM_ARCH_MAMBA) {
  13091. // Mamba needs at least as many KV cells as there are sequences kept at any time
  13092. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  13093. // it's probably best to keep as much precision as possible for the states
  13094. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  13095. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  13096. }
  13097. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  13098. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  13099. if (!hparams.vocab_only) {
  13100. // initialize backends
  13101. #if defined(GGML_USE_RPC)
  13102. for (auto & server : model->rpc_servers) {
  13103. ggml_backend_t backend = ggml_backend_rpc_init(server.c_str());
  13104. if (backend == nullptr) {
  13105. LLAMA_LOG_ERROR("%s: failed to connect RPC backend to %s\n", __func__, server.c_str());
  13106. llama_free(ctx);
  13107. return nullptr;
  13108. }
  13109. ctx->backends.push_back(backend);
  13110. }
  13111. #elif defined(GGML_USE_METAL)
  13112. if (model->n_gpu_layers > 0) {
  13113. ctx->backend_metal = ggml_backend_metal_init();
  13114. if (ctx->backend_metal == nullptr) {
  13115. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  13116. llama_free(ctx);
  13117. return nullptr;
  13118. }
  13119. ctx->backends.push_back(ctx->backend_metal);
  13120. }
  13121. #elif defined(GGML_USE_CUDA)
  13122. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13123. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13124. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  13125. if (backend == nullptr) {
  13126. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  13127. llama_free(ctx);
  13128. return nullptr;
  13129. }
  13130. ctx->backends.push_back(backend);
  13131. } else {
  13132. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  13133. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  13134. ggml_backend_t backend = ggml_backend_cuda_init(device);
  13135. if (backend == nullptr) {
  13136. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  13137. llama_free(ctx);
  13138. return nullptr;
  13139. }
  13140. ctx->backends.push_back(backend);
  13141. }
  13142. }
  13143. #elif defined(GGML_USE_VULKAN)
  13144. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13145. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  13146. llama_free(ctx);
  13147. return nullptr;
  13148. }
  13149. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  13150. ggml_backend_t backend = ggml_backend_vk_init(0);
  13151. if (backend == nullptr) {
  13152. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  13153. llama_free(ctx);
  13154. return nullptr;
  13155. }
  13156. ctx->backends.push_back(backend);
  13157. } else {
  13158. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  13159. ggml_backend_t backend = ggml_backend_vk_init(device);
  13160. if (backend == nullptr) {
  13161. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  13162. llama_free(ctx);
  13163. return nullptr;
  13164. }
  13165. ctx->backends.push_back(backend);
  13166. }
  13167. }
  13168. #elif defined(GGML_USE_SYCL)
  13169. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  13170. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  13171. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  13172. if (backend == nullptr) {
  13173. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  13174. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  13175. llama_free(ctx);
  13176. return nullptr;
  13177. }
  13178. ctx->backends.push_back(backend);
  13179. } else {
  13180. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  13181. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  13182. ggml_backend_t backend = ggml_backend_sycl_init(i);
  13183. if (backend == nullptr) {
  13184. int id_list[GGML_SYCL_MAX_DEVICES];
  13185. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  13186. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  13187. llama_free(ctx);
  13188. return nullptr;
  13189. }
  13190. ctx->backends.push_back(backend);
  13191. }
  13192. }
  13193. #elif defined(GGML_USE_KOMPUTE)
  13194. if (model->n_gpu_layers > 0) {
  13195. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  13196. if (backend == nullptr) {
  13197. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  13198. llama_free(ctx);
  13199. return nullptr;
  13200. }
  13201. ctx->backends.push_back(backend);
  13202. }
  13203. #endif
  13204. ctx->backend_cpu = ggml_backend_cpu_init();
  13205. if (ctx->backend_cpu == nullptr) {
  13206. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  13207. llama_free(ctx);
  13208. return nullptr;
  13209. }
  13210. ctx->backends.push_back(ctx->backend_cpu);
  13211. if (!llama_kv_cache_init(ctx->kv_self, ctx, type_k, type_v, kv_size, cparams.offload_kqv)) {
  13212. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  13213. llama_free(ctx);
  13214. return nullptr;
  13215. }
  13216. {
  13217. size_t memory_size_k = 0;
  13218. size_t memory_size_v = 0;
  13219. for (auto & k : ctx->kv_self.k_l) {
  13220. memory_size_k += ggml_nbytes(k);
  13221. }
  13222. for (auto & v : ctx->kv_self.v_l) {
  13223. memory_size_v += ggml_nbytes(v);
  13224. }
  13225. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  13226. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  13227. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  13228. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  13229. }
  13230. // graph outputs buffer
  13231. {
  13232. // resized during inference when a batch uses more outputs
  13233. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  13234. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  13235. llama_free(ctx);
  13236. return nullptr;
  13237. }
  13238. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  13239. ggml_backend_buffer_name(ctx->buf_output),
  13240. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  13241. }
  13242. // scheduler and compute buffers
  13243. {
  13244. // buffer types used for the compute buffer of each backend
  13245. std::vector<ggml_backend_buffer_type_t> backend_buft;
  13246. for (auto * backend : ctx->backends) {
  13247. if (ggml_backend_is_cpu(backend)) {
  13248. // use host buffers for the CPU backend compute buffer
  13249. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  13250. } else {
  13251. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  13252. }
  13253. }
  13254. // buffer used to store the computation graph and the tensor meta data
  13255. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  13256. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  13257. bool pipeline_parallel =
  13258. llama_get_device_count(*model) > 1 &&
  13259. model->n_gpu_layers > (int)model->hparams.n_layer &&
  13260. model->split_mode == LLAMA_SPLIT_MODE_LAYER &&
  13261. params.offload_kqv;
  13262. #ifndef GGML_USE_CUDA
  13263. // pipeline parallelism requires support for async compute and events
  13264. // currently this is only implemented in the CUDA backend
  13265. pipeline_parallel = false;
  13266. #endif
  13267. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  13268. if (pipeline_parallel) {
  13269. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  13270. }
  13271. // build worst-case graph
  13272. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  13273. int n_past = cparams.n_ctx - n_tokens;
  13274. 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
  13275. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  13276. // initialize scheduler with the worst-case graph
  13277. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  13278. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  13279. llama_free(ctx);
  13280. return nullptr;
  13281. }
  13282. for (size_t i = 0; i < ctx->backends.size(); i++) {
  13283. ggml_backend_t backend = ctx->backends[i];
  13284. ggml_backend_buffer_type_t buft = backend_buft[i];
  13285. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  13286. if (size > 1) {
  13287. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  13288. ggml_backend_buft_name(buft),
  13289. size / 1024.0 / 1024.0);
  13290. }
  13291. }
  13292. // note: the number of splits during measure is higher than during inference due to the kv shift
  13293. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  13294. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  13295. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  13296. }
  13297. }
  13298. return ctx;
  13299. }
  13300. void llama_free(struct llama_context * ctx) {
  13301. delete ctx;
  13302. }
  13303. const llama_model * llama_get_model(const struct llama_context * ctx) {
  13304. return &ctx->model;
  13305. }
  13306. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  13307. return ctx->cparams.n_ctx;
  13308. }
  13309. uint32_t llama_n_batch(const struct llama_context * ctx) {
  13310. return ctx->cparams.n_batch;
  13311. }
  13312. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  13313. return ctx->cparams.n_ubatch;
  13314. }
  13315. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  13316. return ctx->kv_self.size;
  13317. }
  13318. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  13319. return model->vocab.type;
  13320. }
  13321. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  13322. switch (model->arch) {
  13323. // these models do not use RoPE
  13324. case LLM_ARCH_GPT2:
  13325. case LLM_ARCH_GPTJ:
  13326. case LLM_ARCH_GPTNEOX:
  13327. case LLM_ARCH_MPT:
  13328. case LLM_ARCH_REFACT:
  13329. case LLM_ARCH_BLOOM:
  13330. case LLM_ARCH_MAMBA:
  13331. case LLM_ARCH_JINA_BERT_V2:
  13332. return LLAMA_ROPE_TYPE_NONE;
  13333. // use what we call a normal RoPE, operating on pairs of consecutive head values
  13334. case LLM_ARCH_LLAMA:
  13335. case LLM_ARCH_BAICHUAN:
  13336. case LLM_ARCH_STARCODER:
  13337. case LLM_ARCH_PLAMO:
  13338. case LLM_ARCH_CODESHELL:
  13339. case LLM_ARCH_ORION:
  13340. case LLM_ARCH_INTERNLM2:
  13341. case LLM_ARCH_MINICPM:
  13342. case LLM_ARCH_XVERSE:
  13343. case LLM_ARCH_COMMAND_R:
  13344. case LLM_ARCH_OLMO:
  13345. return LLAMA_ROPE_TYPE_NORM;
  13346. // the pairs of head values are offset by n_rot/2
  13347. case LLM_ARCH_FALCON:
  13348. case LLM_ARCH_GROK:
  13349. case LLM_ARCH_DBRX:
  13350. case LLM_ARCH_PERSIMMON:
  13351. case LLM_ARCH_BERT:
  13352. case LLM_ARCH_NOMIC_BERT:
  13353. case LLM_ARCH_STABLELM:
  13354. case LLM_ARCH_QWEN:
  13355. case LLM_ARCH_QWEN2:
  13356. case LLM_ARCH_QWEN2MOE:
  13357. case LLM_ARCH_PHI2:
  13358. case LLM_ARCH_PHI3:
  13359. case LLM_ARCH_GEMMA:
  13360. case LLM_ARCH_STARCODER2:
  13361. return LLAMA_ROPE_TYPE_NEOX;
  13362. // all model arches should be listed explicitly here
  13363. case LLM_ARCH_UNKNOWN:
  13364. GGML_ASSERT(false && "unknown architecture");
  13365. break;
  13366. }
  13367. return LLAMA_ROPE_TYPE_NONE;
  13368. }
  13369. enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
  13370. return ctx->cparams.pooling_type;
  13371. }
  13372. int32_t llama_n_vocab(const struct llama_model * model) {
  13373. return model->hparams.n_vocab;
  13374. }
  13375. int32_t llama_n_ctx_train(const struct llama_model * model) {
  13376. return model->hparams.n_ctx_train;
  13377. }
  13378. int32_t llama_n_embd(const struct llama_model * model) {
  13379. return model->hparams.n_embd;
  13380. }
  13381. int32_t llama_n_layer(const struct llama_model * model) {
  13382. return model->hparams.n_layer;
  13383. }
  13384. float llama_rope_freq_scale_train(const struct llama_model * model) {
  13385. return model->hparams.rope_freq_scale_train;
  13386. }
  13387. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  13388. const auto & it = model->gguf_kv.find(key);
  13389. if (it == model->gguf_kv.end()) {
  13390. if (buf_size > 0) {
  13391. buf[0] = '\0';
  13392. }
  13393. return -1;
  13394. }
  13395. return snprintf(buf, buf_size, "%s", it->second.c_str());
  13396. }
  13397. int32_t llama_model_meta_count(const struct llama_model * model) {
  13398. return (int)model->gguf_kv.size();
  13399. }
  13400. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  13401. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  13402. if (buf_size > 0) {
  13403. buf[0] = '\0';
  13404. }
  13405. return -1;
  13406. }
  13407. auto it = model->gguf_kv.begin();
  13408. std::advance(it, i);
  13409. return snprintf(buf, buf_size, "%s", it->first.c_str());
  13410. }
  13411. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  13412. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  13413. if (buf_size > 0) {
  13414. buf[0] = '\0';
  13415. }
  13416. return -1;
  13417. }
  13418. auto it = model->gguf_kv.begin();
  13419. std::advance(it, i);
  13420. return snprintf(buf, buf_size, "%s", it->second.c_str());
  13421. }
  13422. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  13423. return snprintf(buf, buf_size, "%s %s %s",
  13424. llama_model_arch_name(model->arch),
  13425. llama_model_type_name(model->type),
  13426. llama_model_ftype_name(model->ftype).c_str());
  13427. }
  13428. uint64_t llama_model_size(const struct llama_model * model) {
  13429. uint64_t size = 0;
  13430. for (const auto & it : model->tensors_by_name) {
  13431. size += ggml_nbytes(it.second);
  13432. }
  13433. return size;
  13434. }
  13435. uint64_t llama_model_n_params(const struct llama_model * model) {
  13436. uint64_t nparams = 0;
  13437. for (const auto & it : model->tensors_by_name) {
  13438. nparams += ggml_nelements(it.second);
  13439. }
  13440. return nparams;
  13441. }
  13442. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  13443. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  13444. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  13445. return it.first == name;
  13446. });
  13447. if (it == model->tensors_by_name.end()) {
  13448. return nullptr;
  13449. }
  13450. return it->second;
  13451. }
  13452. uint32_t llama_model_quantize(
  13453. const char * fname_inp,
  13454. const char * fname_out,
  13455. const llama_model_quantize_params * params) {
  13456. try {
  13457. llama_model_quantize_internal(fname_inp, fname_out, params);
  13458. return 0;
  13459. } catch (const std::exception & err) {
  13460. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  13461. return 1;
  13462. }
  13463. }
  13464. 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) {
  13465. try {
  13466. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  13467. } catch (const std::exception & err) {
  13468. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  13469. return 1;
  13470. }
  13471. }
  13472. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  13473. GGML_ASSERT(cvec.tensors.empty());
  13474. GGML_ASSERT(cvec.ctxs.empty());
  13475. GGML_ASSERT(cvec.bufs.empty());
  13476. // count layer buffer types
  13477. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  13478. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  13479. buft_layer_count[model.buft_layer[i].buft]++;
  13480. }
  13481. // allocate contexts
  13482. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  13483. for (auto & it : buft_layer_count) {
  13484. int n_layers = it.second;
  13485. struct ggml_init_params params = {
  13486. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  13487. /*.mem_buffer =*/ NULL,
  13488. /*.no_alloc =*/ true,
  13489. };
  13490. ggml_context * ctx = ggml_init(params);
  13491. if (!ctx) {
  13492. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  13493. return 1;
  13494. }
  13495. ctx_map[it.first] = ctx;
  13496. }
  13497. // make tensors
  13498. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  13499. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  13500. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  13501. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  13502. cvec.tensors.push_back(tensor);
  13503. }
  13504. // allocate tensors / buffers and zero
  13505. for (auto it : ctx_map) {
  13506. ggml_backend_buffer_type_t buft = it.first;
  13507. ggml_context * ctx = it.second;
  13508. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  13509. if (!buf) {
  13510. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  13511. return false;
  13512. }
  13513. ggml_backend_buffer_clear(buf, 0);
  13514. cvec.ctxs.push_back(ctx);
  13515. cvec.bufs.push_back(buf);
  13516. }
  13517. return true;
  13518. }
  13519. 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) {
  13520. const llama_model & model = lctx->model;
  13521. llama_control_vector & cvec = lctx->cvec;
  13522. if (data == nullptr) {
  13523. // disable the current control vector (but leave allocated for later)
  13524. cvec.layer_start = -1;
  13525. cvec.layer_end = -1;
  13526. return 0;
  13527. }
  13528. if (n_embd != (int) model.hparams.n_embd) {
  13529. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  13530. return 1;
  13531. }
  13532. if (cvec.tensors.empty()) {
  13533. if (!llama_control_vector_init(cvec, model)) {
  13534. return 1;
  13535. }
  13536. }
  13537. cvec.layer_start = il_start;
  13538. cvec.layer_end = il_end;
  13539. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  13540. assert(cvec.tensors[il] != nullptr);
  13541. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  13542. if (off + n_embd <= len) {
  13543. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  13544. }
  13545. }
  13546. return 0;
  13547. }
  13548. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  13549. struct llama_kv_cache_view result = {
  13550. /*.n_cells = */ 0,
  13551. /*.n_seq_max = */ n_seq_max,
  13552. /*.token_count = */ 0,
  13553. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  13554. /*.max_contiguous = */ 0,
  13555. /*.max_contiguous_idx = */ -1,
  13556. /*.cells = */ nullptr,
  13557. /*.cells_sequences = */ nullptr,
  13558. };
  13559. return result;
  13560. }
  13561. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  13562. if (view->cells != nullptr) {
  13563. free(view->cells);
  13564. view->cells = nullptr;
  13565. }
  13566. if (view->cells_sequences != nullptr) {
  13567. free(view->cells_sequences);
  13568. view->cells_sequences = nullptr;
  13569. }
  13570. }
  13571. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  13572. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  13573. view->n_cells = int32_t(ctx->kv_self.size);
  13574. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  13575. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  13576. view->cells = (struct llama_kv_cache_view_cell *)p;
  13577. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  13578. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  13579. view->cells_sequences = (llama_seq_id *)p;
  13580. }
  13581. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  13582. llama_kv_cache_view_cell * c_curr = view->cells;
  13583. llama_seq_id * cs_curr = view->cells_sequences;
  13584. int32_t used_cells = 0;
  13585. int32_t token_count = 0;
  13586. int32_t curr_contig_idx = -1;
  13587. uint32_t max_contig = 0;
  13588. int32_t max_contig_idx = -1;
  13589. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  13590. const size_t curr_size = kv_cells[i].seq_id.size();
  13591. token_count += curr_size;
  13592. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  13593. if (curr_size > 0) {
  13594. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  13595. max_contig = i - curr_contig_idx;
  13596. max_contig_idx = curr_contig_idx;
  13597. }
  13598. curr_contig_idx = -1;
  13599. } else if (curr_contig_idx < 0) {
  13600. curr_contig_idx = i;
  13601. }
  13602. int seq_idx = 0;
  13603. for (const llama_seq_id it : kv_cells[i].seq_id) {
  13604. if (seq_idx >= view->n_seq_max) {
  13605. break;
  13606. }
  13607. cs_curr[seq_idx] = it;
  13608. seq_idx++;
  13609. }
  13610. if (seq_idx != 0) {
  13611. used_cells++;
  13612. }
  13613. for (; seq_idx < view->n_seq_max; seq_idx++) {
  13614. cs_curr[seq_idx] = -1;
  13615. }
  13616. }
  13617. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  13618. max_contig_idx = curr_contig_idx;
  13619. max_contig = kv_cells.size() - curr_contig_idx;
  13620. }
  13621. view->max_contiguous = max_contig;
  13622. view->max_contiguous_idx = max_contig_idx;
  13623. view->token_count = token_count;
  13624. view->used_cells = used_cells;
  13625. if (uint32_t(used_cells) != ctx->kv_self.used) {
  13626. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  13627. __func__, ctx->kv_self.used, used_cells);
  13628. }
  13629. }
  13630. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  13631. int result = 0;
  13632. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  13633. result += ctx->kv_self.cells[i].seq_id.size();
  13634. }
  13635. return result;
  13636. }
  13637. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  13638. return ctx->kv_self.used;
  13639. }
  13640. void llama_kv_cache_clear(struct llama_context * ctx) {
  13641. llama_kv_cache_clear(ctx->kv_self);
  13642. }
  13643. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  13644. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  13645. }
  13646. 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) {
  13647. if (seq_id_src == seq_id_dst) {
  13648. return;
  13649. }
  13650. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  13651. }
  13652. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  13653. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  13654. }
  13655. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  13656. if (delta == 0) {
  13657. return;
  13658. }
  13659. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  13660. }
  13661. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  13662. if (d == 1) {
  13663. return;
  13664. }
  13665. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  13666. }
  13667. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  13668. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  13669. }
  13670. void llama_kv_cache_defrag(struct llama_context * ctx) {
  13671. llama_kv_cache_defrag(ctx->kv_self);
  13672. }
  13673. void llama_kv_cache_update(struct llama_context * ctx) {
  13674. llama_kv_cache_update_internal(*ctx);
  13675. }
  13676. // deprecated
  13677. size_t llama_get_state_size(const struct llama_context * ctx) {
  13678. return llama_state_get_size(ctx);
  13679. }
  13680. // deprecated
  13681. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  13682. return llama_state_get_data(ctx, dst);
  13683. }
  13684. // deprecated
  13685. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  13686. return llama_state_set_data(ctx, src);
  13687. }
  13688. // deprecated
  13689. 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) {
  13690. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  13691. }
  13692. // deprecated
  13693. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  13694. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  13695. }
  13696. // Returns the *maximum* size of the state
  13697. size_t llama_state_get_size(const struct llama_context * ctx) {
  13698. const auto & cparams = ctx->cparams;
  13699. const auto & hparams = ctx->model.hparams;
  13700. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  13701. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  13702. const size_t s_rng_size = sizeof(size_t);
  13703. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  13704. const size_t s_n_outputs = sizeof(size_t);
  13705. // assume worst case for outputs although only currently set ones are serialized
  13706. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  13707. const size_t s_logits_size = sizeof(size_t);
  13708. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  13709. const size_t s_embedding_size = sizeof(size_t);
  13710. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  13711. const size_t s_kv_buf_size = sizeof(size_t);
  13712. const size_t s_kv_head = sizeof(uint32_t);
  13713. const size_t s_kv_size = sizeof(uint32_t);
  13714. const size_t s_kv_used = sizeof(uint32_t);
  13715. const size_t s_v_trans = sizeof(uint32_t);
  13716. const size_t s_kv = ctx->kv_self.total_size();
  13717. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  13718. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  13719. const size_t s_total = (
  13720. + s_rng_size
  13721. + s_rng
  13722. + s_n_outputs
  13723. + s_output_pos
  13724. + s_logits_size
  13725. + s_logits
  13726. + s_embedding_size
  13727. + s_embedding
  13728. + s_kv_buf_size
  13729. + s_kv_head
  13730. + s_kv_size
  13731. + s_kv_used
  13732. + s_v_trans
  13733. + s_kv
  13734. + s_kv_cells
  13735. );
  13736. // on session change it is very likely that the state size has changed - so we need to update this function
  13737. static_assert(LLAMA_SESSION_VERSION == 6, "So you just bumped the session version - good. But did you remember to update llama_state_get_size?");
  13738. return s_total;
  13739. }
  13740. // llama_context_data
  13741. struct llama_data_context {
  13742. virtual void write(const void * src, size_t size) = 0;
  13743. virtual size_t get_size_written() = 0;
  13744. virtual ~llama_data_context() = default;
  13745. };
  13746. struct llama_data_buffer_context : llama_data_context {
  13747. uint8_t * ptr;
  13748. size_t size_written = 0;
  13749. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  13750. void write(const void * src, size_t size) override {
  13751. memcpy(ptr, src, size);
  13752. ptr += size;
  13753. size_written += size;
  13754. }
  13755. size_t get_size_written() override {
  13756. return size_written;
  13757. }
  13758. };
  13759. struct llama_data_file_context : llama_data_context {
  13760. llama_file * file;
  13761. size_t size_written = 0;
  13762. llama_data_file_context(llama_file * f) : file(f) {}
  13763. void write(const void * src, size_t size) override {
  13764. file->write_raw(src, size);
  13765. size_written += size;
  13766. }
  13767. size_t get_size_written() override {
  13768. return size_written;
  13769. }
  13770. };
  13771. /** copy state data into either a buffer or file depending on the passed in context
  13772. *
  13773. * file context:
  13774. * llama_file file("/path", "wb");
  13775. * llama_data_file_context data_ctx(&file);
  13776. * llama_state_get_data(ctx, &data_ctx);
  13777. *
  13778. * buffer context:
  13779. * std::vector<uint8_t> buf(max_size, 0);
  13780. * llama_data_buffer_context data_ctx(&buf.data());
  13781. * llama_state_get_data(ctx, &data_ctx);
  13782. *
  13783. */
  13784. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  13785. llama_synchronize(ctx);
  13786. // copy rng
  13787. {
  13788. std::ostringstream rng_ss;
  13789. rng_ss << ctx->rng;
  13790. const std::string & rng_str = rng_ss.str();
  13791. const size_t rng_size = rng_str.size();
  13792. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  13793. data_ctx->write(&rng_size, sizeof(rng_size));
  13794. data_ctx->write(rng_str.data(), rng_size);
  13795. }
  13796. // copy outputs
  13797. {
  13798. // Can't use ctx->n_outputs because it's not for the
  13799. // entire last batch when n_ubatch is smaller than n_batch
  13800. size_t n_outputs = 0;
  13801. // copy output ids
  13802. {
  13803. std::vector<int32_t> output_pos;
  13804. const size_t n_batch = ctx->cparams.n_batch;
  13805. const auto & output_ids = ctx->output_ids;
  13806. output_pos.resize(ctx->output_size);
  13807. // build a more compact representation of the output ids
  13808. for (size_t i = 0; i < n_batch; ++i) {
  13809. // map an output id to a position in the batch
  13810. int32_t pos = output_ids[i];
  13811. if (pos >= 0) {
  13812. if ((size_t) pos >= n_outputs) {
  13813. n_outputs = pos + 1;
  13814. }
  13815. GGML_ASSERT((size_t) pos < ctx->output_size);
  13816. output_pos[pos] = i;
  13817. }
  13818. }
  13819. data_ctx->write(&n_outputs, sizeof(n_outputs));
  13820. if (n_outputs) {
  13821. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  13822. }
  13823. }
  13824. // copy logits
  13825. {
  13826. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  13827. data_ctx->write(&logits_size, sizeof(logits_size));
  13828. if (logits_size) {
  13829. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  13830. }
  13831. }
  13832. // copy embeddings
  13833. {
  13834. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  13835. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  13836. if (embeddings_size) {
  13837. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  13838. }
  13839. }
  13840. }
  13841. // copy kv cache
  13842. {
  13843. const auto & kv_self = ctx->kv_self;
  13844. const auto & hparams = ctx->model.hparams;
  13845. const uint32_t n_layer = hparams.n_layer;
  13846. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13847. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13848. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  13849. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  13850. const uint32_t kv_size = kv_self.size;
  13851. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  13852. const uint32_t kv_used = kv_self.used;
  13853. const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
  13854. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  13855. data_ctx->write(&kv_head, sizeof(kv_head));
  13856. data_ctx->write(&kv_size, sizeof(kv_size));
  13857. data_ctx->write(&kv_used, sizeof(kv_used));
  13858. data_ctx->write(&v_trans, sizeof(v_trans));
  13859. if (kv_buf_size) {
  13860. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  13861. std::vector<uint8_t> tmp_buf;
  13862. for (int il = 0; il < (int) n_layer; ++il) {
  13863. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  13864. tmp_buf.resize(k_size);
  13865. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  13866. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  13867. if (kv_self.recurrent || !kv_self.v_trans) {
  13868. // v is contiguous for recurrent models
  13869. // TODO: use other tensors for state models than k and v
  13870. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  13871. tmp_buf.resize(v_size);
  13872. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  13873. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  13874. continue;
  13875. }
  13876. // v is not contiguous, copy row by row
  13877. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  13878. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  13879. tmp_buf.resize(v_row_size);
  13880. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  13881. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  13882. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  13883. }
  13884. }
  13885. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  13886. }
  13887. for (uint32_t i = 0; i < kv_head; ++i) {
  13888. const auto & cell = kv_self.cells[i];
  13889. const llama_pos pos = cell.pos;
  13890. const size_t seq_id_size = cell.seq_id.size();
  13891. data_ctx->write(&pos, sizeof(pos));
  13892. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  13893. for (auto seq_id : cell.seq_id) {
  13894. data_ctx->write(&seq_id, sizeof(seq_id));
  13895. }
  13896. }
  13897. }
  13898. }
  13899. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  13900. llama_data_buffer_context data_ctx(dst);
  13901. llama_state_get_data_internal(ctx, &data_ctx);
  13902. return data_ctx.get_size_written();
  13903. }
  13904. // Sets the state reading from the specified source address
  13905. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  13906. llama_synchronize(ctx);
  13907. const uint8_t * inp = src;
  13908. // set rng
  13909. {
  13910. size_t rng_size;
  13911. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  13912. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  13913. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  13914. std::istringstream rng_ss(rng_str);
  13915. rng_ss >> ctx->rng;
  13916. GGML_ASSERT(!rng_ss.fail());
  13917. }
  13918. // set output ids
  13919. {
  13920. size_t n_outputs;
  13921. std::vector<int32_t> output_pos;
  13922. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  13923. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  13924. if (n_outputs) {
  13925. output_pos.resize(n_outputs);
  13926. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  13927. inp += n_outputs * sizeof(int32_t);
  13928. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  13929. int32_t id = output_pos[i];
  13930. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  13931. ctx->output_ids[id] = i;
  13932. }
  13933. ctx->n_outputs = n_outputs;
  13934. }
  13935. }
  13936. // set logits
  13937. {
  13938. size_t logits_size;
  13939. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  13940. GGML_ASSERT(ctx->logits_size >= logits_size);
  13941. if (logits_size) {
  13942. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  13943. inp += logits_size * sizeof(float);
  13944. }
  13945. }
  13946. // set embeddings
  13947. {
  13948. size_t embeddings_size;
  13949. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  13950. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  13951. if (embeddings_size) {
  13952. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  13953. inp += embeddings_size * sizeof(float);
  13954. }
  13955. }
  13956. // set kv cache
  13957. {
  13958. const auto & kv_self = ctx->kv_self;
  13959. const auto & hparams = ctx->model.hparams;
  13960. const uint32_t n_layer = hparams.n_layer;
  13961. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13962. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13963. size_t kv_buf_size;
  13964. uint32_t kv_head;
  13965. uint32_t kv_size;
  13966. uint32_t kv_used;
  13967. uint32_t v_trans;
  13968. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  13969. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  13970. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  13971. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  13972. memcpy(&v_trans, inp, sizeof(v_trans)); inp += sizeof(v_trans);
  13973. GGML_ASSERT(kv_self.v_trans == (bool) v_trans); // incompatible V transposition
  13974. if (kv_self.size != kv_size) {
  13975. // the KV cache needs to be big enough to load all the KV cells from the saved state
  13976. GGML_ASSERT(kv_self.size >= kv_head);
  13977. 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",
  13978. __func__, kv_head, kv_size, kv_self.size);
  13979. }
  13980. llama_kv_cache_clear(ctx);
  13981. if (kv_buf_size) {
  13982. const size_t pre_kv_buf_size = inp - src;
  13983. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  13984. for (int il = 0; il < (int) n_layer; ++il) {
  13985. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  13986. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  13987. inp += k_size;
  13988. if (kv_self.recurrent || !kv_self.v_trans) {
  13989. // v is contiguous for recurrent models
  13990. // TODO: use other tensors for state models than k and v
  13991. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  13992. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  13993. inp += v_size;
  13994. continue;
  13995. }
  13996. // v is not contiguous, copy row by row
  13997. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  13998. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  13999. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  14000. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  14001. inp += v_row_size;
  14002. }
  14003. }
  14004. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  14005. }
  14006. ctx->kv_self.head = kv_head;
  14007. ctx->kv_self.used = kv_used;
  14008. for (uint32_t i = 0; i < kv_head; ++i) {
  14009. llama_pos pos;
  14010. size_t seq_id_size;
  14011. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  14012. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  14013. ctx->kv_self.cells[i].pos = pos;
  14014. llama_seq_id seq_id;
  14015. for (size_t j = 0; j < seq_id_size; ++j) {
  14016. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  14017. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  14018. }
  14019. }
  14020. }
  14021. const size_t nread = inp - src;
  14022. const size_t max_size = llama_state_get_size(ctx);
  14023. GGML_ASSERT(nread <= max_size);
  14024. return nread;
  14025. }
  14026. 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) {
  14027. llama_file file(path_session, "rb");
  14028. // sanity checks
  14029. {
  14030. const uint32_t magic = file.read_u32();
  14031. const uint32_t version = file.read_u32();
  14032. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  14033. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  14034. return false;
  14035. }
  14036. llama_hparams session_hparams;
  14037. file.read_raw(&session_hparams, sizeof(llama_hparams));
  14038. if (session_hparams != ctx->model.hparams) {
  14039. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  14040. return false;
  14041. }
  14042. }
  14043. // load the prompt
  14044. {
  14045. const uint32_t n_token_count = file.read_u32();
  14046. if (n_token_count > n_token_capacity) {
  14047. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  14048. return false;
  14049. }
  14050. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  14051. *n_token_count_out = n_token_count;
  14052. }
  14053. // restore the context state
  14054. {
  14055. const size_t n_state_size_cur = file.size - file.tell();
  14056. const size_t n_state_size_max = llama_state_get_size(ctx);
  14057. if (n_state_size_cur > n_state_size_max) {
  14058. 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);
  14059. return false;
  14060. }
  14061. std::vector<uint8_t> state_data(n_state_size_max);
  14062. file.read_raw(state_data.data(), n_state_size_cur);
  14063. llama_state_set_data(ctx, state_data.data());
  14064. }
  14065. return true;
  14066. }
  14067. 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) {
  14068. try {
  14069. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  14070. } catch (const std::exception & err) {
  14071. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  14072. return false;
  14073. }
  14074. }
  14075. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14076. llama_file file(path_session, "wb");
  14077. file.write_u32(LLAMA_SESSION_MAGIC);
  14078. file.write_u32(LLAMA_SESSION_VERSION);
  14079. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  14080. // save the prompt
  14081. file.write_u32((uint32_t) n_token_count);
  14082. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  14083. // save the context state using stream saving
  14084. llama_data_file_context data_ctx(&file);
  14085. llama_state_get_data_internal(ctx, &data_ctx);
  14086. return true;
  14087. }
  14088. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  14089. try {
  14090. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  14091. } catch (const std::exception & err) {
  14092. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  14093. return false;
  14094. }
  14095. }
  14096. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  14097. // save the size of size_t as a uint32_t for safety check
  14098. const size_t size_t_size_size = sizeof(uint32_t);
  14099. // other values
  14100. const size_t s_cell_count_size = sizeof(uint32_t);
  14101. const size_t s_layer_count_size = sizeof(uint32_t);
  14102. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  14103. size_t s_cell_count = 0;
  14104. size_t s_cell_data_size = 0;
  14105. const auto & kv_self = ctx->kv_self;
  14106. const auto & hparams = ctx->model.hparams;
  14107. const uint32_t n_layer = hparams.n_layer;
  14108. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14109. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14110. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14111. const auto & cell = kv_self.cells[i];
  14112. if (cell.seq_id.count(seq_id) > 0) {
  14113. ++s_cell_count;
  14114. s_cell_data_size += sizeof(llama_pos);
  14115. }
  14116. }
  14117. for (int il = 0; il < (int)n_layer; ++il) {
  14118. // types of keys and values
  14119. s_cell_data_size += sizeof(int32_t) * 2;
  14120. // k_size_row and v_size_el values of layer
  14121. s_cell_data_size += sizeof(size_t) * 2;
  14122. // keys
  14123. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14124. s_cell_data_size += k_size_row * s_cell_count;
  14125. // values (transposed)
  14126. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14127. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  14128. }
  14129. const size_t s_total = (
  14130. size_t_size_size +
  14131. s_cell_count_size +
  14132. s_layer_count_size +
  14133. n_embd_v_gqa_size +
  14134. s_cell_data_size
  14135. );
  14136. return s_total;
  14137. }
  14138. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  14139. llama_synchronize(ctx);
  14140. const auto & kv_self = ctx->kv_self;
  14141. GGML_ASSERT(!kv_self.recurrent); // not implemented
  14142. // Save the size of size_t as a uint32_t for safety check
  14143. const uint32_t size_t_size = sizeof(size_t);
  14144. data_ctx.write(&size_t_size, sizeof(size_t_size));
  14145. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  14146. uint32_t cell_count = 0;
  14147. // Count the number of cells with the specified seq_id
  14148. // Find all the ranges of cells with this seq id
  14149. {
  14150. uint32_t cell_range_begin = kv_self.size;
  14151. for (uint32_t i = 0; i < kv_self.size; ++i) {
  14152. const auto & cell = kv_self.cells[i];
  14153. if (cell.has_seq_id(seq_id)) {
  14154. ++cell_count;
  14155. if (cell_range_begin == kv_self.size) {
  14156. cell_range_begin = i;
  14157. }
  14158. }
  14159. else {
  14160. if (cell_range_begin != kv_self.size) {
  14161. cell_ranges.emplace_back(cell_range_begin, i);
  14162. cell_range_begin = kv_self.size;
  14163. }
  14164. }
  14165. }
  14166. if (cell_range_begin != kv_self.size) {
  14167. cell_ranges.emplace_back(cell_range_begin, kv_self.size);
  14168. }
  14169. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  14170. uint32_t cell_count_check = 0;
  14171. for (const auto & range : cell_ranges) {
  14172. cell_count_check += range.second - range.first;
  14173. }
  14174. GGML_ASSERT(cell_count == cell_count_check);
  14175. }
  14176. // Write the cell count
  14177. data_ctx.write(&cell_count, sizeof(cell_count));
  14178. const auto & hparams = ctx->model.hparams;
  14179. const uint32_t n_layer = hparams.n_layer;
  14180. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14181. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14182. // Write the layer count
  14183. data_ctx.write(&n_layer, sizeof(n_layer));
  14184. // Write n_embd_v_gqa
  14185. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  14186. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  14187. for (const auto & range : cell_ranges) {
  14188. for (uint32_t i = range.first; i < range.second; ++i) {
  14189. const auto & cell = kv_self.cells[i];
  14190. data_ctx.write(&cell.pos, sizeof(cell.pos));
  14191. }
  14192. }
  14193. // Iterate and write all the keys first, each row is a cell
  14194. // Get whole range at a time
  14195. std::vector<uint8_t> tmp_buf;
  14196. for (int il = 0; il < (int)n_layer; ++il) {
  14197. // Write key type
  14198. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14199. data_ctx.write(&k_type_i, sizeof(k_type_i));
  14200. // Write row size of key
  14201. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14202. data_ctx.write(&k_size_row, sizeof(k_size_row));
  14203. // Read each range of cells of k_size length each into tmp_buf and write out
  14204. for (const auto & range : cell_ranges) {
  14205. const size_t range_size = range.second - range.first;
  14206. tmp_buf.resize(range_size * k_size_row);
  14207. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  14208. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14209. }
  14210. }
  14211. // TODO: simplify, reduce copy-paste
  14212. if (!kv_self.v_trans) {
  14213. for (int il = 0; il < (int)n_layer; ++il) {
  14214. // Write value type
  14215. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14216. data_ctx.write(&v_type_i, sizeof(v_type_i));
  14217. // Write row size of value
  14218. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14219. data_ctx.write(&v_size_row, sizeof(v_size_row));
  14220. // Read each range of cells of v_size length each into tmp_buf and write out
  14221. for (const auto & range : cell_ranges) {
  14222. const size_t range_size = range.second - range.first;
  14223. tmp_buf.resize(range_size * v_size_row);
  14224. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), range.first * v_size_row, range_size * v_size_row);
  14225. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14226. }
  14227. }
  14228. } else {
  14229. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  14230. const uint32_t kv_size = kv_self.size;
  14231. for (int il = 0; il < (int)n_layer; ++il) {
  14232. // Write value type
  14233. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14234. data_ctx.write(&v_type_i, sizeof(v_type_i));
  14235. // Write element size
  14236. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14237. data_ctx.write(&v_size_el, sizeof(v_size_el));
  14238. // For each row, we get the element values of each cell
  14239. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14240. // Read each range of cells of v_size_el length each into tmp_buf and write out
  14241. for (const auto & range : cell_ranges) {
  14242. const size_t range_size = range.second - range.first;
  14243. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  14244. tmp_buf.resize(range_size * v_size_el);
  14245. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  14246. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  14247. }
  14248. }
  14249. }
  14250. }
  14251. return data_ctx.get_size_written();
  14252. }
  14253. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  14254. llama_data_buffer_context data_ctx(dst);
  14255. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  14256. }
  14257. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  14258. llama_synchronize(ctx);
  14259. auto & kv_self = ctx->kv_self;
  14260. GGML_ASSERT(!kv_self.recurrent); // not implemented
  14261. // Wipe the slot
  14262. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14263. const uint8_t * inp = src;
  14264. // Read size of size_t
  14265. uint32_t size_t_size;
  14266. memcpy(&size_t_size, inp, sizeof(size_t_size));
  14267. inp += sizeof(size_t_size);
  14268. if (size_t_size != sizeof(size_t)) {
  14269. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  14270. return 0;
  14271. }
  14272. // Read the cell count
  14273. uint32_t cell_count;
  14274. memcpy(&cell_count, inp, sizeof(cell_count));
  14275. inp += sizeof(cell_count);
  14276. // Read the layer count
  14277. uint32_t n_layer_ref;
  14278. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  14279. inp += sizeof(n_layer_ref);
  14280. // Read n_embd_v_gqa
  14281. uint32_t n_embd_v_gqa_ref;
  14282. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  14283. inp += sizeof(n_embd_v_gqa_ref);
  14284. // Sanity check model compatibility
  14285. const auto & hparams = ctx->model.hparams;
  14286. const uint32_t n_layer = hparams.n_layer;
  14287. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  14288. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  14289. if (n_layer != n_layer_ref) {
  14290. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  14291. return 0;
  14292. }
  14293. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  14294. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  14295. return 0;
  14296. }
  14297. // Allocate the new cells for the slot
  14298. if (cell_count) {
  14299. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  14300. batch.n_tokens = cell_count;
  14301. for (uint32_t i = 0; i < cell_count; ++i) {
  14302. llama_pos pos;
  14303. memcpy(&pos, inp, sizeof(pos));
  14304. inp += sizeof(pos);
  14305. batch.pos[i] = pos;
  14306. batch.n_seq_id[i] = 1;
  14307. batch.seq_id[i][0] = dest_seq_id;
  14308. }
  14309. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  14310. llama_batch_free(batch);
  14311. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  14312. return 0;
  14313. }
  14314. // 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)
  14315. // Assume that this is one contiguous block of cells
  14316. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  14317. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  14318. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  14319. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  14320. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  14321. // Cleanup
  14322. llama_batch_free(batch);
  14323. }
  14324. const uint32_t kv_size = kv_self.size;
  14325. const uint32_t kv_head = kv_self.head;
  14326. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  14327. for (int il = 0; il < (int)n_layer; ++il) {
  14328. // Read type of key
  14329. int32_t k_type_i_ref;
  14330. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  14331. inp += sizeof(k_type_i_ref);
  14332. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  14333. if (k_type_i != k_type_i_ref) {
  14334. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14335. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  14336. return 0;
  14337. }
  14338. // Read row size of key
  14339. size_t k_size_row_ref;
  14340. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  14341. inp += sizeof(k_size_row_ref);
  14342. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  14343. if (k_size_row != k_size_row_ref) {
  14344. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14345. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  14346. return 0;
  14347. }
  14348. if (cell_count) {
  14349. // Read and set the keys for the whole cell range
  14350. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  14351. inp += cell_count * k_size_row;
  14352. }
  14353. }
  14354. // TODO: simplify, reduce copy-paste
  14355. if (!kv_self.v_trans) {
  14356. for (int il = 0; il < (int)n_layer; ++il) {
  14357. // Read type of value
  14358. int32_t v_type_i_ref;
  14359. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  14360. inp += sizeof(v_type_i_ref);
  14361. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14362. if (v_type_i != v_type_i_ref) {
  14363. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14364. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14365. return 0;
  14366. }
  14367. // Read row size of value
  14368. size_t v_size_row_ref;
  14369. memcpy(&v_size_row_ref, inp, sizeof(v_size_row_ref));
  14370. inp += sizeof(v_size_row_ref);
  14371. const size_t v_size_row = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
  14372. if (v_size_row != v_size_row_ref) {
  14373. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14374. LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, v_size_row_ref, il);
  14375. return 0;
  14376. }
  14377. if (cell_count) {
  14378. // Read and set the values for the whole cell range
  14379. ggml_backend_tensor_set(kv_self.v_l[il], inp, kv_head * v_size_row, cell_count * v_size_row);
  14380. inp += cell_count * v_size_row;
  14381. }
  14382. }
  14383. } else {
  14384. // For each layer, read the values for each cell (transposed)
  14385. for (int il = 0; il < (int)n_layer; ++il) {
  14386. // Read type of value
  14387. int32_t v_type_i_ref;
  14388. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  14389. inp += sizeof(v_type_i_ref);
  14390. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  14391. if (v_type_i != v_type_i_ref) {
  14392. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14393. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  14394. return 0;
  14395. }
  14396. // Read element size of value
  14397. size_t v_size_el_ref;
  14398. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  14399. inp += sizeof(v_size_el_ref);
  14400. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  14401. if (v_size_el != v_size_el_ref) {
  14402. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  14403. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  14404. return 0;
  14405. }
  14406. if (cell_count) {
  14407. // For each row in the transposed matrix, read the values for the whole cell range
  14408. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  14409. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  14410. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  14411. inp += cell_count * v_size_el;
  14412. }
  14413. }
  14414. }
  14415. }
  14416. const size_t nread = inp - src;
  14417. return nread;
  14418. }
  14419. 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) {
  14420. llama_file file(filepath, "wb");
  14421. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  14422. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  14423. // save the prompt
  14424. file.write_u32((uint32_t)n_token_count);
  14425. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  14426. // save the context state using stream saving
  14427. llama_data_file_context data_ctx(&file);
  14428. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  14429. const size_t res = file.tell();
  14430. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  14431. return res;
  14432. }
  14433. 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) {
  14434. llama_file file(filepath, "rb");
  14435. // version checks
  14436. {
  14437. const uint32_t magic = file.read_u32();
  14438. const uint32_t version = file.read_u32();
  14439. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  14440. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  14441. return 0;
  14442. }
  14443. }
  14444. // load the prompt
  14445. {
  14446. const uint32_t n_token_count = file.read_u32();
  14447. if (n_token_count > n_token_capacity) {
  14448. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  14449. return 0;
  14450. }
  14451. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  14452. *n_token_count_out = n_token_count;
  14453. }
  14454. // restore the context state
  14455. {
  14456. const size_t state_size = file.size - file.tell();
  14457. std::vector<uint8_t> state_data(state_size);
  14458. file.read_raw(state_data.data(), state_size);
  14459. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  14460. if (!nread) {
  14461. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  14462. return 0;
  14463. }
  14464. GGML_ASSERT(nread <= state_size);
  14465. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  14466. }
  14467. return file.tell();
  14468. }
  14469. 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) {
  14470. try {
  14471. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  14472. } catch (const std::exception & err) {
  14473. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  14474. return 0;
  14475. }
  14476. }
  14477. 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) {
  14478. try {
  14479. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  14480. } catch (const std::exception & err) {
  14481. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  14482. return 0;
  14483. }
  14484. }
  14485. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  14486. ctx->cparams.n_threads = n_threads;
  14487. ctx->cparams.n_threads_batch = n_threads_batch;
  14488. }
  14489. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  14490. ctx->abort_callback = abort_callback;
  14491. ctx->abort_callback_data = abort_callback_data;
  14492. }
  14493. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  14494. ctx->cparams.causal_attn = causal_attn;
  14495. }
  14496. struct llama_batch llama_batch_get_one(
  14497. llama_token * tokens,
  14498. int32_t n_tokens,
  14499. llama_pos pos_0,
  14500. llama_seq_id seq_id) {
  14501. return {
  14502. /*n_tokens =*/ n_tokens,
  14503. /*tokens =*/ tokens,
  14504. /*embd =*/ nullptr,
  14505. /*pos =*/ nullptr,
  14506. /*n_seq_id =*/ nullptr,
  14507. /*seq_id =*/ nullptr,
  14508. /*logits =*/ nullptr,
  14509. /*all_pos_0 =*/ pos_0,
  14510. /*all_pos_1 =*/ 1,
  14511. /*all_seq_id =*/ seq_id,
  14512. };
  14513. }
  14514. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  14515. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  14516. if (embd) {
  14517. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  14518. } else {
  14519. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  14520. }
  14521. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  14522. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  14523. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  14524. for (int i = 0; i < n_tokens_alloc; ++i) {
  14525. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  14526. }
  14527. batch.seq_id[n_tokens_alloc] = nullptr;
  14528. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  14529. return batch;
  14530. }
  14531. void llama_batch_free(struct llama_batch batch) {
  14532. if (batch.token) free(batch.token);
  14533. if (batch.embd) free(batch.embd);
  14534. if (batch.pos) free(batch.pos);
  14535. if (batch.n_seq_id) free(batch.n_seq_id);
  14536. if (batch.seq_id) {
  14537. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  14538. free(batch.seq_id[i]);
  14539. }
  14540. free(batch.seq_id);
  14541. }
  14542. if (batch.logits) free(batch.logits);
  14543. }
  14544. int32_t llama_decode(
  14545. struct llama_context * ctx,
  14546. struct llama_batch batch) {
  14547. const int ret = llama_decode_internal(*ctx, batch);
  14548. if (ret < 0) {
  14549. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  14550. }
  14551. return ret;
  14552. }
  14553. void llama_synchronize(struct llama_context * ctx) {
  14554. ggml_backend_sched_synchronize(ctx->sched);
  14555. // FIXME: if multiple single tokens are evaluated without a synchronization,
  14556. // the stats will be added to the prompt evaluation stats
  14557. // this should only happen when using batch size 1 to evaluate a batch
  14558. // add the evaluation to the stats
  14559. if (ctx->n_queued_tokens == 1) {
  14560. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  14561. ctx->n_eval++;
  14562. } else if (ctx->n_queued_tokens > 1) {
  14563. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  14564. ctx->n_p_eval += ctx->n_queued_tokens;
  14565. }
  14566. // get a more accurate load time, upon first eval
  14567. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  14568. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  14569. ctx->has_evaluated_once = true;
  14570. }
  14571. ctx->n_queued_tokens = 0;
  14572. ctx->t_compute_start_us = 0;
  14573. }
  14574. float * llama_get_logits(struct llama_context * ctx) {
  14575. llama_synchronize(ctx);
  14576. return ctx->logits;
  14577. }
  14578. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  14579. int32_t j = -1;
  14580. llama_synchronize(ctx);
  14581. try {
  14582. if (ctx->logits == nullptr) {
  14583. throw std::runtime_error("no logits");
  14584. }
  14585. if (i < 0) {
  14586. j = ctx->n_outputs + i;
  14587. if (j < 0) {
  14588. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  14589. }
  14590. } else if ((size_t) i >= ctx->output_ids.size()) {
  14591. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  14592. } else {
  14593. j = ctx->output_ids[i];
  14594. }
  14595. if (j < 0) {
  14596. throw std::runtime_error(format("batch.logits[%d] != true", i));
  14597. }
  14598. if (j >= ctx->n_outputs) {
  14599. // This should not happen
  14600. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  14601. }
  14602. return ctx->logits + j*ctx->model.hparams.n_vocab;
  14603. } catch (const std::exception & err) {
  14604. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  14605. #ifndef NDEBUG
  14606. GGML_ASSERT(false);
  14607. #endif
  14608. return nullptr;
  14609. }
  14610. }
  14611. float * llama_get_embeddings(struct llama_context * ctx) {
  14612. llama_synchronize(ctx);
  14613. return ctx->embd;
  14614. }
  14615. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  14616. int32_t j = -1;
  14617. llama_synchronize(ctx);
  14618. try {
  14619. if (ctx->embd == nullptr) {
  14620. throw std::runtime_error("no embeddings");
  14621. }
  14622. if (i < 0) {
  14623. j = ctx->n_outputs + i;
  14624. if (j < 0) {
  14625. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  14626. }
  14627. } else if ((size_t) i >= ctx->output_ids.size()) {
  14628. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  14629. } else {
  14630. j = ctx->output_ids[i];
  14631. }
  14632. if (j < 0) {
  14633. throw std::runtime_error(format("batch.logits[%d] != true", i));
  14634. }
  14635. if (j >= ctx->n_outputs) {
  14636. // This should not happen
  14637. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  14638. }
  14639. return ctx->embd + j*ctx->model.hparams.n_embd;
  14640. } catch (const std::exception & err) {
  14641. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  14642. #ifndef NDEBUG
  14643. GGML_ASSERT(false);
  14644. #endif
  14645. return nullptr;
  14646. }
  14647. }
  14648. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  14649. llama_synchronize(ctx);
  14650. auto it = ctx->embd_seq.find(seq_id);
  14651. if (it == ctx->embd_seq.end()) {
  14652. return nullptr;
  14653. }
  14654. return it->second.data();
  14655. }
  14656. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  14657. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  14658. return model->vocab.id_to_token[token].text.c_str();
  14659. }
  14660. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  14661. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  14662. return model->vocab.id_to_token[token].score;
  14663. }
  14664. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  14665. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  14666. return model->vocab.id_to_token[token].type;
  14667. }
  14668. bool llama_token_is_eog(const struct llama_model * model, llama_token token) {
  14669. return token != -1 && (
  14670. token == llama_token_eos(model) ||
  14671. token == llama_token_eot(model)
  14672. );
  14673. }
  14674. llama_token llama_token_bos(const struct llama_model * model) {
  14675. return model->vocab.special_bos_id;
  14676. }
  14677. llama_token llama_token_eos(const struct llama_model * model) {
  14678. return model->vocab.special_eos_id;
  14679. }
  14680. llama_token llama_token_cls(const struct llama_model * model) {
  14681. return model->vocab.special_cls_id;
  14682. }
  14683. llama_token llama_token_sep(const struct llama_model * model) {
  14684. return model->vocab.special_sep_id;
  14685. }
  14686. llama_token llama_token_nl(const struct llama_model * model) {
  14687. return model->vocab.linefeed_id;
  14688. }
  14689. int32_t llama_add_bos_token(const struct llama_model * model) {
  14690. return model->vocab.special_add_bos;
  14691. }
  14692. int32_t llama_add_eos_token(const struct llama_model * model) {
  14693. return model->vocab.special_add_eos;
  14694. }
  14695. llama_token llama_token_prefix(const struct llama_model * model) {
  14696. return model->vocab.special_prefix_id;
  14697. }
  14698. llama_token llama_token_middle(const struct llama_model * model) {
  14699. return model->vocab.special_middle_id;
  14700. }
  14701. llama_token llama_token_suffix(const struct llama_model * model) {
  14702. return model->vocab.special_suffix_id;
  14703. }
  14704. llama_token llama_token_eot(const struct llama_model * model) {
  14705. return model->vocab.special_eot_id;
  14706. }
  14707. int32_t llama_tokenize(
  14708. const struct llama_model * model,
  14709. const char * text,
  14710. int32_t text_len,
  14711. llama_token * tokens,
  14712. int32_t n_tokens_max,
  14713. bool add_special,
  14714. bool parse_special) {
  14715. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_special, parse_special);
  14716. if (n_tokens_max < (int) res.size()) {
  14717. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  14718. return -((int) res.size());
  14719. }
  14720. for (size_t i = 0; i < res.size(); i++) {
  14721. tokens[i] = res[i];
  14722. }
  14723. return res.size();
  14724. }
  14725. static std::string llama_decode_text(const std::string & text) {
  14726. std::string decoded_text;
  14727. const auto cpts = unicode_cpts_from_utf8(text);
  14728. for (const auto cpt : cpts) {
  14729. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(cpt));
  14730. }
  14731. return decoded_text;
  14732. }
  14733. // does not write null-terminator to buf
  14734. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length, bool special) {
  14735. if (0 <= token && token < llama_n_vocab(model)) {
  14736. switch (llama_vocab_get_type(model->vocab)) {
  14737. case LLAMA_VOCAB_TYPE_WPM:
  14738. case LLAMA_VOCAB_TYPE_SPM: {
  14739. // NOTE: we accept all unsupported token types,
  14740. // suppressing them like CONTROL tokens.
  14741. if (llama_is_normal_token(model->vocab, token)) {
  14742. std::string result = model->vocab.id_to_token[token].text;
  14743. llama_unescape_whitespace(result);
  14744. if (length < (int) result.length()) {
  14745. return -(int) result.length();
  14746. }
  14747. memcpy(buf, result.c_str(), result.length());
  14748. return result.length();
  14749. } else if (
  14750. (llama_is_user_defined_token(model->vocab, token)) ||
  14751. (llama_is_control_token (model->vocab, token) && special)) {
  14752. std::string result = model->vocab.id_to_token[token].text;
  14753. if (length < (int) result.length()) {
  14754. return -(int) result.length();
  14755. }
  14756. memcpy(buf, result.c_str(), result.length());
  14757. return result.length();
  14758. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  14759. if (length < 3) {
  14760. return -3;
  14761. }
  14762. memcpy(buf, "\xe2\x96\x85", 3);
  14763. return 3;
  14764. } else if (llama_is_byte_token(model->vocab, token)) {
  14765. if (length < 1) {
  14766. return -1;
  14767. }
  14768. buf[0] = llama_token_to_byte(model->vocab, token);
  14769. return 1;
  14770. }
  14771. break;
  14772. }
  14773. case LLAMA_VOCAB_TYPE_BPE: {
  14774. // NOTE: we accept all unsupported token types,
  14775. // suppressing them like CONTROL tokens.
  14776. if (llama_is_normal_token(model->vocab, token)) {
  14777. std::string result = model->vocab.id_to_token[token].text;
  14778. result = llama_decode_text(result);
  14779. if (length < (int) result.length()) {
  14780. return -(int) result.length();
  14781. }
  14782. memcpy(buf, result.c_str(), result.length());
  14783. return result.length();
  14784. } else if (
  14785. (llama_is_user_defined_token(model->vocab, token)) ||
  14786. (llama_is_control_token (model->vocab, token) && special)) {
  14787. std::string result = model->vocab.id_to_token[token].text;
  14788. if (length < (int) result.length()) {
  14789. return -(int) result.length();
  14790. }
  14791. memcpy(buf, result.c_str(), result.length());
  14792. return result.length();
  14793. }
  14794. break;
  14795. }
  14796. default:
  14797. GGML_ASSERT(false);
  14798. }
  14799. }
  14800. return 0;
  14801. }
  14802. // trim whitespace from the beginning and end of a string
  14803. static std::string trim(const std::string & str) {
  14804. size_t start = 0;
  14805. size_t end = str.size();
  14806. while (start < end && isspace(str[start])) {
  14807. start += 1;
  14808. }
  14809. while (end > start && isspace(str[end - 1])) {
  14810. end -= 1;
  14811. }
  14812. return str.substr(start, end - start);
  14813. }
  14814. // Simple version of "llama_apply_chat_template" that only works with strings
  14815. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  14816. static int32_t llama_chat_apply_template_internal(
  14817. const std::string & tmpl,
  14818. const std::vector<const llama_chat_message *> & chat,
  14819. std::string & dest, bool add_ass) {
  14820. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  14821. std::stringstream ss;
  14822. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  14823. // chatml template
  14824. for (auto message : chat) {
  14825. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  14826. }
  14827. if (add_ass) {
  14828. ss << "<|im_start|>assistant\n";
  14829. }
  14830. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  14831. // llama2 template and its variants
  14832. // [variant] support system message
  14833. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  14834. // [variant] space before + after response
  14835. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  14836. // [variant] add BOS inside history
  14837. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  14838. // [variant] trim spaces from the input message
  14839. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  14840. // construct the prompt
  14841. bool is_inside_turn = true; // skip BOS at the beginning
  14842. ss << "[INST] ";
  14843. for (auto message : chat) {
  14844. std::string content = strip_message ? trim(message->content) : message->content;
  14845. std::string role(message->role);
  14846. if (!is_inside_turn) {
  14847. is_inside_turn = true;
  14848. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  14849. }
  14850. if (role == "system") {
  14851. if (support_system_message) {
  14852. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  14853. } else {
  14854. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  14855. ss << content << "\n";
  14856. }
  14857. } else if (role == "user") {
  14858. ss << content << " [/INST]";
  14859. } else {
  14860. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  14861. is_inside_turn = false;
  14862. }
  14863. }
  14864. // llama2 templates seem to not care about "add_generation_prompt"
  14865. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  14866. // zephyr template
  14867. for (auto message : chat) {
  14868. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  14869. }
  14870. if (add_ass) {
  14871. ss << "<|assistant|>\n";
  14872. }
  14873. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  14874. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  14875. for (auto message : chat) {
  14876. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  14877. ss << bos << message->role << "\n" << message->content << "</s>\n";
  14878. }
  14879. if (add_ass) {
  14880. ss << "<s>assistant\n";
  14881. }
  14882. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  14883. // google/gemma-7b-it
  14884. std::string system_prompt = "";
  14885. for (auto message : chat) {
  14886. std::string role(message->role);
  14887. if (role == "system") {
  14888. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  14889. system_prompt = trim(message->content);
  14890. continue;
  14891. }
  14892. // in gemma, "assistant" is "model"
  14893. role = role == "assistant" ? "model" : message->role;
  14894. ss << "<start_of_turn>" << role << "\n";
  14895. if (!system_prompt.empty() && role != "model") {
  14896. ss << system_prompt << "\n\n";
  14897. system_prompt = "";
  14898. }
  14899. ss << trim(message->content) << "<end_of_turn>\n";
  14900. }
  14901. if (add_ass) {
  14902. ss << "<start_of_turn>model\n";
  14903. }
  14904. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  14905. // OrionStarAI/Orion-14B-Chat
  14906. std::string system_prompt = "";
  14907. for (auto message : chat) {
  14908. std::string role(message->role);
  14909. if (role == "system") {
  14910. // there is no system message support, we will merge it with user prompt
  14911. system_prompt = message->content;
  14912. continue;
  14913. } else if (role == "user") {
  14914. ss << "Human: ";
  14915. if (!system_prompt.empty()) {
  14916. ss << system_prompt << "\n\n";
  14917. system_prompt = "";
  14918. }
  14919. ss << message->content << "\n\nAssistant: </s>";
  14920. } else {
  14921. ss << message->content << "</s>";
  14922. }
  14923. }
  14924. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  14925. // openchat/openchat-3.5-0106,
  14926. for (auto message : chat) {
  14927. std::string role(message->role);
  14928. if (role == "system") {
  14929. ss << message->content << "<|end_of_turn|>";
  14930. } else {
  14931. role[0] = toupper(role[0]);
  14932. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  14933. }
  14934. }
  14935. if (add_ass) {
  14936. ss << "GPT4 Correct Assistant:";
  14937. }
  14938. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  14939. // eachadea/vicuna-13b-1.1 (and Orca variant)
  14940. for (auto message : chat) {
  14941. std::string role(message->role);
  14942. if (role == "system") {
  14943. // Orca-Vicuna variant uses a system prefix
  14944. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  14945. ss << "SYSTEM: " << message->content << "\n";
  14946. } else {
  14947. ss << message->content << "\n\n";
  14948. }
  14949. } else if (role == "user") {
  14950. ss << "USER: " << message->content << "\n";
  14951. } else if (role == "assistant") {
  14952. ss << "ASSISTANT: " << message->content << "</s>\n";
  14953. }
  14954. }
  14955. if (add_ass) {
  14956. ss << "ASSISTANT:";
  14957. }
  14958. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  14959. // deepseek-ai/deepseek-coder-33b-instruct
  14960. for (auto message : chat) {
  14961. std::string role(message->role);
  14962. if (role == "system") {
  14963. ss << message->content;
  14964. } else if (role == "user") {
  14965. ss << "### Instruction:\n" << message->content << "\n";
  14966. } else if (role == "assistant") {
  14967. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  14968. }
  14969. }
  14970. if (add_ass) {
  14971. ss << "### Response:\n";
  14972. }
  14973. } else if (tmpl == "command-r" || (tmpl.find("<|START_OF_TURN_TOKEN|>") != std::string::npos && tmpl.find("<|USER_TOKEN|>") != std::string::npos)) {
  14974. // CohereForAI/c4ai-command-r-plus
  14975. for (auto message : chat) {
  14976. std::string role(message->role);
  14977. if (role == "system") {
  14978. ss << "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  14979. } else if (role == "user") {
  14980. ss << "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  14981. } else if (role == "assistant") {
  14982. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>" << trim(message->content) << "<|END_OF_TURN_TOKEN|>";
  14983. }
  14984. }
  14985. if (add_ass) {
  14986. ss << "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>";
  14987. }
  14988. } else if (tmpl == "llama3" || (tmpl.find("<|start_header_id|>") != std::string::npos && tmpl.find("<|end_header_id|>") != std::string::npos)) {
  14989. // Llama 3
  14990. for (auto message : chat) {
  14991. std::string role(message->role);
  14992. ss << "<|start_header_id|>" << role << "<|end_header_id|>\n\n" << trim(message->content) << "<|eot_id|>";
  14993. }
  14994. if (add_ass) {
  14995. ss << "<|start_header_id|>assistant<|end_header_id|>\n\n";
  14996. }
  14997. } else if (tmpl == "phi3" || (tmpl.find("<|assistant|>") != std::string::npos && tmpl.find("<|end|>") != std::string::npos )) {
  14998. // Phi 3
  14999. for (auto message : chat) {
  15000. std::string role(message->role);
  15001. ss << "<|" << role << "|>\n" << trim(message->content) << "<|end|>\n";
  15002. }
  15003. if (add_ass) {
  15004. ss << "<|assistant|>\n";
  15005. }
  15006. } else {
  15007. // template not supported
  15008. return -1;
  15009. }
  15010. dest = ss.str();
  15011. return dest.size();
  15012. }
  15013. LLAMA_API int32_t llama_chat_apply_template(
  15014. const struct llama_model * model,
  15015. const char * tmpl,
  15016. const struct llama_chat_message * chat,
  15017. size_t n_msg,
  15018. bool add_ass,
  15019. char * buf,
  15020. int32_t length) {
  15021. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  15022. if (tmpl == nullptr) {
  15023. GGML_ASSERT(model != nullptr);
  15024. // load template from model
  15025. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  15026. std::string template_key = "tokenizer.chat_template";
  15027. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  15028. if (res < 0) {
  15029. // worst case: there is no information about template, we will use chatml by default
  15030. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  15031. } else {
  15032. curr_tmpl = std::string(model_template.data(), model_template.size());
  15033. }
  15034. }
  15035. // format the chat to string
  15036. std::vector<const llama_chat_message *> chat_vec;
  15037. chat_vec.resize(n_msg);
  15038. for (size_t i = 0; i < n_msg; i++) {
  15039. chat_vec[i] = &chat[i];
  15040. }
  15041. std::string formatted_chat;
  15042. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  15043. if (res < 0) {
  15044. return res;
  15045. }
  15046. if (buf && length > 0) {
  15047. strncpy(buf, formatted_chat.c_str(), length);
  15048. }
  15049. return res;
  15050. }
  15051. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  15052. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  15053. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  15054. return strlen(split_path);
  15055. }
  15056. return 0;
  15057. }
  15058. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  15059. std::string str_split_path(split_path);
  15060. char postfix[32];
  15061. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  15062. std::string str_postfix(postfix);
  15063. // check if dest ends with postfix
  15064. int size_prefix = str_split_path.size() - str_postfix.size();
  15065. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  15066. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  15067. return size_prefix;
  15068. }
  15069. return 0;
  15070. }
  15071. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  15072. struct llama_timings result = {
  15073. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  15074. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  15075. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  15076. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  15077. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  15078. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  15079. /*.n_sample =*/ std::max(1, ctx->n_sample),
  15080. /*.n_p_eval =*/ std::max(0, ctx->n_p_eval),
  15081. /*.n_eval =*/ std::max(1, ctx->n_eval),
  15082. };
  15083. return result;
  15084. }
  15085. void llama_print_timings(struct llama_context * ctx) {
  15086. const llama_timings timings = llama_get_timings(ctx);
  15087. LLAMA_LOG_INFO("\n");
  15088. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  15089. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15090. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  15091. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  15092. __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);
  15093. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  15094. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  15095. 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));
  15096. }
  15097. void llama_reset_timings(struct llama_context * ctx) {
  15098. ctx->t_start_us = ggml_time_us();
  15099. ctx->t_sample_us = ctx->n_sample = 0;
  15100. ctx->t_eval_us = ctx->n_eval = 0;
  15101. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  15102. }
  15103. const char * llama_print_system_info(void) {
  15104. static std::string s;
  15105. s = "";
  15106. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  15107. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  15108. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  15109. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  15110. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  15111. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  15112. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  15113. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  15114. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  15115. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  15116. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  15117. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  15118. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  15119. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  15120. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  15121. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  15122. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  15123. #ifdef GGML_USE_LLAMAFILE
  15124. s += "LLAMAFILE = 1 | ";
  15125. #else
  15126. s += "LLAMAFILE = 0 | ";
  15127. #endif
  15128. return s.c_str();
  15129. }
  15130. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  15131. fprintf(stream, "\n");
  15132. fprintf(stream, "###########\n");
  15133. fprintf(stream, "# Timings #\n");
  15134. fprintf(stream, "###########\n");
  15135. fprintf(stream, "\n");
  15136. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  15137. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  15138. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  15139. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  15140. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  15141. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  15142. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  15143. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  15144. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  15145. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  15146. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  15147. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  15148. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  15149. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  15150. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  15151. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  15152. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  15153. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  15154. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  15155. }
  15156. // For internal test use
  15157. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  15158. struct llama_context * ctx
  15159. ) {
  15160. return ctx->model.tensors_by_name;
  15161. }
  15162. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  15163. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  15164. g_state.log_callback_user_data = user_data;
  15165. #ifdef GGML_USE_METAL
  15166. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15167. #elif defined(GGML_USE_CUDA)
  15168. ggml_backend_cuda_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  15169. #endif
  15170. }
  15171. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  15172. va_list args_copy;
  15173. va_copy(args_copy, args);
  15174. char buffer[128];
  15175. int len = vsnprintf(buffer, 128, format, args);
  15176. if (len < 128) {
  15177. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  15178. } else {
  15179. char* buffer2 = new char[len+1];
  15180. vsnprintf(buffer2, len+1, format, args_copy);
  15181. buffer2[len] = 0;
  15182. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  15183. delete[] buffer2;
  15184. }
  15185. va_end(args_copy);
  15186. }
  15187. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  15188. va_list args;
  15189. va_start(args, format);
  15190. llama_log_internal_v(level, format, args);
  15191. va_end(args);
  15192. }
  15193. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  15194. (void) level;
  15195. (void) user_data;
  15196. fputs(text, stderr);
  15197. fflush(stderr);
  15198. }