llama.cpp 657 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683
  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_CUDA
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.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 <initializer_list>
  72. #include <locale>
  73. #include <map>
  74. #include <memory>
  75. #include <mutex>
  76. #include <numeric>
  77. #include <queue>
  78. #include <random>
  79. #include <regex>
  80. #include <set>
  81. #include <sstream>
  82. #include <thread>
  83. #include <type_traits>
  84. #include <unordered_map>
  85. #if defined(_MSC_VER)
  86. #pragma warning(disable: 4244 4267) // possible loss of data
  87. #endif
  88. #ifdef __GNUC__
  89. #ifdef __MINGW32__
  90. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  93. #endif
  94. #else
  95. #define LLAMA_ATTRIBUTE_FORMAT(...)
  96. #endif
  97. #define LLAMA_MAX_NODES 8192
  98. #define LLAMA_MAX_EXPERTS 8
  99. //
  100. // logging
  101. //
  102. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  103. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  104. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  105. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  106. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  107. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  108. //
  109. // helpers
  110. //
  111. static size_t utf8_len(char src) {
  112. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  113. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  114. return lookup[highbits];
  115. }
  116. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  117. std::string result;
  118. for (size_t pos = 0; ; pos += search.length()) {
  119. auto new_pos = s.find(search, pos);
  120. if (new_pos == std::string::npos) {
  121. result += s.substr(pos, s.size() - pos);
  122. break;
  123. }
  124. result += s.substr(pos, new_pos - pos) + replace;
  125. pos = new_pos;
  126. }
  127. s = std::move(result);
  128. }
  129. static bool is_float_close(float a, float b, float abs_tol) {
  130. // Check for non-negative tolerance
  131. if (abs_tol < 0.0) {
  132. throw std::invalid_argument("Tolerance must be non-negative");
  133. }
  134. // Exact equality check
  135. if (a == b) {
  136. return true;
  137. }
  138. // Check for infinities
  139. if (std::isinf(a) || std::isinf(b)) {
  140. return false;
  141. }
  142. // Regular comparison using the provided absolute tolerance
  143. return std::fabs(b - a) <= abs_tol;
  144. }
  145. static void zeros(std::ofstream & file, size_t n) {
  146. char zero = 0;
  147. for (size_t i = 0; i < n; ++i) {
  148. file.write(&zero, 1);
  149. }
  150. }
  151. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  152. static std::string format(const char * fmt, ...) {
  153. va_list ap;
  154. va_list ap2;
  155. va_start(ap, fmt);
  156. va_copy(ap2, ap);
  157. int size = vsnprintf(NULL, 0, fmt, ap);
  158. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  159. std::vector<char> buf(size + 1);
  160. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  161. GGML_ASSERT(size2 == size);
  162. va_end(ap2);
  163. va_end(ap);
  164. return std::string(buf.data(), size);
  165. }
  166. //
  167. // gguf constants (sync with gguf.py)
  168. //
  169. enum llm_arch {
  170. LLM_ARCH_LLAMA,
  171. LLM_ARCH_FALCON,
  172. LLM_ARCH_BAICHUAN,
  173. LLM_ARCH_GROK,
  174. LLM_ARCH_GPT2,
  175. LLM_ARCH_GPTJ,
  176. LLM_ARCH_GPTNEOX,
  177. LLM_ARCH_MPT,
  178. LLM_ARCH_STARCODER,
  179. LLM_ARCH_PERSIMMON,
  180. LLM_ARCH_REFACT,
  181. LLM_ARCH_BERT,
  182. LLM_ARCH_NOMIC_BERT,
  183. LLM_ARCH_BLOOM,
  184. LLM_ARCH_STABLELM,
  185. LLM_ARCH_QWEN,
  186. LLM_ARCH_QWEN2,
  187. LLM_ARCH_PHI2,
  188. LLM_ARCH_PLAMO,
  189. LLM_ARCH_CODESHELL,
  190. LLM_ARCH_ORION,
  191. LLM_ARCH_INTERNLM2,
  192. LLM_ARCH_MINICPM,
  193. LLM_ARCH_GEMMA,
  194. LLM_ARCH_STARCODER2,
  195. LLM_ARCH_MAMBA,
  196. LLM_ARCH_XVERSE,
  197. LLM_ARCH_COMMAND_R,
  198. LLM_ARCH_UNKNOWN,
  199. };
  200. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  201. { LLM_ARCH_LLAMA, "llama" },
  202. { LLM_ARCH_FALCON, "falcon" },
  203. { LLM_ARCH_GROK, "grok" },
  204. { LLM_ARCH_GPT2, "gpt2" },
  205. { LLM_ARCH_GPTJ, "gptj" },
  206. { LLM_ARCH_GPTNEOX, "gptneox" },
  207. { LLM_ARCH_MPT, "mpt" },
  208. { LLM_ARCH_BAICHUAN, "baichuan" },
  209. { LLM_ARCH_STARCODER, "starcoder" },
  210. { LLM_ARCH_PERSIMMON, "persimmon" },
  211. { LLM_ARCH_REFACT, "refact" },
  212. { LLM_ARCH_BERT, "bert" },
  213. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  214. { LLM_ARCH_BLOOM, "bloom" },
  215. { LLM_ARCH_STABLELM, "stablelm" },
  216. { LLM_ARCH_QWEN, "qwen" },
  217. { LLM_ARCH_QWEN2, "qwen2" },
  218. { LLM_ARCH_PHI2, "phi2" },
  219. { LLM_ARCH_PLAMO, "plamo" },
  220. { LLM_ARCH_CODESHELL, "codeshell" },
  221. { LLM_ARCH_ORION, "orion" },
  222. { LLM_ARCH_INTERNLM2, "internlm2" },
  223. { LLM_ARCH_MINICPM, "minicpm" },
  224. { LLM_ARCH_GEMMA, "gemma" },
  225. { LLM_ARCH_STARCODER2, "starcoder2" },
  226. { LLM_ARCH_MAMBA, "mamba" },
  227. { LLM_ARCH_XVERSE, "xverse" },
  228. { LLM_ARCH_COMMAND_R, "command-r" },
  229. { LLM_ARCH_UNKNOWN, "(unknown)" },
  230. };
  231. enum llm_kv {
  232. LLM_KV_GENERAL_ARCHITECTURE,
  233. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  234. LLM_KV_GENERAL_ALIGNMENT,
  235. LLM_KV_GENERAL_NAME,
  236. LLM_KV_GENERAL_AUTHOR,
  237. LLM_KV_GENERAL_VERSION,
  238. LLM_KV_GENERAL_URL,
  239. LLM_KV_GENERAL_DESCRIPTION,
  240. LLM_KV_GENERAL_LICENSE,
  241. LLM_KV_GENERAL_SOURCE_URL,
  242. LLM_KV_GENERAL_SOURCE_HF_REPO,
  243. LLM_KV_VOCAB_SIZE,
  244. LLM_KV_CONTEXT_LENGTH,
  245. LLM_KV_EMBEDDING_LENGTH,
  246. LLM_KV_BLOCK_COUNT,
  247. LLM_KV_FEED_FORWARD_LENGTH,
  248. LLM_KV_USE_PARALLEL_RESIDUAL,
  249. LLM_KV_TENSOR_DATA_LAYOUT,
  250. LLM_KV_EXPERT_COUNT,
  251. LLM_KV_EXPERT_USED_COUNT,
  252. LLM_KV_POOLING_TYPE,
  253. LLM_KV_LOGIT_SCALE,
  254. LLM_KV_ATTENTION_HEAD_COUNT,
  255. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  256. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  257. LLM_KV_ATTENTION_CLAMP_KQV,
  258. LLM_KV_ATTENTION_KEY_LENGTH,
  259. LLM_KV_ATTENTION_VALUE_LENGTH,
  260. LLM_KV_ATTENTION_LAYERNORM_EPS,
  261. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  262. LLM_KV_ATTENTION_CAUSAL,
  263. LLM_KV_ROPE_DIMENSION_COUNT,
  264. LLM_KV_ROPE_FREQ_BASE,
  265. LLM_KV_ROPE_SCALE_LINEAR,
  266. LLM_KV_ROPE_SCALING_TYPE,
  267. LLM_KV_ROPE_SCALING_FACTOR,
  268. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  269. LLM_KV_ROPE_SCALING_FINETUNED,
  270. LLM_KV_SPLIT_NO,
  271. LLM_KV_SPLIT_COUNT,
  272. LLM_KV_SPLIT_TENSORS_COUNT,
  273. LLM_KV_SSM_INNER_SIZE,
  274. LLM_KV_SSM_CONV_KERNEL,
  275. LLM_KV_SSM_STATE_SIZE,
  276. LLM_KV_SSM_TIME_STEP_RANK,
  277. LLM_KV_TOKENIZER_MODEL,
  278. LLM_KV_TOKENIZER_LIST,
  279. LLM_KV_TOKENIZER_TOKEN_TYPE,
  280. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  281. LLM_KV_TOKENIZER_SCORES,
  282. LLM_KV_TOKENIZER_MERGES,
  283. LLM_KV_TOKENIZER_BOS_ID,
  284. LLM_KV_TOKENIZER_EOS_ID,
  285. LLM_KV_TOKENIZER_UNK_ID,
  286. LLM_KV_TOKENIZER_SEP_ID,
  287. LLM_KV_TOKENIZER_PAD_ID,
  288. LLM_KV_TOKENIZER_CLS_ID,
  289. LLM_KV_TOKENIZER_MASK_ID,
  290. LLM_KV_TOKENIZER_ADD_BOS,
  291. LLM_KV_TOKENIZER_ADD_EOS,
  292. LLM_KV_TOKENIZER_ADD_PREFIX,
  293. LLM_KV_TOKENIZER_HF_JSON,
  294. LLM_KV_TOKENIZER_RWKV,
  295. };
  296. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  297. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  298. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  299. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  300. { LLM_KV_GENERAL_NAME, "general.name" },
  301. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  302. { LLM_KV_GENERAL_VERSION, "general.version" },
  303. { LLM_KV_GENERAL_URL, "general.url" },
  304. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  305. { LLM_KV_GENERAL_LICENSE, "general.license" },
  306. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  307. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  308. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  309. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  310. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  311. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  312. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  313. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  314. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  315. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  316. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  317. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  318. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  319. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  320. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  321. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  322. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  323. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  324. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  325. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  326. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  327. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  328. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  329. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  330. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  331. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  332. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  333. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  334. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  335. { LLM_KV_SPLIT_NO, "split.no" },
  336. { LLM_KV_SPLIT_COUNT, "split.count" },
  337. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  338. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  339. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  340. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  341. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  342. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  343. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  344. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  345. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  346. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  347. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  348. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  349. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  350. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  351. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  352. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  353. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  354. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  355. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  356. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  357. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  358. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  359. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  360. };
  361. struct LLM_KV {
  362. LLM_KV(llm_arch arch) : arch(arch) {}
  363. llm_arch arch;
  364. std::string operator()(llm_kv kv) const {
  365. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  366. }
  367. };
  368. enum llm_tensor {
  369. LLM_TENSOR_TOKEN_EMBD,
  370. LLM_TENSOR_TOKEN_EMBD_NORM,
  371. LLM_TENSOR_TOKEN_TYPES,
  372. LLM_TENSOR_POS_EMBD,
  373. LLM_TENSOR_OUTPUT,
  374. LLM_TENSOR_OUTPUT_NORM,
  375. LLM_TENSOR_ROPE_FREQS,
  376. LLM_TENSOR_ATTN_Q,
  377. LLM_TENSOR_ATTN_K,
  378. LLM_TENSOR_ATTN_V,
  379. LLM_TENSOR_ATTN_QKV,
  380. LLM_TENSOR_ATTN_OUT,
  381. LLM_TENSOR_ATTN_NORM,
  382. LLM_TENSOR_ATTN_NORM_2,
  383. LLM_TENSOR_ATTN_OUT_NORM,
  384. LLM_TENSOR_ATTN_ROT_EMBD,
  385. LLM_TENSOR_FFN_GATE_INP,
  386. LLM_TENSOR_FFN_NORM,
  387. LLM_TENSOR_FFN_GATE,
  388. LLM_TENSOR_FFN_DOWN,
  389. LLM_TENSOR_FFN_UP,
  390. LLM_TENSOR_FFN_ACT,
  391. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  392. LLM_TENSOR_FFN_GATE_EXP,
  393. LLM_TENSOR_FFN_UP_EXP,
  394. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  395. LLM_TENSOR_FFN_GATE_EXPS,
  396. LLM_TENSOR_FFN_UP_EXPS,
  397. LLM_TENSOR_ATTN_Q_NORM,
  398. LLM_TENSOR_ATTN_K_NORM,
  399. LLM_TENSOR_LAYER_OUT_NORM,
  400. LLM_TENSOR_SSM_IN,
  401. LLM_TENSOR_SSM_CONV1D,
  402. LLM_TENSOR_SSM_X,
  403. LLM_TENSOR_SSM_DT,
  404. LLM_TENSOR_SSM_A,
  405. LLM_TENSOR_SSM_D,
  406. LLM_TENSOR_SSM_OUT,
  407. };
  408. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  409. {
  410. LLM_ARCH_LLAMA,
  411. {
  412. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  413. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  414. { LLM_TENSOR_OUTPUT, "output" },
  415. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  416. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  417. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  418. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  419. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  420. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  421. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  422. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  423. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  424. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  425. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  426. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  427. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  428. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  429. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  430. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  431. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  432. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  433. },
  434. },
  435. {
  436. LLM_ARCH_BAICHUAN,
  437. {
  438. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  439. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  440. { LLM_TENSOR_OUTPUT, "output" },
  441. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  442. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  443. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  444. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  445. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  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. },
  453. },
  454. {
  455. LLM_ARCH_FALCON,
  456. {
  457. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  458. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  459. { LLM_TENSOR_OUTPUT, "output" },
  460. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  461. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  462. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  463. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  465. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  466. },
  467. },
  468. {
  469. LLM_ARCH_GROK,
  470. {
  471. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  472. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  473. { LLM_TENSOR_OUTPUT, "output" },
  474. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  475. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  476. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  477. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  478. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  479. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  480. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  481. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  482. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  483. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  484. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  485. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  486. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  487. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  488. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  489. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  490. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  491. },
  492. },
  493. {
  494. LLM_ARCH_GPT2,
  495. {
  496. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  497. { LLM_TENSOR_POS_EMBD, "position_embd" },
  498. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  499. { LLM_TENSOR_OUTPUT, "output" },
  500. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  501. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  502. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  503. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  504. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  505. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  506. },
  507. },
  508. {
  509. LLM_ARCH_GPTJ,
  510. {
  511. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  512. },
  513. },
  514. {
  515. LLM_ARCH_GPTNEOX,
  516. {
  517. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  518. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  519. { LLM_TENSOR_OUTPUT, "output" },
  520. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  521. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  522. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  523. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  524. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  525. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  526. },
  527. },
  528. {
  529. LLM_ARCH_PERSIMMON,
  530. {
  531. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  532. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  533. { LLM_TENSOR_OUTPUT, "output"},
  534. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  535. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  536. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  537. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  538. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  539. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  540. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  541. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  542. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  543. },
  544. },
  545. {
  546. LLM_ARCH_MPT,
  547. {
  548. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  549. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  550. { LLM_TENSOR_OUTPUT, "output"},
  551. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  552. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  553. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  554. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  555. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  556. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  557. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  558. { LLM_TENSOR_POS_EMBD, "position_embd" },
  559. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  560. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  561. },
  562. },
  563. {
  564. LLM_ARCH_STARCODER,
  565. {
  566. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  567. { LLM_TENSOR_POS_EMBD, "position_embd" },
  568. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  569. { LLM_TENSOR_OUTPUT, "output" },
  570. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  571. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  572. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  573. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  574. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  575. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  576. },
  577. },
  578. {
  579. LLM_ARCH_REFACT,
  580. {
  581. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  582. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  583. { LLM_TENSOR_OUTPUT, "output" },
  584. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  585. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  586. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  587. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  588. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  589. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  590. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  591. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  592. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  593. },
  594. },
  595. {
  596. LLM_ARCH_BERT,
  597. {
  598. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  599. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  600. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  601. { LLM_TENSOR_POS_EMBD, "position_embd" },
  602. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  603. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  604. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  605. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  606. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  607. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  608. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  609. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  610. },
  611. },
  612. {
  613. LLM_ARCH_NOMIC_BERT,
  614. {
  615. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  616. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  617. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  618. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  619. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  620. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  621. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  622. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  623. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  624. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  625. },
  626. },
  627. {
  628. LLM_ARCH_BLOOM,
  629. {
  630. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  631. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  632. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  633. { LLM_TENSOR_OUTPUT, "output" },
  634. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  635. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  636. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  637. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  638. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  639. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  640. },
  641. },
  642. {
  643. LLM_ARCH_STABLELM,
  644. {
  645. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  646. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  647. { LLM_TENSOR_OUTPUT, "output" },
  648. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  649. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  650. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  651. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  652. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  653. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  654. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  655. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  656. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  657. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  658. },
  659. },
  660. {
  661. LLM_ARCH_QWEN,
  662. {
  663. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  664. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  665. { LLM_TENSOR_OUTPUT, "output" },
  666. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  667. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  668. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  669. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  670. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  671. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  672. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  673. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  674. },
  675. },
  676. {
  677. LLM_ARCH_QWEN2,
  678. {
  679. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  680. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  681. { LLM_TENSOR_OUTPUT, "output" },
  682. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  683. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  684. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  685. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  686. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  687. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  688. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  689. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  690. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  691. },
  692. },
  693. {
  694. LLM_ARCH_PHI2,
  695. {
  696. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  697. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  698. { LLM_TENSOR_OUTPUT, "output" },
  699. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  700. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  701. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  702. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  703. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  704. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  705. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  706. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  707. },
  708. },
  709. {
  710. LLM_ARCH_PLAMO,
  711. {
  712. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  713. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  714. { LLM_TENSOR_OUTPUT, "output" },
  715. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  716. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  717. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  718. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  719. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  720. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  721. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  722. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  723. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  724. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  725. },
  726. },
  727. {
  728. LLM_ARCH_CODESHELL,
  729. {
  730. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  731. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  732. { LLM_TENSOR_OUTPUT, "output" },
  733. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  736. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  737. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  738. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  739. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  740. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  741. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  742. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  743. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  744. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  745. },
  746. },
  747. {
  748. LLM_ARCH_ORION,
  749. {
  750. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  751. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  752. { LLM_TENSOR_OUTPUT, "output" },
  753. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  754. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  755. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  756. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  757. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  758. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  759. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  760. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  761. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  762. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  763. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  764. },
  765. },
  766. {
  767. LLM_ARCH_INTERNLM2,
  768. {
  769. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  770. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  771. { LLM_TENSOR_OUTPUT, "output" },
  772. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  773. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  774. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  775. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  776. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  777. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  778. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  779. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  780. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  781. },
  782. },
  783. {
  784. LLM_ARCH_MINICPM,
  785. {
  786. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  787. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  788. { LLM_TENSOR_OUTPUT, "output" },
  789. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  790. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  791. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  792. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  793. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  794. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  795. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  796. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  797. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  798. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  799. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  800. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  801. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  802. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  803. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  804. },
  805. },
  806. {
  807. LLM_ARCH_GEMMA,
  808. {
  809. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  810. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  811. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  812. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  813. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  814. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  815. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  816. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  817. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  818. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  819. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  820. },
  821. },
  822. {
  823. LLM_ARCH_STARCODER2,
  824. {
  825. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  826. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  827. { LLM_TENSOR_OUTPUT, "output" },
  828. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  829. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  830. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  831. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  832. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  833. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  834. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  835. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  836. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  837. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  838. },
  839. },
  840. {
  841. LLM_ARCH_MAMBA,
  842. {
  843. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  844. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  845. { LLM_TENSOR_OUTPUT, "output" },
  846. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  847. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  848. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  849. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  850. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  851. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  852. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  853. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  854. },
  855. },
  856. {
  857. LLM_ARCH_XVERSE,
  858. {
  859. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  860. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  861. { LLM_TENSOR_OUTPUT, "output" },
  862. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  863. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  864. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  865. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  866. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  867. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  868. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  869. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  870. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  871. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  872. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  873. },
  874. },
  875. {
  876. LLM_ARCH_COMMAND_R,
  877. {
  878. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  879. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  880. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  881. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  882. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  883. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  884. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  885. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  886. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  887. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  888. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  889. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  890. },
  891. },
  892. {
  893. LLM_ARCH_UNKNOWN,
  894. {
  895. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  896. },
  897. },
  898. };
  899. static llm_arch llm_arch_from_string(const std::string & name) {
  900. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  901. if (kv.second == name) {
  902. return kv.first;
  903. }
  904. }
  905. return LLM_ARCH_UNKNOWN;
  906. }
  907. // helper to handle gguf constants
  908. // usage:
  909. //
  910. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  911. //
  912. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  913. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  914. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  915. //
  916. struct LLM_TN {
  917. LLM_TN(llm_arch arch) : arch(arch) {}
  918. llm_arch arch;
  919. std::string operator()(llm_tensor tensor) const {
  920. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  921. return "__missing__";
  922. }
  923. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  924. }
  925. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  926. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  927. return "__missing__";
  928. }
  929. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  930. }
  931. std::string operator()(llm_tensor tensor, int bid) const {
  932. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  933. return "__missing__";
  934. }
  935. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  936. }
  937. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  938. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  939. return "__missing__";
  940. }
  941. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  942. }
  943. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  944. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  945. return "__missing__";
  946. }
  947. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  948. }
  949. };
  950. //
  951. // gguf helpers
  952. //
  953. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  954. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  955. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  956. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  957. };
  958. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  959. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  960. if (kv.second == name) {
  961. return (llama_rope_scaling_type) kv.first;
  962. }
  963. }
  964. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  965. }
  966. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  967. switch (type) {
  968. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  969. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  970. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  971. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  972. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  973. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  974. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  975. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  976. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  977. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  978. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  979. default: return format("unknown type %d", type);
  980. }
  981. }
  982. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  983. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  984. switch (type) {
  985. case GGUF_TYPE_STRING:
  986. return gguf_get_val_str(ctx_gguf, i);
  987. case GGUF_TYPE_ARRAY:
  988. {
  989. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  990. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  991. const void * data = gguf_get_arr_data(ctx_gguf, i);
  992. std::stringstream ss;
  993. ss << "[";
  994. for (int j = 0; j < arr_n; j++) {
  995. if (arr_type == GGUF_TYPE_STRING) {
  996. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  997. // escape quotes
  998. replace_all(val, "\\", "\\\\");
  999. replace_all(val, "\"", "\\\"");
  1000. ss << '"' << val << '"';
  1001. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1002. ss << "???";
  1003. } else {
  1004. ss << gguf_data_to_str(arr_type, data, j);
  1005. }
  1006. if (j < arr_n - 1) {
  1007. ss << ", ";
  1008. }
  1009. }
  1010. ss << "]";
  1011. return ss.str();
  1012. }
  1013. default:
  1014. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1015. }
  1016. }
  1017. //
  1018. // llama helpers
  1019. //
  1020. #if defined(_WIN32)
  1021. static std::string llama_format_win_err(DWORD err) {
  1022. LPSTR buf;
  1023. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1024. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1025. if (!size) {
  1026. return "FormatMessageA failed";
  1027. }
  1028. std::string ret(buf, size);
  1029. LocalFree(buf);
  1030. return ret;
  1031. }
  1032. #endif
  1033. template <typename T>
  1034. struct no_init {
  1035. T value;
  1036. no_init() { /* do nothing */ }
  1037. };
  1038. struct llama_file {
  1039. // use FILE * so we don't have to re-open the file to mmap
  1040. FILE * fp;
  1041. size_t size;
  1042. llama_file(const char * fname, const char * mode) {
  1043. fp = ggml_fopen(fname, mode);
  1044. if (fp == NULL) {
  1045. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1046. }
  1047. seek(0, SEEK_END);
  1048. size = tell();
  1049. seek(0, SEEK_SET);
  1050. }
  1051. size_t tell() const {
  1052. #ifdef _WIN32
  1053. __int64 ret = _ftelli64(fp);
  1054. #else
  1055. long ret = std::ftell(fp);
  1056. #endif
  1057. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1058. return (size_t) ret;
  1059. }
  1060. void seek(size_t offset, int whence) const {
  1061. #ifdef _WIN32
  1062. int ret = _fseeki64(fp, (__int64) offset, whence);
  1063. #else
  1064. int ret = std::fseek(fp, (long) offset, whence);
  1065. #endif
  1066. GGML_ASSERT(ret == 0); // same
  1067. }
  1068. void read_raw(void * ptr, size_t len) const {
  1069. if (len == 0) {
  1070. return;
  1071. }
  1072. errno = 0;
  1073. std::size_t ret = std::fread(ptr, len, 1, fp);
  1074. if (ferror(fp)) {
  1075. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1076. }
  1077. if (ret != 1) {
  1078. throw std::runtime_error("unexpectedly reached end of file");
  1079. }
  1080. }
  1081. uint32_t read_u32() const {
  1082. uint32_t ret;
  1083. read_raw(&ret, sizeof(ret));
  1084. return ret;
  1085. }
  1086. void write_raw(const void * ptr, size_t len) const {
  1087. if (len == 0) {
  1088. return;
  1089. }
  1090. errno = 0;
  1091. size_t ret = std::fwrite(ptr, len, 1, fp);
  1092. if (ret != 1) {
  1093. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1094. }
  1095. }
  1096. void write_u32(std::uint32_t val) const {
  1097. write_raw(&val, sizeof(val));
  1098. }
  1099. ~llama_file() {
  1100. if (fp) {
  1101. std::fclose(fp);
  1102. }
  1103. }
  1104. };
  1105. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1106. struct llama_mmap {
  1107. void * addr;
  1108. size_t size;
  1109. llama_mmap(const llama_mmap &) = delete;
  1110. #ifdef _POSIX_MAPPED_FILES
  1111. static constexpr bool SUPPORTED = true;
  1112. // list of mapped fragments (first_offset, last_offset)
  1113. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1114. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1115. size = file->size;
  1116. int fd = fileno(file->fp);
  1117. int flags = MAP_SHARED;
  1118. // prefetch/readahead impairs performance on NUMA systems
  1119. if (numa) { prefetch = 0; }
  1120. #ifdef __linux__
  1121. // advise the kernel to read the file sequentially (increases readahead)
  1122. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1123. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1124. strerror(errno));
  1125. }
  1126. if (prefetch) { flags |= MAP_POPULATE; }
  1127. #endif
  1128. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1129. if (addr == MAP_FAILED) { // NOLINT
  1130. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1131. }
  1132. if (prefetch > 0) {
  1133. // advise the kernel to preload the mapped memory
  1134. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1135. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1136. strerror(errno));
  1137. }
  1138. }
  1139. if (numa) {
  1140. // advise the kernel not to use readahead
  1141. // (because the next page might not belong on the same node)
  1142. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1143. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1144. strerror(errno));
  1145. }
  1146. }
  1147. // initialize list of mapped_fragments
  1148. mapped_fragments.emplace_back(0, file->size);
  1149. }
  1150. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1151. // align first to the next page
  1152. size_t offset_in_page = *first & (page_size - 1);
  1153. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1154. *first += offset_to_page;
  1155. // align last to the previous page
  1156. *last = *last & ~(page_size - 1);
  1157. if (*last <= *first) {
  1158. *last = *first;
  1159. }
  1160. }
  1161. // partially unmap the file in the range [first, last)
  1162. void unmap_fragment(size_t first, size_t last) {
  1163. // note: this function must not be called multiple times with overlapping ranges
  1164. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1165. int page_size = sysconf(_SC_PAGESIZE);
  1166. align_range(&first, &last, page_size);
  1167. size_t len = last - first;
  1168. if (len == 0) {
  1169. return;
  1170. }
  1171. GGML_ASSERT(first % page_size == 0);
  1172. GGML_ASSERT(last % page_size == 0);
  1173. GGML_ASSERT(last > first);
  1174. void * next_page_start = (uint8_t *) addr + first;
  1175. // unmap the range
  1176. if (munmap(next_page_start, len)) {
  1177. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1178. }
  1179. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1180. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1181. for (const auto & frag : mapped_fragments) {
  1182. if (frag.first < first && frag.second > last) {
  1183. // the range is in the middle of the fragment, split it
  1184. new_mapped_fragments.emplace_back(frag.first, first);
  1185. new_mapped_fragments.emplace_back(last, frag.second);
  1186. } else if (frag.first < first && frag.second > first) {
  1187. // the range starts in the middle of the fragment
  1188. new_mapped_fragments.emplace_back(frag.first, first);
  1189. } else if (frag.first < last && frag.second > last) {
  1190. // the range ends in the middle of the fragment
  1191. new_mapped_fragments.emplace_back(last, frag.second);
  1192. } else if (frag.first >= first && frag.second <= last) {
  1193. // the range covers the entire fragment
  1194. } else {
  1195. // the range is outside the fragment
  1196. new_mapped_fragments.push_back(frag);
  1197. }
  1198. }
  1199. mapped_fragments = std::move(new_mapped_fragments);
  1200. }
  1201. ~llama_mmap() {
  1202. for (const auto & frag : mapped_fragments) {
  1203. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1204. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1205. }
  1206. }
  1207. }
  1208. #elif defined(_WIN32)
  1209. static constexpr bool SUPPORTED = true;
  1210. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1211. GGML_UNUSED(numa);
  1212. size = file->size;
  1213. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1214. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1215. if (hMapping == NULL) {
  1216. DWORD error = GetLastError();
  1217. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1218. }
  1219. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1220. DWORD error = GetLastError();
  1221. CloseHandle(hMapping);
  1222. if (addr == NULL) {
  1223. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1224. }
  1225. if (prefetch > 0) {
  1226. #if _WIN32_WINNT >= 0x602
  1227. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1228. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1229. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1230. // may fail on pre-Windows 8 systems
  1231. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1232. if (pPrefetchVirtualMemory) {
  1233. // advise the kernel to preload the mapped memory
  1234. WIN32_MEMORY_RANGE_ENTRY range;
  1235. range.VirtualAddress = addr;
  1236. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1237. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1238. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1239. llama_format_win_err(GetLastError()).c_str());
  1240. }
  1241. }
  1242. #else
  1243. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1244. #endif
  1245. }
  1246. }
  1247. void unmap_fragment(size_t first, size_t last) {
  1248. // not supported
  1249. GGML_UNUSED(first);
  1250. GGML_UNUSED(last);
  1251. }
  1252. ~llama_mmap() {
  1253. if (!UnmapViewOfFile(addr)) {
  1254. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1255. llama_format_win_err(GetLastError()).c_str());
  1256. }
  1257. }
  1258. #else
  1259. static constexpr bool SUPPORTED = false;
  1260. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1261. GGML_UNUSED(file);
  1262. GGML_UNUSED(prefetch);
  1263. GGML_UNUSED(numa);
  1264. throw std::runtime_error("mmap not supported");
  1265. }
  1266. void unmap_fragment(size_t first, size_t last) {
  1267. GGML_UNUSED(first);
  1268. GGML_UNUSED(last);
  1269. throw std::runtime_error("mmap not supported");
  1270. }
  1271. #endif
  1272. };
  1273. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1274. // Represents some region of memory being locked using mlock or VirtualLock;
  1275. // will automatically unlock on destruction.
  1276. struct llama_mlock {
  1277. void * addr = NULL;
  1278. size_t size = 0;
  1279. bool failed_already = false;
  1280. llama_mlock() {}
  1281. llama_mlock(const llama_mlock &) = delete;
  1282. ~llama_mlock() {
  1283. if (size) {
  1284. raw_unlock(addr, size);
  1285. }
  1286. }
  1287. void init(void * ptr) {
  1288. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1289. addr = ptr;
  1290. }
  1291. void grow_to(size_t target_size) {
  1292. GGML_ASSERT(addr);
  1293. if (failed_already) {
  1294. return;
  1295. }
  1296. size_t granularity = lock_granularity();
  1297. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1298. if (target_size > size) {
  1299. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1300. size = target_size;
  1301. } else {
  1302. failed_already = true;
  1303. }
  1304. }
  1305. }
  1306. #ifdef _POSIX_MEMLOCK_RANGE
  1307. static constexpr bool SUPPORTED = true;
  1308. static size_t lock_granularity() {
  1309. return (size_t) sysconf(_SC_PAGESIZE);
  1310. }
  1311. #ifdef __APPLE__
  1312. #define MLOCK_SUGGESTION \
  1313. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1314. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1315. #else
  1316. #define MLOCK_SUGGESTION \
  1317. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1318. #endif
  1319. bool raw_lock(const void * addr, size_t size) const {
  1320. if (!mlock(addr, size)) {
  1321. return true;
  1322. }
  1323. char* errmsg = std::strerror(errno);
  1324. bool suggest = (errno == ENOMEM);
  1325. // Check if the resource limit is fine after all
  1326. struct rlimit lock_limit;
  1327. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1328. suggest = false;
  1329. }
  1330. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1331. suggest = false;
  1332. }
  1333. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1334. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1335. return false;
  1336. }
  1337. #undef MLOCK_SUGGESTION
  1338. static void raw_unlock(void * addr, size_t size) {
  1339. if (munlock(addr, size)) {
  1340. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1341. }
  1342. }
  1343. #elif defined(_WIN32)
  1344. static constexpr bool SUPPORTED = true;
  1345. static size_t lock_granularity() {
  1346. SYSTEM_INFO si;
  1347. GetSystemInfo(&si);
  1348. return (size_t) si.dwPageSize;
  1349. }
  1350. bool raw_lock(void * ptr, size_t len) const {
  1351. for (int tries = 1; ; tries++) {
  1352. if (VirtualLock(ptr, len)) {
  1353. return true;
  1354. }
  1355. if (tries == 2) {
  1356. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1357. len, size, llama_format_win_err(GetLastError()).c_str());
  1358. return false;
  1359. }
  1360. // It failed but this was only the first try; increase the working
  1361. // set size and try again.
  1362. SIZE_T min_ws_size, max_ws_size;
  1363. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1364. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1365. llama_format_win_err(GetLastError()).c_str());
  1366. return false;
  1367. }
  1368. // Per MSDN: "The maximum number of pages that a process can lock
  1369. // is equal to the number of pages in its minimum working set minus
  1370. // a small overhead."
  1371. // Hopefully a megabyte is enough overhead:
  1372. size_t increment = len + 1048576;
  1373. // The minimum must be <= the maximum, so we need to increase both:
  1374. min_ws_size += increment;
  1375. max_ws_size += increment;
  1376. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1377. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1378. llama_format_win_err(GetLastError()).c_str());
  1379. return false;
  1380. }
  1381. }
  1382. }
  1383. static void raw_unlock(void * ptr, size_t len) {
  1384. if (!VirtualUnlock(ptr, len)) {
  1385. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1386. llama_format_win_err(GetLastError()).c_str());
  1387. }
  1388. }
  1389. #else
  1390. static constexpr bool SUPPORTED = false;
  1391. static size_t lock_granularity() {
  1392. return (size_t) 65536;
  1393. }
  1394. bool raw_lock(const void * addr, size_t len) const {
  1395. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1396. return false;
  1397. }
  1398. static void raw_unlock(const void * addr, size_t len) {}
  1399. #endif
  1400. };
  1401. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1402. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1403. std::vector<char> result(8, 0);
  1404. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1405. if (n_tokens < 0) {
  1406. result.resize(-n_tokens);
  1407. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1408. GGML_ASSERT(check == -n_tokens);
  1409. }
  1410. else {
  1411. result.resize(n_tokens);
  1412. }
  1413. return std::string(result.data(), result.size());
  1414. }
  1415. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1416. ggml_backend_buffer_type_t buft = nullptr;
  1417. #if defined(GGML_USE_CUDA)
  1418. // host buffers should only be used when data is expected to be copied to/from the GPU
  1419. if (host_buffer) {
  1420. buft = ggml_backend_cuda_host_buffer_type();
  1421. }
  1422. #elif defined(GGML_USE_SYCL)
  1423. if (host_buffer) {
  1424. buft = ggml_backend_sycl_host_buffer_type();
  1425. }
  1426. #elif defined(GGML_USE_CPU_HBM)
  1427. buft = ggml_backend_cpu_hbm_buffer_type();
  1428. #elif defined(GGML_USE_VULKAN)
  1429. if (host_buffer) {
  1430. buft = ggml_backend_vk_host_buffer_type();
  1431. }
  1432. #endif
  1433. if (buft == nullptr) {
  1434. buft = ggml_backend_cpu_buffer_type();
  1435. }
  1436. return buft;
  1437. GGML_UNUSED(host_buffer);
  1438. }
  1439. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1440. ggml_backend_buffer_type_t buft = nullptr;
  1441. #ifdef GGML_USE_METAL
  1442. buft = ggml_backend_metal_buffer_type();
  1443. #elif defined(GGML_USE_CUDA)
  1444. buft = ggml_backend_cuda_buffer_type(gpu);
  1445. #elif defined(GGML_USE_VULKAN)
  1446. buft = ggml_backend_vk_buffer_type(gpu);
  1447. #elif defined(GGML_USE_SYCL)
  1448. buft = ggml_backend_sycl_buffer_type(gpu);
  1449. #elif defined(GGML_USE_CLBLAST)
  1450. buft = ggml_backend_opencl_buffer_type();
  1451. #elif defined(GGML_USE_KOMPUTE)
  1452. buft = ggml_backend_kompute_buffer_type(gpu);
  1453. if (buft == nullptr) {
  1454. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1455. }
  1456. #endif
  1457. if (buft == nullptr) {
  1458. buft = llama_default_buffer_type_cpu(true);
  1459. }
  1460. return buft;
  1461. GGML_UNUSED(gpu);
  1462. }
  1463. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1464. ggml_backend_buffer_type_t buft = nullptr;
  1465. #ifdef GGML_USE_CUDA
  1466. if (ggml_backend_cuda_get_device_count() > 1) {
  1467. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1468. }
  1469. #endif
  1470. #ifdef GGML_USE_SYCL
  1471. if (ggml_backend_sycl_get_device_count() > 1) {
  1472. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1473. }
  1474. #endif
  1475. if (buft == nullptr) {
  1476. buft = llama_default_buffer_type_offload(fallback_gpu);
  1477. }
  1478. return buft;
  1479. GGML_UNUSED(tensor_split);
  1480. }
  1481. static size_t llama_get_device_count() {
  1482. #if defined(GGML_USE_CUDA)
  1483. return ggml_backend_cuda_get_device_count();
  1484. #elif defined(GGML_USE_SYCL)
  1485. return ggml_backend_sycl_get_device_count();
  1486. #elif defined(GGML_USE_VULKAN)
  1487. return ggml_backend_vk_get_device_count();
  1488. #else
  1489. return 1;
  1490. #endif
  1491. }
  1492. static size_t llama_get_device_memory(int device) {
  1493. #if defined(GGML_USE_CUDA)
  1494. size_t total;
  1495. size_t free;
  1496. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1497. return free;
  1498. #elif defined(GGML_USE_SYCL)
  1499. size_t total;
  1500. size_t free;
  1501. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1502. return free;
  1503. #elif defined(GGML_USE_VULKAN)
  1504. size_t total;
  1505. size_t free;
  1506. ggml_backend_vk_get_device_memory(device, &total, &free);
  1507. return free;
  1508. #else
  1509. return 1;
  1510. GGML_UNUSED(device);
  1511. #endif
  1512. }
  1513. //
  1514. // globals
  1515. //
  1516. struct llama_state {
  1517. llama_state() {
  1518. #ifdef GGML_USE_METAL
  1519. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1520. #endif
  1521. }
  1522. // We save the log callback globally
  1523. ggml_log_callback log_callback = llama_log_callback_default;
  1524. void * log_callback_user_data = nullptr;
  1525. };
  1526. static llama_state g_state;
  1527. // available llama models
  1528. enum e_model {
  1529. MODEL_UNKNOWN,
  1530. MODEL_17M,
  1531. MODEL_22M,
  1532. MODEL_33M,
  1533. MODEL_109M,
  1534. MODEL_137M,
  1535. MODEL_335M,
  1536. MODEL_0_5B,
  1537. MODEL_1B,
  1538. MODEL_2B,
  1539. MODEL_3B,
  1540. MODEL_4B,
  1541. MODEL_7B,
  1542. MODEL_8B,
  1543. MODEL_13B,
  1544. MODEL_14B,
  1545. MODEL_15B,
  1546. MODEL_20B,
  1547. MODEL_30B,
  1548. MODEL_34B,
  1549. MODEL_35B,
  1550. MODEL_40B,
  1551. MODEL_65B,
  1552. MODEL_70B,
  1553. MODEL_314B,
  1554. MODEL_SMALL,
  1555. MODEL_MEDIUM,
  1556. MODEL_LARGE,
  1557. MODEL_XL,
  1558. MODEL_8x7B,
  1559. MODEL_8x22B,
  1560. };
  1561. static const size_t kiB = 1024;
  1562. static const size_t MiB = 1024*kiB;
  1563. static const size_t GiB = 1024*MiB;
  1564. struct llama_hparams {
  1565. bool vocab_only;
  1566. bool rope_finetuned;
  1567. uint32_t n_vocab;
  1568. uint32_t n_ctx_train; // context size the model was trained on
  1569. uint32_t n_embd;
  1570. uint32_t n_head;
  1571. uint32_t n_head_kv;
  1572. uint32_t n_layer;
  1573. uint32_t n_rot;
  1574. 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
  1575. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1576. uint32_t n_ff;
  1577. uint32_t n_expert = 0;
  1578. uint32_t n_expert_used = 0;
  1579. uint32_t n_vocab_type = 0; // for BERT-style token types
  1580. float f_norm_eps;
  1581. float f_norm_rms_eps;
  1582. float rope_freq_base_train;
  1583. float rope_freq_scale_train;
  1584. uint32_t n_yarn_orig_ctx;
  1585. // for State Space Models
  1586. uint32_t ssm_d_conv = 0;
  1587. uint32_t ssm_d_inner = 0;
  1588. uint32_t ssm_d_state = 0;
  1589. uint32_t ssm_dt_rank = 0;
  1590. float f_clamp_kqv = 0.0f;
  1591. float f_max_alibi_bias = 0.0f;
  1592. float f_logit_scale = 0.0f;
  1593. bool causal_attn = true;
  1594. bool need_kq_pos = false;
  1595. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1596. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1597. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1598. bool operator!=(const llama_hparams & other) const {
  1599. if (this->vocab_only != other.vocab_only) return true;
  1600. if (this->n_vocab != other.n_vocab) return true;
  1601. if (this->n_ctx_train != other.n_ctx_train) return true;
  1602. if (this->n_embd != other.n_embd) return true;
  1603. if (this->n_head != other.n_head) return true;
  1604. if (this->n_head_kv != other.n_head_kv) return true;
  1605. if (this->n_layer != other.n_layer) return true;
  1606. if (this->n_rot != other.n_rot) return true;
  1607. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1608. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1609. if (this->n_ff != other.n_ff) return true;
  1610. if (this->n_expert != other.n_expert) return true;
  1611. if (this->n_expert_used != other.n_expert_used) return true;
  1612. if (this->rope_finetuned != other.rope_finetuned) return true;
  1613. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1614. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1615. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1616. if (this->ssm_d_state != other.ssm_d_state) return true;
  1617. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1618. const float EPSILON = 1e-9f;
  1619. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1620. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1621. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1622. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1623. return false;
  1624. }
  1625. uint32_t n_gqa() const {
  1626. if (n_head_kv == 0) {
  1627. return 0;
  1628. }
  1629. return n_head/n_head_kv;
  1630. }
  1631. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1632. return n_embd_head_k * n_head_kv;
  1633. }
  1634. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1635. return n_embd_head_v * n_head_kv;
  1636. }
  1637. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1638. // corresponds to Mamba's conv_states size
  1639. // TODO: maybe support other convolution strides than 1
  1640. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1641. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1642. }
  1643. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1644. // corresponds to Mamba's ssm_states size
  1645. return ssm_d_state * ssm_d_inner;
  1646. }
  1647. };
  1648. struct llama_cparams {
  1649. uint32_t n_ctx; // context size used during inference
  1650. uint32_t n_batch;
  1651. uint32_t n_ubatch;
  1652. uint32_t n_seq_max;
  1653. uint32_t n_threads; // number of threads to use for generation
  1654. uint32_t n_threads_batch; // number of threads to use for batch processing
  1655. float rope_freq_base;
  1656. float rope_freq_scale;
  1657. uint32_t n_yarn_orig_ctx;
  1658. // These hyperparameters are not exposed in GGUF, because all
  1659. // existing YaRN models use the same values for them.
  1660. float yarn_ext_factor;
  1661. float yarn_attn_factor;
  1662. float yarn_beta_fast;
  1663. float yarn_beta_slow;
  1664. float defrag_thold;
  1665. bool embeddings;
  1666. bool causal_attn;
  1667. bool offload_kqv;
  1668. enum llama_pooling_type pooling_type;
  1669. ggml_backend_sched_eval_callback cb_eval;
  1670. void * cb_eval_user_data;
  1671. };
  1672. struct llama_layer {
  1673. // normalization
  1674. struct ggml_tensor * attn_norm;
  1675. struct ggml_tensor * attn_norm_b;
  1676. struct ggml_tensor * attn_norm_2;
  1677. struct ggml_tensor * attn_norm_2_b;
  1678. struct ggml_tensor * attn_q_norm;
  1679. struct ggml_tensor * attn_q_norm_b;
  1680. struct ggml_tensor * attn_k_norm;
  1681. struct ggml_tensor * attn_k_norm_b;
  1682. struct ggml_tensor * attn_out_norm;
  1683. struct ggml_tensor * attn_out_norm_b;
  1684. // attention
  1685. struct ggml_tensor * wq;
  1686. struct ggml_tensor * wk;
  1687. struct ggml_tensor * wv;
  1688. struct ggml_tensor * wo;
  1689. struct ggml_tensor * wqkv;
  1690. // attention bias
  1691. struct ggml_tensor * bq;
  1692. struct ggml_tensor * bk;
  1693. struct ggml_tensor * bv;
  1694. struct ggml_tensor * bo;
  1695. struct ggml_tensor * bqkv;
  1696. // normalization
  1697. struct ggml_tensor * ffn_norm;
  1698. struct ggml_tensor * ffn_norm_b;
  1699. struct ggml_tensor * layer_out_norm;
  1700. struct ggml_tensor * layer_out_norm_b;
  1701. // ff
  1702. struct ggml_tensor * ffn_gate; // w1
  1703. struct ggml_tensor * ffn_down; // w2
  1704. struct ggml_tensor * ffn_up; // w3
  1705. // ff MoE
  1706. struct ggml_tensor * ffn_gate_inp;
  1707. struct ggml_tensor * ffn_gate_exps;
  1708. struct ggml_tensor * ffn_down_exps;
  1709. struct ggml_tensor * ffn_up_exps ;
  1710. // ff bias
  1711. struct ggml_tensor * ffn_down_b; // b2
  1712. struct ggml_tensor * ffn_up_b; // b3
  1713. struct ggml_tensor * ffn_act;
  1714. // mamba proj
  1715. struct ggml_tensor * ssm_in;
  1716. struct ggml_tensor * ssm_x;
  1717. struct ggml_tensor * ssm_dt;
  1718. struct ggml_tensor * ssm_out;
  1719. // mamba
  1720. struct ggml_tensor * ssm_conv1d;
  1721. struct ggml_tensor * ssm_a;
  1722. struct ggml_tensor * ssm_d;
  1723. // mamba bias
  1724. struct ggml_tensor * ssm_conv1d_b;
  1725. struct ggml_tensor * ssm_dt_b;
  1726. };
  1727. struct llama_kv_cell {
  1728. llama_pos pos = -1;
  1729. llama_pos delta = 0;
  1730. int32_t src = 0; // used by recurrent state models to copy states
  1731. std::set<llama_seq_id> seq_id;
  1732. bool has_seq_id(const llama_seq_id & id) const {
  1733. return seq_id.find(id) != seq_id.end();
  1734. }
  1735. bool is_empty() const {
  1736. return seq_id.empty();
  1737. }
  1738. bool is_same_seq(const llama_kv_cell & other) const {
  1739. return seq_id == other.seq_id;
  1740. }
  1741. };
  1742. // ring-buffer of cached KV data
  1743. struct llama_kv_cache {
  1744. bool has_shift = false;
  1745. bool do_defrag = false;
  1746. bool do_copy = false;
  1747. // with recurrent state models, a cell can hold the state for more than one past token
  1748. bool recurrent = false;
  1749. // Note: The value of head isn't only used to optimize searching
  1750. // for a free KV slot. llama_decode_internal also uses it, so it
  1751. // cannot be freely changed after a slot has been allocated.
  1752. uint32_t head = 0;
  1753. uint32_t size = 0;
  1754. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1755. // computed before each graph build
  1756. uint32_t n = 0;
  1757. ggml_type type_k = GGML_TYPE_F16;
  1758. ggml_type type_v = GGML_TYPE_F16;
  1759. std::vector<llama_kv_cell> cells;
  1760. std::vector<struct ggml_tensor *> k_l; // per layer
  1761. std::vector<struct ggml_tensor *> v_l;
  1762. std::vector<struct ggml_context *> ctxs;
  1763. std::vector<ggml_backend_buffer_t> bufs;
  1764. size_t total_size() const {
  1765. size_t size = 0;
  1766. for (ggml_backend_buffer_t buf : bufs) {
  1767. size += ggml_backend_buffer_get_size(buf);
  1768. }
  1769. return size;
  1770. }
  1771. ~llama_kv_cache() {
  1772. for (struct ggml_context * ctx : ctxs) {
  1773. ggml_free(ctx);
  1774. }
  1775. for (ggml_backend_buffer_t buf : bufs) {
  1776. ggml_backend_buffer_free(buf);
  1777. }
  1778. }
  1779. };
  1780. struct llama_control_vector {
  1781. std::vector<struct ggml_tensor *> tensors; // per layer
  1782. std::vector<struct ggml_context *> ctxs;
  1783. std::vector<ggml_backend_buffer_t> bufs;
  1784. int32_t layer_start = -1;
  1785. int32_t layer_end = -1;
  1786. ggml_tensor * tensor_for(int il) const {
  1787. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1788. return nullptr;
  1789. }
  1790. return tensors[il];
  1791. }
  1792. ~llama_control_vector() {
  1793. for (struct ggml_context * ctx : ctxs) {
  1794. ggml_free(ctx);
  1795. }
  1796. for (ggml_backend_buffer_t buf : bufs) {
  1797. ggml_backend_buffer_free(buf);
  1798. }
  1799. }
  1800. };
  1801. struct llama_vocab {
  1802. using id = int32_t;
  1803. using token = std::string;
  1804. using ttype = llama_token_type;
  1805. struct token_data {
  1806. token text;
  1807. float score;
  1808. ttype type;
  1809. };
  1810. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1811. std::unordered_map<token, id> token_to_id;
  1812. std::vector<token_data> id_to_token;
  1813. std::unordered_map<token, id> special_tokens_cache;
  1814. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1815. // default LLaMA special tokens
  1816. id special_bos_id = 1;
  1817. id special_eos_id = 2;
  1818. id special_unk_id = 0;
  1819. id special_sep_id = -1;
  1820. id special_pad_id = -1;
  1821. id special_cls_id = -1;
  1822. id special_mask_id = -1;
  1823. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1824. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1825. id linefeed_id = 13;
  1826. id special_prefix_id = 32007;
  1827. id special_middle_id = 32009;
  1828. id special_suffix_id = 32008;
  1829. id special_eot_id = 32010;
  1830. bool add_space_prefix = true;
  1831. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1832. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1833. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1834. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1835. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1836. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1837. if (it == bpe_ranks.end()) {
  1838. return -1;
  1839. }
  1840. return it->second;
  1841. }
  1842. };
  1843. struct llama_model {
  1844. e_model type = MODEL_UNKNOWN;
  1845. llm_arch arch = LLM_ARCH_UNKNOWN;
  1846. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1847. std::string name = "n/a";
  1848. llama_hparams hparams = {};
  1849. llama_vocab vocab;
  1850. struct ggml_tensor * tok_embd;
  1851. struct ggml_tensor * type_embd;
  1852. struct ggml_tensor * pos_embd;
  1853. struct ggml_tensor * tok_norm;
  1854. struct ggml_tensor * tok_norm_b;
  1855. struct ggml_tensor * output_norm;
  1856. struct ggml_tensor * output_norm_b;
  1857. struct ggml_tensor * output;
  1858. struct ggml_tensor * output_b;
  1859. std::vector<llama_layer> layers;
  1860. llama_split_mode split_mode;
  1861. int main_gpu;
  1862. int n_gpu_layers;
  1863. // gguf metadata
  1864. std::unordered_map<std::string, std::string> gguf_kv;
  1865. // layer -> buffer type mapping
  1866. struct layer_buft {
  1867. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1868. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1869. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1870. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1871. ggml_backend_buffer_type_t buft; // everything else
  1872. };
  1873. layer_buft buft_input;
  1874. layer_buft buft_output;
  1875. std::vector<layer_buft> buft_layer;
  1876. // contexts where the model tensors metadata is stored
  1877. std::vector<struct ggml_context *> ctxs;
  1878. // the model memory buffers for the tensor data
  1879. std::vector<ggml_backend_buffer_t> bufs;
  1880. // model memory mapped files
  1881. llama_mmaps mappings;
  1882. // objects representing data potentially being locked in memory
  1883. llama_mlocks mlock_bufs;
  1884. llama_mlocks mlock_mmaps;
  1885. // for quantize-stats only
  1886. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1887. int64_t t_load_us = 0;
  1888. int64_t t_start_us = 0;
  1889. ~llama_model() {
  1890. for (struct ggml_context * ctx : ctxs) {
  1891. ggml_free(ctx);
  1892. }
  1893. for (ggml_backend_buffer_t buf : bufs) {
  1894. #ifdef GGML_USE_CUDA
  1895. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1896. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1897. }
  1898. #endif
  1899. ggml_backend_buffer_free(buf);
  1900. }
  1901. }
  1902. };
  1903. struct llama_context {
  1904. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1905. ~llama_context() {
  1906. ggml_backend_sched_free(sched);
  1907. for (ggml_backend_t backend : backends) {
  1908. ggml_backend_free(backend);
  1909. }
  1910. ggml_backend_buffer_free(buf_output);
  1911. }
  1912. llama_cparams cparams;
  1913. std::vector<ggml_backend_t> backends;
  1914. #ifdef GGML_USE_METAL
  1915. ggml_backend_t backend_metal = nullptr;
  1916. #endif
  1917. ggml_backend_t backend_cpu = nullptr;
  1918. const llama_model & model;
  1919. // key + value cache for the self attention
  1920. struct llama_kv_cache kv_self;
  1921. std::mt19937 rng;
  1922. bool has_evaluated_once = false;
  1923. int64_t t_start_us;
  1924. int64_t t_load_us;
  1925. int64_t t_sample_us = 0;
  1926. int64_t t_p_eval_us = 0;
  1927. int64_t t_eval_us = 0;
  1928. int64_t t_compute_start_us = 0;
  1929. int64_t n_queued_tokens = 0;
  1930. int32_t n_sample = 0; // number of tokens sampled
  1931. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1932. int32_t n_eval = 0; // number of eval calls
  1933. // host buffer for the model output (logits and embeddings)
  1934. ggml_backend_buffer_t buf_output = nullptr;
  1935. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1936. size_t logits_size = 0; // capacity (of floats) for logits
  1937. float * logits = nullptr;
  1938. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1939. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1940. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  1941. bool logits_all = false;
  1942. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1943. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1944. size_t embd_size = 0; // capacity (of floats) for embeddings
  1945. float * embd = nullptr;
  1946. // sequence embeddings output (map of [n_embd] vectors)
  1947. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1948. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1949. // memory buffers used to evaluate the model
  1950. std::vector<uint8_t> buf_compute_meta;
  1951. ggml_backend_sched_t sched = nullptr;
  1952. ggml_abort_callback abort_callback = nullptr;
  1953. void * abort_callback_data = nullptr;
  1954. // input tensors
  1955. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1956. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1957. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1958. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1959. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1960. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1961. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1962. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1963. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1964. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1965. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1966. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1967. // control vectors
  1968. struct llama_control_vector cvec;
  1969. #ifdef GGML_USE_MPI
  1970. ggml_mpi_context * ctx_mpi = NULL;
  1971. #endif
  1972. };
  1973. //
  1974. // kv cache helpers
  1975. //
  1976. static bool llama_kv_cache_init(
  1977. struct llama_kv_cache & cache,
  1978. const llama_model & model,
  1979. ggml_type type_k,
  1980. ggml_type type_v,
  1981. uint32_t kv_size,
  1982. bool offload) {
  1983. const struct llama_hparams & hparams = model.hparams;
  1984. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1985. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1986. const int64_t n_layer = hparams.n_layer;
  1987. cache.has_shift = false;
  1988. // TODO: find a nicer way to add other recurrent model architectures
  1989. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1990. // TODO: support mixed reccurent Transformer architectues
  1991. // NOTE: (!a || b) is a logical implication (a -> b)
  1992. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1993. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1994. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1995. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1996. cache.head = 0;
  1997. cache.size = kv_size;
  1998. cache.used = 0;
  1999. cache.type_k = type_k;
  2000. cache.type_v = type_v;
  2001. cache.cells.clear();
  2002. cache.cells.resize(kv_size);
  2003. if (cache.recurrent) {
  2004. // init state copy sources
  2005. for (uint32_t i = 0; i < cache.size; ++i) {
  2006. cache.cells[i].src = i;
  2007. }
  2008. }
  2009. #ifdef GGML_USE_CLBLAST
  2010. offload = false;
  2011. #endif
  2012. // count used buffer types
  2013. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2014. if (offload) {
  2015. for (int64_t i = 0; i < n_layer; ++i) {
  2016. buft_layer_count[model.buft_layer[i].buft]++;
  2017. }
  2018. } else {
  2019. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2020. }
  2021. // create a context for each buffer type
  2022. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2023. for (auto & it : buft_layer_count) {
  2024. int n_layers = it.second;
  2025. struct ggml_init_params params = {
  2026. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2027. /*.mem_buffer =*/ NULL,
  2028. /*.no_alloc =*/ true,
  2029. };
  2030. ggml_context * ctx = ggml_init(params);
  2031. if (!ctx) {
  2032. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2033. return false;
  2034. }
  2035. ctx_map[it.first] = ctx;
  2036. cache.ctxs.push_back(ctx);
  2037. }
  2038. cache.k_l.reserve(n_layer);
  2039. cache.v_l.reserve(n_layer);
  2040. for (int i = 0; i < (int) n_layer; i++) {
  2041. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2042. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2043. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2044. ggml_format_name(k, "cache_k_l%d", i);
  2045. ggml_format_name(v, "cache_v_l%d", i);
  2046. cache.k_l.push_back(k);
  2047. cache.v_l.push_back(v);
  2048. }
  2049. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2050. for (auto it : ctx_map) {
  2051. ggml_backend_buffer_type_t buft = it.first;
  2052. ggml_context * ctx = it.second;
  2053. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2054. if (!buf) {
  2055. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2056. return false;
  2057. }
  2058. ggml_backend_buffer_clear(buf, 0);
  2059. 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);
  2060. cache.bufs.push_back(buf);
  2061. }
  2062. return true;
  2063. }
  2064. // find an empty slot of size "n_tokens" in the cache
  2065. // updates the cache head
  2066. // Note: On success, it's important that cache.head points
  2067. // to the first cell of the slot.
  2068. static bool llama_kv_cache_find_slot(
  2069. struct llama_kv_cache & cache,
  2070. const struct llama_batch & batch) {
  2071. const uint32_t n_ctx = cache.size;
  2072. const uint32_t n_tokens = batch.n_tokens;
  2073. if (cache.recurrent) {
  2074. // For recurrent state architectures (like Mamba),
  2075. // each KV cache cell can store the state for a whole sequence.
  2076. llama_seq_id min = cache.size - 1;
  2077. llama_seq_id max = 0;
  2078. for (uint32_t i = 0; i < n_tokens; ++i) {
  2079. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2080. llama_seq_id seq_id = batch.seq_id[i][j];
  2081. // make sure it's a valid seq_id
  2082. if ((uint32_t) seq_id < cache.size) {
  2083. if (seq_id > max) {
  2084. max = seq_id;
  2085. }
  2086. if (seq_id < min) {
  2087. min = seq_id;
  2088. }
  2089. // Assuming the tokens are in-order
  2090. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2091. // What should happen when the pos backtracks or skips a value?
  2092. // Clearing the state mid-batch would require special-casing which isn't done.
  2093. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2094. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2095. }
  2096. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2097. cache.used += 1;
  2098. }
  2099. cache.cells[seq_id].pos = batch.pos[i];
  2100. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2101. } else {
  2102. // too big seq_id
  2103. // TODO: would it be possible to resize the KV cache size instead?
  2104. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2105. return false;
  2106. }
  2107. }
  2108. }
  2109. // allow getting the range of used cells, from head to head + n
  2110. cache.head = min;
  2111. cache.n = max - min + 1;
  2112. // sanity check
  2113. return max >= min;
  2114. }
  2115. // otherwise, one cell per token.
  2116. if (n_tokens > n_ctx) {
  2117. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2118. return false;
  2119. }
  2120. uint32_t n_tested = 0;
  2121. while (true) {
  2122. if (cache.head + n_tokens > n_ctx) {
  2123. n_tested += n_ctx - cache.head;
  2124. cache.head = 0;
  2125. continue;
  2126. }
  2127. bool found = true;
  2128. for (uint32_t i = 0; i < n_tokens; i++) {
  2129. if (cache.cells[cache.head + i].pos >= 0) {
  2130. found = false;
  2131. cache.head += i + 1;
  2132. n_tested += i + 1;
  2133. break;
  2134. }
  2135. }
  2136. if (found) {
  2137. break;
  2138. }
  2139. if (n_tested >= n_ctx) {
  2140. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2141. return false;
  2142. }
  2143. }
  2144. for (uint32_t i = 0; i < n_tokens; i++) {
  2145. cache.cells[cache.head + i].pos = batch.pos[i];
  2146. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2147. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2148. }
  2149. }
  2150. cache.used += n_tokens;
  2151. return true;
  2152. }
  2153. // find how many cells are currently in use
  2154. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2155. for (uint32_t i = cache.size; i > 0; --i) {
  2156. const llama_kv_cell & cell = cache.cells[i - 1];
  2157. if (cell.pos >= 0 && !cell.is_empty()) {
  2158. return i;
  2159. }
  2160. }
  2161. return 0;
  2162. }
  2163. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2164. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2165. cache.cells[i].pos = -1;
  2166. cache.cells[i].seq_id.clear();
  2167. }
  2168. cache.head = 0;
  2169. cache.used = 0;
  2170. }
  2171. static bool llama_kv_cache_seq_rm(
  2172. struct llama_kv_cache & cache,
  2173. llama_seq_id seq_id,
  2174. llama_pos p0,
  2175. llama_pos p1) {
  2176. uint32_t new_head = cache.size;
  2177. if (p0 < 0) p0 = 0;
  2178. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2179. // models like Mamba can't have a state partially erased
  2180. if (cache.recurrent) {
  2181. if (seq_id >= (int64_t) cache.size) {
  2182. // could be fatal
  2183. return false;
  2184. }
  2185. if (0 <= seq_id) {
  2186. // partial intersection is invalid
  2187. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2188. return false;
  2189. }
  2190. } else {
  2191. // seq_id is negative, then the range should include everything or nothing
  2192. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2193. return false;
  2194. }
  2195. }
  2196. }
  2197. for (uint32_t i = 0; i < cache.size; ++i) {
  2198. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2199. if (seq_id < 0) {
  2200. cache.cells[i].seq_id.clear();
  2201. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2202. cache.cells[i].seq_id.erase(seq_id);
  2203. } else {
  2204. continue;
  2205. }
  2206. if (cache.cells[i].is_empty()) {
  2207. // keep count of the number of used cells
  2208. if (cache.cells[i].pos >= 0) cache.used--;
  2209. cache.cells[i].pos = -1;
  2210. if (new_head == cache.size) new_head = i;
  2211. }
  2212. }
  2213. }
  2214. // If we freed up a slot, set head to it so searching can start there.
  2215. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2216. return true;
  2217. }
  2218. static void llama_kv_cache_seq_cp(
  2219. struct llama_kv_cache & cache,
  2220. llama_seq_id seq_id_src,
  2221. llama_seq_id seq_id_dst,
  2222. llama_pos p0,
  2223. llama_pos p1) {
  2224. if (p0 < 0) p0 = 0;
  2225. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2226. if (cache.recurrent) {
  2227. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2228. seq_id_src = cache.cells[seq_id_src].src;
  2229. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2230. // intent to "copy from"
  2231. // supports copy chains thanks to taking the source of the source
  2232. cache.cells[seq_id_dst].src = seq_id_src;
  2233. // preserve the "keep or clear" status of the copied sequence
  2234. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2235. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2236. } else {
  2237. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2238. }
  2239. cache.do_copy = true;
  2240. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2241. }
  2242. return;
  2243. }
  2244. // otherwise, this is the KV cache of a Transformer-like model
  2245. cache.head = 0;
  2246. for (uint32_t i = 0; i < cache.size; ++i) {
  2247. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2248. cache.cells[i].seq_id.insert(seq_id_dst);
  2249. }
  2250. }
  2251. }
  2252. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2253. uint32_t new_head = cache.size;
  2254. for (uint32_t i = 0; i < cache.size; ++i) {
  2255. if (!cache.cells[i].has_seq_id(seq_id)) {
  2256. if (cache.cells[i].pos >= 0) cache.used--;
  2257. cache.cells[i].pos = -1;
  2258. cache.cells[i].seq_id.clear();
  2259. if (new_head == cache.size) new_head = i;
  2260. } else {
  2261. cache.cells[i].seq_id.clear();
  2262. cache.cells[i].seq_id.insert(seq_id);
  2263. }
  2264. }
  2265. // If we freed up a slot, set head to it so searching can start there.
  2266. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2267. }
  2268. static void llama_kv_cache_seq_add(
  2269. struct llama_kv_cache & cache,
  2270. llama_seq_id seq_id,
  2271. llama_pos p0,
  2272. llama_pos p1,
  2273. llama_pos delta) {
  2274. uint32_t new_head = cache.size;
  2275. if (p0 < 0) p0 = 0;
  2276. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2277. if (cache.recurrent) {
  2278. // for Mamba-like models, only the pos needs to be shifted
  2279. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2280. llama_kv_cell & cell = cache.cells[seq_id];
  2281. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2282. cell.pos += delta;
  2283. }
  2284. }
  2285. return;
  2286. }
  2287. for (uint32_t i = 0; i < cache.size; ++i) {
  2288. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2289. cache.has_shift = true;
  2290. cache.cells[i].pos += delta;
  2291. cache.cells[i].delta += delta;
  2292. if (cache.cells[i].pos < 0) {
  2293. if (!cache.cells[i].is_empty()) {
  2294. cache.used--;
  2295. }
  2296. cache.cells[i].pos = -1;
  2297. cache.cells[i].seq_id.clear();
  2298. if (new_head == cache.size) {
  2299. new_head = i;
  2300. }
  2301. }
  2302. }
  2303. }
  2304. // If we freed up a slot, set head to it so searching can start there.
  2305. // Otherwise we just start the next search from the beginning.
  2306. cache.head = new_head != cache.size ? new_head : 0;
  2307. }
  2308. static void llama_kv_cache_seq_div(
  2309. struct llama_kv_cache & cache,
  2310. llama_seq_id seq_id,
  2311. llama_pos p0,
  2312. llama_pos p1,
  2313. int d) {
  2314. if (p0 < 0) p0 = 0;
  2315. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2316. if (cache.recurrent) {
  2317. // for Mamba-like models, only the pos needs to be changed
  2318. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2319. llama_kv_cell & cell = cache.cells[seq_id];
  2320. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2321. cell.pos /= d;
  2322. }
  2323. }
  2324. return;
  2325. }
  2326. for (uint32_t i = 0; i < cache.size; ++i) {
  2327. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2328. cache.has_shift = true;
  2329. {
  2330. llama_pos p_old = cache.cells[i].pos;
  2331. cache.cells[i].pos /= d;
  2332. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2333. }
  2334. }
  2335. }
  2336. }
  2337. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2338. llama_pos result = 0;
  2339. for (uint32_t i = 0; i < cache.size; ++i) {
  2340. if (cache.cells[i].has_seq_id(seq_id)) {
  2341. result = std::max(result, cache.cells[i].pos);
  2342. }
  2343. }
  2344. return result;
  2345. }
  2346. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2347. cache.do_defrag = true;
  2348. }
  2349. //
  2350. // model loading and saving
  2351. //
  2352. enum llama_fver {
  2353. GGUF_FILE_VERSION_V1 = 1,
  2354. GGUF_FILE_VERSION_V2 = 2,
  2355. GGUF_FILE_VERSION_V3 = 3,
  2356. };
  2357. static const char * llama_file_version_name(llama_fver version) {
  2358. switch (version) {
  2359. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2360. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2361. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2362. }
  2363. return "unknown";
  2364. }
  2365. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2366. char buf[256];
  2367. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2368. for (size_t i = 1; i < ne.size(); i++) {
  2369. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2370. }
  2371. return buf;
  2372. }
  2373. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2374. char buf[256];
  2375. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2376. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2377. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2378. }
  2379. return buf;
  2380. }
  2381. namespace GGUFMeta {
  2382. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2383. struct GKV_Base_Type {
  2384. static constexpr gguf_type gt = gt_;
  2385. static T getter(const gguf_context * ctx, const int kid) {
  2386. return gfun(ctx, kid);
  2387. }
  2388. };
  2389. template<typename T> struct GKV_Base;
  2390. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2391. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2392. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2393. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2394. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2395. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2396. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2397. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2398. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2399. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2400. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2401. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2402. template<> struct GKV_Base<std::string> {
  2403. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2404. static std::string getter(const gguf_context * ctx, const int kid) {
  2405. return gguf_get_val_str(ctx, kid);
  2406. }
  2407. };
  2408. struct ArrayInfo {
  2409. const gguf_type gt;
  2410. const size_t length;
  2411. const void * data;
  2412. };
  2413. template<> struct GKV_Base<ArrayInfo> {
  2414. public:
  2415. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2416. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2417. return ArrayInfo {
  2418. gguf_get_arr_type(ctx, k),
  2419. size_t(gguf_get_arr_n(ctx, k)),
  2420. gguf_get_arr_data(ctx, k),
  2421. };
  2422. }
  2423. };
  2424. template<typename T>
  2425. class GKV : public GKV_Base<T> {
  2426. GKV() = delete;
  2427. public:
  2428. static T get_kv(const gguf_context * ctx, const int k) {
  2429. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2430. if (kt != GKV::gt) {
  2431. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2432. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2433. }
  2434. return GKV::getter(ctx, k);
  2435. }
  2436. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2437. switch (ty) {
  2438. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2439. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2440. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2441. }
  2442. return "unknown";
  2443. }
  2444. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2445. if (!ovrd) { return false; }
  2446. if (ovrd->tag == expected_type) {
  2447. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2448. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2449. switch (ovrd->tag) {
  2450. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2451. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2452. } break;
  2453. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2454. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2455. } break;
  2456. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2457. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2458. } break;
  2459. default:
  2460. // Shouldn't be possible to end up here, but just in case...
  2461. throw std::runtime_error(
  2462. format("Unsupported attempt to override %s type for metadata key %s\n",
  2463. override_type_to_str(ovrd->tag), ovrd->key));
  2464. }
  2465. return true;
  2466. }
  2467. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2468. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2469. return false;
  2470. }
  2471. template<typename OT>
  2472. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2473. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2474. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2475. target = ovrd->bool_value;
  2476. return true;
  2477. }
  2478. return false;
  2479. }
  2480. template<typename OT>
  2481. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2482. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2483. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2484. target = ovrd->int_value;
  2485. return true;
  2486. }
  2487. return false;
  2488. }
  2489. template<typename OT>
  2490. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2491. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2492. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2493. target = ovrd->float_value;
  2494. return true;
  2495. }
  2496. return false;
  2497. }
  2498. template<typename OT>
  2499. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2500. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2501. (void)target;
  2502. (void)ovrd;
  2503. if (!ovrd) { return false; }
  2504. // Currently, we should never end up here so it would be a bug if we do.
  2505. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2506. ovrd ? ovrd->key : "NULL"));
  2507. }
  2508. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2509. if (try_override<T>(target, ovrd)) {
  2510. return true;
  2511. }
  2512. if (k < 0) { return false; }
  2513. target = get_kv(ctx, k);
  2514. return true;
  2515. }
  2516. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2517. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2518. }
  2519. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2520. return set(ctx, key.c_str(), target, ovrd);
  2521. }
  2522. };
  2523. }
  2524. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2525. struct llama_model_loader {
  2526. int n_kv = 0;
  2527. int n_tensors = 0;
  2528. int n_created = 0;
  2529. int64_t n_elements = 0;
  2530. size_t n_bytes = 0;
  2531. bool use_mmap = false;
  2532. llama_files files;
  2533. llama_ftype ftype;
  2534. llama_fver fver;
  2535. llama_mmaps mappings;
  2536. // Holds information on a model weight
  2537. struct llama_tensor_weight {
  2538. uint16_t idx; // source file index
  2539. size_t offs; // tensor data offset in the original file
  2540. ggml_tensor * tensor;
  2541. llama_tensor_weight(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2542. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2543. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2544. }
  2545. };
  2546. std::vector<llama_tensor_weight> weights;
  2547. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2548. struct gguf_context * meta = NULL;
  2549. std::vector<ggml_context *> contexts;
  2550. std::string arch_name;
  2551. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2552. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2553. int trace = 0;
  2554. if (getenv("LLAMA_TRACE")) {
  2555. trace = atoi(getenv("LLAMA_TRACE"));
  2556. }
  2557. if (param_overrides_p != nullptr) {
  2558. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2559. kv_overrides.insert({std::string(p->key), *p});
  2560. }
  2561. }
  2562. struct ggml_context * ctx = NULL;
  2563. struct gguf_init_params params = {
  2564. /*.no_alloc = */ true,
  2565. /*.ctx = */ &ctx,
  2566. };
  2567. meta = gguf_init_from_file(fname.c_str(), params);
  2568. if (!meta) {
  2569. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2570. }
  2571. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2572. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2573. // Save tensors data offset of the main file.
  2574. // For subsidiary files, `meta` tensor data offset must not be used,
  2575. // so we build a unified tensors index for weights.
  2576. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2577. weights.emplace_back(0, cur->name, meta, cur);
  2578. }
  2579. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2580. contexts.emplace_back(ctx);
  2581. uint16_t n_split = 0;
  2582. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2583. // Load additional GGML contexts
  2584. if (n_split > 1) {
  2585. uint16_t idx = 0;
  2586. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2587. if (idx != 0) {
  2588. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2589. }
  2590. char split_prefix[PATH_MAX] = {0};
  2591. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2592. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2593. }
  2594. if (trace > 0) {
  2595. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2596. }
  2597. char split_path[PATH_MAX] = {0};
  2598. for (idx = 1; idx < n_split; idx++) {
  2599. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2600. struct gguf_init_params split_params = {
  2601. /*.no_alloc = */ true,
  2602. /*.ctx = */ &ctx,
  2603. };
  2604. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2605. if (!ctx_gguf) {
  2606. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2607. }
  2608. // Save tensors data offset info of the shard.
  2609. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2610. weights.emplace_back(idx, cur->name, ctx_gguf, cur);
  2611. }
  2612. files.emplace_back(new llama_file(split_path, "rb"));
  2613. contexts.emplace_back(ctx);
  2614. gguf_free(ctx_gguf);
  2615. }
  2616. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2617. // sanity check
  2618. {
  2619. const int n_tensors_loaded = (int) weights.size();
  2620. if (n_tensors != n_tensors_loaded) {
  2621. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2622. }
  2623. }
  2624. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2625. }
  2626. n_kv = gguf_get_n_kv(meta);
  2627. n_tensors = weights.size();
  2628. fver = (enum llama_fver) gguf_get_version(meta);
  2629. for (auto & w : weights) {
  2630. n_elements += ggml_nelements(w.tensor);
  2631. n_bytes += ggml_nbytes(w.tensor);
  2632. }
  2633. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2634. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2635. // determine file type based on the number of tensors for each quantization and print meta data
  2636. // TODO: make optional
  2637. {
  2638. std::map<enum ggml_type, uint32_t> n_type;
  2639. uint32_t n_type_max = 0;
  2640. enum ggml_type type_max = GGML_TYPE_F32;
  2641. for (int i = 0; i < n_tensors; i++) {
  2642. const ggml_tensor * tensor = weights.at(i).tensor;
  2643. enum ggml_type type = tensor->type;
  2644. n_type[type]++;
  2645. if (n_type_max < n_type[type]) {
  2646. n_type_max = n_type[type];
  2647. type_max = type;
  2648. }
  2649. if (trace > 0) {
  2650. const uint16_t sid = weights.at(i).idx;
  2651. 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());
  2652. }
  2653. }
  2654. switch (type_max) {
  2655. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2656. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2657. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2658. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2659. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2660. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2661. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2662. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2663. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2664. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2665. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2666. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2667. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2668. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2669. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2670. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2671. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2672. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2673. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2674. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2675. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2676. default:
  2677. {
  2678. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2679. ftype = LLAMA_FTYPE_ALL_F32;
  2680. } break;
  2681. }
  2682. // this is a way to mark that we have "guessed" the file type
  2683. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2684. {
  2685. const int kid = gguf_find_key(meta, "general.file_type");
  2686. if (kid >= 0) {
  2687. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2688. }
  2689. }
  2690. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2691. for (int i = 0; i < n_kv; i++) {
  2692. const char * name = gguf_get_key(meta, i);
  2693. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2694. const std::string type_name =
  2695. type == GGUF_TYPE_ARRAY
  2696. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2697. : gguf_type_name(type);
  2698. std::string value = gguf_kv_to_str(meta, i);
  2699. const size_t MAX_VALUE_LEN = 40;
  2700. if (value.size() > MAX_VALUE_LEN) {
  2701. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2702. }
  2703. replace_all(value, "\n", "\\n");
  2704. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2705. }
  2706. // print type counts
  2707. for (auto & kv : n_type) {
  2708. if (kv.second == 0) {
  2709. continue;
  2710. }
  2711. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2712. }
  2713. }
  2714. if (!llama_mmap::SUPPORTED) {
  2715. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2716. use_mmap = false;
  2717. }
  2718. this->use_mmap = use_mmap;
  2719. }
  2720. ~llama_model_loader() {
  2721. if (meta) {
  2722. gguf_free(meta);
  2723. }
  2724. for (auto * ctx : contexts) {
  2725. ggml_free(ctx);
  2726. }
  2727. }
  2728. template<typename T>
  2729. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2730. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2731. const int kid = gguf_find_key(meta, key.c_str());
  2732. if (kid < 0) {
  2733. if (required) {
  2734. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2735. }
  2736. return false;
  2737. }
  2738. struct GGUFMeta::ArrayInfo arr_info =
  2739. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2740. result = arr_info.length;
  2741. return true;
  2742. }
  2743. template<typename T>
  2744. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2745. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2746. return get_arr_n(llm_kv(kid), result, required);
  2747. }
  2748. template<typename T>
  2749. bool get_key(const std::string & key, T & result, const bool required = true) {
  2750. auto it = kv_overrides.find(key);
  2751. const struct llama_model_kv_override * override =
  2752. it != kv_overrides.end() ? &it->second : nullptr;
  2753. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2754. if (required && !found) {
  2755. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2756. }
  2757. return found;
  2758. }
  2759. template<typename T>
  2760. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2761. return get_key(llm_kv(kid), result, required);
  2762. }
  2763. std::string get_arch_name() const {
  2764. return arch_name;
  2765. }
  2766. enum llm_arch get_arch() const {
  2767. return llm_kv.arch;
  2768. }
  2769. const char * get_tensor_name(int i) const {
  2770. return weights.at(i).tensor->name;
  2771. }
  2772. const llama_tensor_weight * get_weight(const char * name) const {
  2773. for (const auto & weight : weights) {
  2774. if (strcmp(name, weight.tensor->name) == 0) {
  2775. return &weight;
  2776. }
  2777. }
  2778. return nullptr;
  2779. }
  2780. const llama_tensor_weight & require_weight(const char * name) const {
  2781. const llama_tensor_weight * weight = get_weight(name);
  2782. if (!weight) {
  2783. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2784. }
  2785. return *weight;
  2786. }
  2787. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2788. const auto * weight = get_weight(name);
  2789. if (!weight) {
  2790. return nullptr;
  2791. }
  2792. return weight->tensor;
  2793. }
  2794. struct ggml_tensor * require_tensor_meta(const char * name) const {
  2795. struct ggml_tensor * tensor = get_tensor_meta(name);
  2796. if (!tensor) {
  2797. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2798. }
  2799. return tensor;
  2800. }
  2801. struct ggml_tensor * get_tensor_meta(int i) const {
  2802. return get_tensor_meta(get_tensor_name(i));
  2803. }
  2804. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2805. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2806. ggml_set_name(tensor, ggml_get_name(cur));
  2807. n_created++;
  2808. return tensor;
  2809. }
  2810. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  2811. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2812. if (cur == NULL) {
  2813. if (!required) {
  2814. return NULL;
  2815. }
  2816. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2817. }
  2818. {
  2819. bool is_ok = true;
  2820. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2821. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  2822. is_ok = false;
  2823. break;
  2824. }
  2825. }
  2826. if (!is_ok) {
  2827. throw std::runtime_error(
  2828. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2829. __func__, name.c_str(),
  2830. llama_format_tensor_shape(ne).c_str(),
  2831. llama_format_tensor_shape(cur).c_str()));
  2832. }
  2833. }
  2834. return cur;
  2835. }
  2836. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2837. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2838. if (cur == NULL) {
  2839. return NULL;
  2840. }
  2841. return create_tensor_for(ctx, cur);
  2842. }
  2843. 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) {
  2844. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2845. if (cur == NULL) {
  2846. return NULL;
  2847. }
  2848. if (cur->type != base->type) {
  2849. 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)));
  2850. }
  2851. std::array<int64_t, GGML_MAX_DIMS> dims;
  2852. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2853. dims[i] = i < ne.size() ? ne[i] : 1;
  2854. }
  2855. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  2856. dims[0], dims[1], dims[2], dims[3],
  2857. cur->nb[1], cur->nb[2], cur->nb[3],
  2858. offset);
  2859. ggml_set_name(tensor, name.c_str());
  2860. n_created++;
  2861. return tensor;
  2862. }
  2863. void done_getting_tensors() const {
  2864. if (n_created != n_tensors) {
  2865. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2866. }
  2867. }
  2868. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2869. if (use_mmap) {
  2870. mappings.reserve(files.size());
  2871. mmaps_used.reserve(files.size());
  2872. for (const auto & file : files) {
  2873. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2874. mmaps_used.emplace_back(mapping->size, 0);
  2875. if (mlock_mmaps) {
  2876. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2877. mlock_mmap->init(mapping->addr);
  2878. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2879. }
  2880. mappings.emplace_back(std::move(mapping));
  2881. }
  2882. }
  2883. // compute the total size of all tensors for progress reporting
  2884. for (auto & w : weights) {
  2885. size_data += ggml_nbytes(w.tensor);
  2886. }
  2887. }
  2888. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2889. GGML_ASSERT(!mappings.empty());
  2890. const auto & mapping = mappings.at(idx);
  2891. *first = mapping->size;
  2892. *last = 0;
  2893. *addr = mapping->addr;
  2894. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2895. try {
  2896. const auto * weight = get_weight(ggml_get_name(tensor));
  2897. if (!weight) {
  2898. continue;
  2899. }
  2900. if (weight->idx != idx) {
  2901. continue;
  2902. }
  2903. *first = std::min(*first, weight->offs);
  2904. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  2905. } catch(...) {
  2906. // the tensor is not in the model
  2907. }
  2908. }
  2909. }
  2910. // for backwards compatibility, does not support ggml-backend
  2911. void load_data_for(struct ggml_tensor * cur) const {
  2912. const auto & w = require_weight(ggml_get_name(cur));
  2913. if (use_mmap) {
  2914. const auto & mapping = mappings.at(w.idx);
  2915. if (cur->data == nullptr) {
  2916. cur->data = (uint8_t *)mapping->addr + w.offs;
  2917. } else {
  2918. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2919. }
  2920. } else {
  2921. GGML_ASSERT(cur->data != nullptr);
  2922. GGML_ASSERT(w.idx < files.size());
  2923. const auto & file = files.at(w.idx);
  2924. file->seek(w.offs, SEEK_SET);
  2925. file->read_raw(cur->data, ggml_nbytes(cur));
  2926. }
  2927. }
  2928. size_t size_done = 0;
  2929. size_t size_data = 0;
  2930. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2931. // Returns false if cancelled by progress_callback
  2932. bool load_all_data(
  2933. struct ggml_context * ctx,
  2934. llama_buf_map & bufs_mmap,
  2935. llama_mlocks * lmlocks,
  2936. llama_progress_callback progress_callback,
  2937. void * progress_callback_user_data) {
  2938. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2939. std::vector<no_init<uint8_t>> read_buf;
  2940. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2941. const auto * weight = get_weight(ggml_get_name(cur));
  2942. if (weight == nullptr) {
  2943. // this can happen with split experts models
  2944. continue;
  2945. }
  2946. if (progress_callback) {
  2947. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2948. return false;
  2949. }
  2950. }
  2951. size_t n_size = ggml_nbytes(cur);
  2952. if (use_mmap) {
  2953. const auto & mapping = mappings.at(weight->idx);
  2954. ggml_backend_buffer_t buf_mmap = nullptr;
  2955. if (bufs_mmap.count(weight->idx)) {
  2956. buf_mmap = bufs_mmap.at(weight->idx);
  2957. }
  2958. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2959. if (buf_mmap && cur->data == nullptr) {
  2960. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + weight->offs);
  2961. if (lmlocks) {
  2962. const auto & lmlock = lmlocks->at(weight->idx);
  2963. lmlock->grow_to(weight->offs + ggml_nbytes(cur));
  2964. }
  2965. auto & mmap_used = mmaps_used[weight->idx];
  2966. mmap_used.first = std::min(mmap_used.first, weight->offs);
  2967. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  2968. } else {
  2969. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + weight->offs, 0, n_size);
  2970. }
  2971. } else {
  2972. GGML_ASSERT(weight->idx < files.size());
  2973. const auto & file = files.at(weight->idx);
  2974. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2975. file->seek(weight->offs, SEEK_SET);
  2976. file->read_raw(cur->data, ggml_nbytes(cur));
  2977. } else {
  2978. read_buf.resize(ggml_nbytes(cur));
  2979. file->seek(weight->offs, SEEK_SET);
  2980. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2981. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2982. }
  2983. }
  2984. size_done += n_size;
  2985. }
  2986. // check if this is the last call and do final cleanup
  2987. if (size_done >= size_data) {
  2988. // unmap offloaded tensors and metadata
  2989. if (use_mmap) {
  2990. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2991. const auto & mmap_used = mmaps_used.at(idx);
  2992. auto & mapping = mappings.at(idx);
  2993. mapping->unmap_fragment(0, mmap_used.first);
  2994. if (mmap_used.second != 0) {
  2995. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2996. }
  2997. }
  2998. }
  2999. if (progress_callback) {
  3000. // Even though the model is done loading, we still honor
  3001. // cancellation since we need to free allocations.
  3002. return progress_callback(1.0f, progress_callback_user_data);
  3003. }
  3004. }
  3005. return true;
  3006. }
  3007. };
  3008. template<>
  3009. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3010. uint32_t tmp;
  3011. const bool found = get_key(kid, tmp, required);
  3012. if (found) {
  3013. result = (enum llama_pooling_type) tmp;
  3014. } else {
  3015. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3016. }
  3017. return found;
  3018. }
  3019. //
  3020. // load LLaMA models
  3021. //
  3022. static const char * llama_model_arch_name(llm_arch arch) {
  3023. auto it = LLM_ARCH_NAMES.find(arch);
  3024. if (it == LLM_ARCH_NAMES.end()) {
  3025. return "unknown";
  3026. }
  3027. return it->second;
  3028. }
  3029. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3030. if (ftype & LLAMA_FTYPE_GUESSED) {
  3031. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3032. }
  3033. switch (ftype) {
  3034. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3035. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3036. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3037. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3038. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  3039. return "Q4_1, some F16";
  3040. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3041. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3042. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3043. // K-quants
  3044. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3045. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3046. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3047. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3048. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3049. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3050. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3051. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3052. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3053. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3054. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  3055. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3056. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3057. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3058. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3059. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  3060. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  3061. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  3062. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3063. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3064. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3065. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3066. default: return "unknown, may not work";
  3067. }
  3068. }
  3069. static const char * llama_model_type_name(e_model type) {
  3070. switch (type) {
  3071. case MODEL_22M: return "22M";
  3072. case MODEL_33M: return "33M";
  3073. case MODEL_109M: return "109M";
  3074. case MODEL_137M: return "137M";
  3075. case MODEL_0_5B: return "0.5B";
  3076. case MODEL_1B: return "1B";
  3077. case MODEL_2B: return "2B";
  3078. case MODEL_3B: return "3B";
  3079. case MODEL_7B: return "7B";
  3080. case MODEL_8B: return "8B";
  3081. case MODEL_13B: return "13B";
  3082. case MODEL_14B: return "14B";
  3083. case MODEL_15B: return "15B";
  3084. case MODEL_20B: return "20B";
  3085. case MODEL_30B: return "30B";
  3086. case MODEL_34B: return "34B";
  3087. case MODEL_35B: return "35B";
  3088. case MODEL_40B: return "40B";
  3089. case MODEL_65B: return "65B";
  3090. case MODEL_70B: return "70B";
  3091. case MODEL_314B: return "314B";
  3092. case MODEL_SMALL: return "0.1B";
  3093. case MODEL_MEDIUM: return "0.4B";
  3094. case MODEL_LARGE: return "0.8B";
  3095. case MODEL_XL: return "1.5B";
  3096. case MODEL_8x7B: return "8x7B";
  3097. case MODEL_8x22B: return "8x22B";
  3098. default: return "?B";
  3099. }
  3100. }
  3101. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3102. switch (type) {
  3103. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3104. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3105. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3106. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3107. default: return "unknown";
  3108. }
  3109. }
  3110. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3111. model.arch = ml.get_arch();
  3112. if (model.arch == LLM_ARCH_UNKNOWN) {
  3113. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3114. }
  3115. }
  3116. static void llm_load_hparams(
  3117. llama_model_loader & ml,
  3118. llama_model & model) {
  3119. auto & hparams = model.hparams;
  3120. const gguf_context * ctx = ml.meta;
  3121. // get metadata as string
  3122. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3123. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3124. if (type == GGUF_TYPE_ARRAY) {
  3125. continue;
  3126. }
  3127. const char * name = gguf_get_key(ctx, i);
  3128. const std::string value = gguf_kv_to_str(ctx, i);
  3129. model.gguf_kv.emplace(name, value);
  3130. }
  3131. // get general kv
  3132. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3133. // get hparams kv
  3134. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3135. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3136. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3137. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3138. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3139. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3140. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3141. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3142. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3143. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3144. if (hparams.n_expert > 0) {
  3145. GGML_ASSERT(hparams.n_expert_used > 0);
  3146. } else {
  3147. GGML_ASSERT(hparams.n_expert_used == 0);
  3148. }
  3149. // n_head_kv is optional, default to n_head
  3150. hparams.n_head_kv = hparams.n_head;
  3151. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3152. bool rope_finetuned = false;
  3153. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3154. hparams.rope_finetuned = rope_finetuned;
  3155. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3156. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3157. // rope_freq_base (optional)
  3158. hparams.rope_freq_base_train = 10000.0f;
  3159. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3160. std::string rope_scaling("linear");
  3161. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3162. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3163. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3164. // rope_freq_scale (inverse of the kv) is optional
  3165. float ropescale = 0.0f;
  3166. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3167. // try the old key name
  3168. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3169. }
  3170. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3171. // sanity check for n_rot (optional)
  3172. {
  3173. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3174. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3175. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3176. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3177. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3178. }
  3179. }
  3180. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3181. // gpt-j n_rot = rotary_dim
  3182. }
  3183. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3184. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3185. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3186. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3187. // arch-specific KVs
  3188. switch (model.arch) {
  3189. case LLM_ARCH_LLAMA:
  3190. {
  3191. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3192. if (hparams.n_expert == 8) {
  3193. switch (hparams.n_layer) {
  3194. case 32: model.type = e_model::MODEL_8x7B; break;
  3195. case 56: model.type = e_model::MODEL_8x22B; break;
  3196. default: model.type = e_model::MODEL_UNKNOWN;
  3197. }
  3198. } else {
  3199. switch (hparams.n_layer) {
  3200. case 22: model.type = e_model::MODEL_1B; break;
  3201. case 26: model.type = e_model::MODEL_3B; break;
  3202. case 32: model.type = e_model::MODEL_7B; break;
  3203. case 40: model.type = e_model::MODEL_13B; break;
  3204. case 48: model.type = e_model::MODEL_34B; break;
  3205. case 60: model.type = e_model::MODEL_30B; break;
  3206. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3207. default: model.type = e_model::MODEL_UNKNOWN;
  3208. }
  3209. }
  3210. } break;
  3211. case LLM_ARCH_MINICPM:
  3212. {
  3213. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3214. switch (hparams.n_layer) {
  3215. case 40: model.type = e_model::MODEL_2B; break;
  3216. default: model.type = e_model::MODEL_UNKNOWN;
  3217. }
  3218. } break;
  3219. case LLM_ARCH_GROK:
  3220. {
  3221. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3222. switch (hparams.n_layer) {
  3223. case 64: model.type = e_model::MODEL_314B; break;
  3224. default: model.type = e_model::MODEL_UNKNOWN;
  3225. }
  3226. } break;
  3227. case LLM_ARCH_FALCON:
  3228. {
  3229. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3230. switch (hparams.n_layer) {
  3231. case 32: model.type = e_model::MODEL_7B; break;
  3232. case 60: model.type = e_model::MODEL_40B; break;
  3233. default: model.type = e_model::MODEL_UNKNOWN;
  3234. }
  3235. } break;
  3236. case LLM_ARCH_BAICHUAN:
  3237. {
  3238. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3239. switch (hparams.n_layer) {
  3240. case 32: model.type = e_model::MODEL_7B; break;
  3241. case 40: model.type = e_model::MODEL_13B; break;
  3242. default: model.type = e_model::MODEL_UNKNOWN;
  3243. }
  3244. if (model.type == e_model::MODEL_13B) {
  3245. // TODO: become GGUF KV parameter
  3246. hparams.f_max_alibi_bias = 8.0f;
  3247. }
  3248. } break;
  3249. case LLM_ARCH_STARCODER:
  3250. {
  3251. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3252. switch (hparams.n_layer) {
  3253. case 24: model.type = e_model::MODEL_1B; break;
  3254. case 36: model.type = e_model::MODEL_3B; break;
  3255. case 42: model.type = e_model::MODEL_7B; break;
  3256. case 40: model.type = e_model::MODEL_15B; break;
  3257. default: model.type = e_model::MODEL_UNKNOWN;
  3258. }
  3259. } break;
  3260. case LLM_ARCH_PERSIMMON:
  3261. {
  3262. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3263. switch (hparams.n_layer) {
  3264. case 36: model.type = e_model::MODEL_8B; break;
  3265. default: model.type = e_model::MODEL_UNKNOWN;
  3266. }
  3267. } break;
  3268. case LLM_ARCH_REFACT:
  3269. {
  3270. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3271. switch (hparams.n_layer) {
  3272. case 32: model.type = e_model::MODEL_1B; break;
  3273. default: model.type = e_model::MODEL_UNKNOWN;
  3274. }
  3275. // TODO: become GGUF KV parameter
  3276. hparams.f_max_alibi_bias = 8.0f;
  3277. } break;
  3278. case LLM_ARCH_BERT:
  3279. {
  3280. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3281. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3282. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3283. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3284. switch (hparams.n_layer) {
  3285. case 3:
  3286. model.type = e_model::MODEL_17M; break; // bge-micro
  3287. case 6:
  3288. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3289. case 12:
  3290. switch (hparams.n_embd) {
  3291. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3292. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3293. } break;
  3294. case 24:
  3295. model.type = e_model::MODEL_335M; break; // bge-large
  3296. }
  3297. } break;
  3298. case LLM_ARCH_NOMIC_BERT:
  3299. {
  3300. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3301. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3302. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3303. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3304. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3305. model.type = e_model::MODEL_137M;
  3306. }
  3307. } break;
  3308. case LLM_ARCH_BLOOM:
  3309. {
  3310. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3311. switch (hparams.n_layer) {
  3312. case 24: model.type = e_model::MODEL_1B; break;
  3313. case 30:
  3314. switch (hparams.n_embd) {
  3315. case 2560: model.type = e_model::MODEL_3B; break;
  3316. case 4096: model.type = e_model::MODEL_7B; break;
  3317. } break;
  3318. }
  3319. // TODO: become GGUF KV parameter
  3320. hparams.f_max_alibi_bias = 8.0f;
  3321. } break;
  3322. case LLM_ARCH_MPT:
  3323. {
  3324. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3325. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3326. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3327. switch (hparams.n_layer) {
  3328. case 32: model.type = e_model::MODEL_7B; break;
  3329. case 48: model.type = e_model::MODEL_30B; break;
  3330. default: model.type = e_model::MODEL_UNKNOWN;
  3331. }
  3332. } break;
  3333. case LLM_ARCH_STABLELM:
  3334. {
  3335. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3336. switch (hparams.n_layer) {
  3337. case 24: model.type = e_model::MODEL_1B; break;
  3338. case 32: model.type = e_model::MODEL_3B; break;
  3339. default: model.type = e_model::MODEL_UNKNOWN;
  3340. }
  3341. } break;
  3342. case LLM_ARCH_QWEN:
  3343. {
  3344. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3345. switch (hparams.n_layer) {
  3346. case 32: model.type = e_model::MODEL_7B; break;
  3347. case 40: model.type = e_model::MODEL_13B; break;
  3348. default: model.type = e_model::MODEL_UNKNOWN;
  3349. }
  3350. } break;
  3351. case LLM_ARCH_QWEN2:
  3352. {
  3353. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3354. switch (hparams.n_layer) {
  3355. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3356. case 32: model.type = e_model::MODEL_7B; break;
  3357. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3358. case 80: model.type = e_model::MODEL_70B; break;
  3359. default: model.type = e_model::MODEL_UNKNOWN;
  3360. }
  3361. } break;
  3362. case LLM_ARCH_PHI2:
  3363. {
  3364. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3365. switch (hparams.n_layer) {
  3366. case 24: model.type = e_model::MODEL_1B; break;
  3367. case 32: model.type = e_model::MODEL_3B; break;
  3368. default: model.type = e_model::MODEL_UNKNOWN;
  3369. }
  3370. } break;
  3371. case LLM_ARCH_PLAMO:
  3372. {
  3373. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3374. switch (hparams.n_layer) {
  3375. case 40: model.type = e_model::MODEL_13B; break;
  3376. default: model.type = e_model::MODEL_UNKNOWN;
  3377. }
  3378. } break;
  3379. case LLM_ARCH_GPT2:
  3380. {
  3381. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3382. switch (hparams.n_layer) {
  3383. case 12: model.type = e_model::MODEL_SMALL; break;
  3384. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3385. case 36: model.type = e_model::MODEL_LARGE; break;
  3386. case 48: model.type = e_model::MODEL_XL; break;
  3387. default: model.type = e_model::MODEL_UNKNOWN;
  3388. }
  3389. } break;
  3390. case LLM_ARCH_CODESHELL:
  3391. {
  3392. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3393. switch (hparams.n_layer) {
  3394. case 42: model.type = e_model::MODEL_SMALL; break;
  3395. default: model.type = e_model::MODEL_UNKNOWN;
  3396. }
  3397. } break;
  3398. case LLM_ARCH_ORION:
  3399. {
  3400. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3401. switch (hparams.n_layer) {
  3402. case 40: model.type = e_model::MODEL_14B; break;
  3403. default: model.type = e_model::MODEL_UNKNOWN;
  3404. }
  3405. } break;
  3406. case LLM_ARCH_INTERNLM2:
  3407. {
  3408. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3409. switch (hparams.n_layer) {
  3410. case 32: model.type = e_model::MODEL_7B; break;
  3411. case 48: model.type = e_model::MODEL_20B; break;
  3412. default: model.type = e_model::MODEL_UNKNOWN;
  3413. }
  3414. } break;
  3415. case LLM_ARCH_GEMMA:
  3416. {
  3417. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3418. switch (hparams.n_layer) {
  3419. case 18: model.type = e_model::MODEL_2B; break;
  3420. case 28: model.type = e_model::MODEL_7B; break;
  3421. default: model.type = e_model::MODEL_UNKNOWN;
  3422. }
  3423. } break;
  3424. case LLM_ARCH_STARCODER2:
  3425. {
  3426. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3427. switch (hparams.n_layer) {
  3428. case 30: model.type = e_model::MODEL_3B; break;
  3429. case 32: model.type = e_model::MODEL_7B; break;
  3430. case 40: model.type = e_model::MODEL_15B; break;
  3431. default: model.type = e_model::MODEL_UNKNOWN;
  3432. }
  3433. } break;
  3434. case LLM_ARCH_MAMBA:
  3435. {
  3436. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3437. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3438. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3439. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3440. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3441. switch (hparams.n_layer) {
  3442. case 24:
  3443. switch (hparams.n_embd) {
  3444. case 768: model.type = e_model::MODEL_SMALL; break;
  3445. default: model.type = e_model::MODEL_UNKNOWN;
  3446. } break;
  3447. case 48:
  3448. switch (hparams.n_embd) {
  3449. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3450. case 1536: model.type = e_model::MODEL_LARGE; break;
  3451. case 2048: model.type = e_model::MODEL_XL; break;
  3452. default: model.type = e_model::MODEL_UNKNOWN;
  3453. } break;
  3454. case 64:
  3455. switch (hparams.n_embd) {
  3456. case 2560: model.type = e_model::MODEL_3B; break;
  3457. default: model.type = e_model::MODEL_UNKNOWN;
  3458. } break;
  3459. default: model.type = e_model::MODEL_UNKNOWN;
  3460. }
  3461. } break;
  3462. case LLM_ARCH_XVERSE:
  3463. {
  3464. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3465. switch (hparams.n_layer) {
  3466. case 32: model.type = e_model::MODEL_7B; break;
  3467. case 40: model.type = e_model::MODEL_13B; break;
  3468. case 80: model.type = e_model::MODEL_65B; break;
  3469. default: model.type = e_model::MODEL_UNKNOWN;
  3470. }
  3471. } break;
  3472. case LLM_ARCH_COMMAND_R:
  3473. {
  3474. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3475. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3476. switch (hparams.n_layer) {
  3477. case 40: model.type = e_model::MODEL_35B; break;
  3478. default: model.type = e_model::MODEL_UNKNOWN;
  3479. }
  3480. } break;
  3481. default: (void)0;
  3482. }
  3483. model.ftype = ml.ftype;
  3484. if (hparams.f_max_alibi_bias > 0.0f) {
  3485. hparams.need_kq_pos = true;
  3486. }
  3487. hparams.rope_type = llama_rope_type(&model);
  3488. }
  3489. // TODO: This should probably be in llama.h
  3490. static std::vector<llama_vocab::id> llama_tokenize_internal(
  3491. const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special = false
  3492. );
  3493. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3494. static void llm_load_vocab(
  3495. llama_model_loader & ml,
  3496. llama_model & model) {
  3497. auto & vocab = model.vocab;
  3498. struct gguf_context * ctx = ml.meta;
  3499. const auto kv = LLM_KV(model.arch);
  3500. // determine vocab type
  3501. {
  3502. std::string tokenizer_name;
  3503. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3504. if (tokenizer_name == "no_vocab") {
  3505. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3506. // default special tokens
  3507. vocab.special_bos_id = -1;
  3508. vocab.special_eos_id = -1;
  3509. vocab.special_unk_id = -1;
  3510. vocab.special_sep_id = -1;
  3511. vocab.special_pad_id = -1;
  3512. vocab.special_cls_id = -1;
  3513. vocab.special_mask_id = -1;
  3514. vocab.linefeed_id = -1;
  3515. return;
  3516. } else if (tokenizer_name == "llama") {
  3517. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3518. // default special tokens
  3519. vocab.special_bos_id = 1;
  3520. vocab.special_eos_id = 2;
  3521. vocab.special_unk_id = 0;
  3522. vocab.special_sep_id = -1;
  3523. vocab.special_pad_id = -1;
  3524. vocab.special_cls_id = -1;
  3525. vocab.special_mask_id = -1;
  3526. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3527. if (add_space_prefix_keyidx != -1) {
  3528. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3529. } // The default value of add_space_prefix is true.
  3530. } else if (tokenizer_name == "gpt2") {
  3531. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3532. // read bpe merges and populate bpe ranks
  3533. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3534. if (merges_keyidx == -1) {
  3535. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3536. }
  3537. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3538. for (int i = 0; i < n_merges; i++) {
  3539. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3540. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3541. std::string first;
  3542. std::string second;
  3543. const size_t pos = word.find(' ', 1);
  3544. if (pos != std::string::npos) {
  3545. first = word.substr(0, pos);
  3546. second = word.substr(pos + 1);
  3547. }
  3548. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3549. }
  3550. // default special tokens
  3551. vocab.special_bos_id = 11;
  3552. vocab.special_eos_id = 11;
  3553. vocab.special_unk_id = -1;
  3554. vocab.special_sep_id = -1;
  3555. vocab.special_pad_id = -1;
  3556. vocab.special_cls_id = -1;
  3557. vocab.special_mask_id = -1;
  3558. } else if (tokenizer_name == "bert") {
  3559. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3560. // default special tokens
  3561. vocab.special_bos_id = -1;
  3562. vocab.special_eos_id = -1;
  3563. vocab.special_unk_id = 100;
  3564. vocab.special_sep_id = 102;
  3565. vocab.special_pad_id = 0;
  3566. vocab.special_cls_id = 101;
  3567. vocab.special_mask_id = 103;
  3568. vocab.add_space_prefix = false;
  3569. } else {
  3570. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3571. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3572. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3573. }
  3574. }
  3575. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3576. if (token_idx == -1) {
  3577. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3578. }
  3579. const float * scores = nullptr;
  3580. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3581. if (score_idx != -1) {
  3582. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3583. }
  3584. const int * toktypes = nullptr;
  3585. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3586. if (toktype_idx != -1) {
  3587. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3588. }
  3589. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3590. vocab.id_to_token.resize(n_vocab);
  3591. for (uint32_t i = 0; i < n_vocab; i++) {
  3592. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3593. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3594. vocab.token_to_id[word] = i;
  3595. auto & token_data = vocab.id_to_token[i];
  3596. token_data.text = std::move(word);
  3597. token_data.score = scores ? scores[i] : 0.0f;
  3598. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3599. }
  3600. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3601. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3602. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3603. try {
  3604. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3605. } catch (const std::exception & e) {
  3606. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3607. vocab.linefeed_id = vocab.special_pad_id;
  3608. }
  3609. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3610. vocab.linefeed_id = vocab.special_pad_id;
  3611. } else {
  3612. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3613. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3614. vocab.linefeed_id = ids[0];
  3615. }
  3616. // special tokens
  3617. {
  3618. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3619. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3620. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3621. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3622. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3623. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3624. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  3625. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  3626. };
  3627. for (const auto & it : special_token_types) {
  3628. const std::string & key = kv(std::get<0>(it));
  3629. int32_t & id = std::get<1>(it);
  3630. uint32_t new_id;
  3631. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3632. continue;
  3633. }
  3634. if (new_id >= vocab.id_to_token.size()) {
  3635. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3636. __func__, key.c_str(), new_id, id);
  3637. } else {
  3638. id = new_id;
  3639. }
  3640. }
  3641. // Handle add_bos_token and add_eos_token
  3642. {
  3643. bool temp = true;
  3644. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3645. vocab.special_add_bos = int(temp);
  3646. }
  3647. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3648. vocab.special_add_eos = int(temp);
  3649. }
  3650. }
  3651. }
  3652. // build special tokens cache
  3653. {
  3654. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3655. // and will always be correctly labeled in 'added_tokens.json' etc.
  3656. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3657. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3658. // are special tokens.
  3659. // From testing, this appears to correlate 1:1 with special tokens.
  3660. //
  3661. // Counting special tokens and verifying in only one direction
  3662. // is sufficient to detect difference in those two sets.
  3663. //
  3664. uint32_t special_tokens_count_by_type = 0;
  3665. uint32_t special_tokens_count_from_verification = 0;
  3666. bool special_tokens_definition_mismatch = false;
  3667. for (const auto & t : vocab.token_to_id) {
  3668. const auto & token = t.first;
  3669. const auto & id = t.second;
  3670. // Count all non-normal tokens in the vocab while iterating
  3671. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3672. special_tokens_count_by_type++;
  3673. }
  3674. // Skip single character tokens
  3675. if (token.length() > 1) {
  3676. bool is_tokenizable = false;
  3677. // Split token string representation in two, in all possible ways
  3678. // and check if both halves can be matched to a valid token
  3679. for (unsigned i = 1; i < token.length();) {
  3680. const auto left = token.substr(0, i);
  3681. const auto right = token.substr(i);
  3682. // check if we didnt partition in the middle of a utf sequence
  3683. auto utf = utf8_len(left.at(left.length() - 1));
  3684. if (utf == 1) {
  3685. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3686. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3687. is_tokenizable = true;
  3688. break;
  3689. }
  3690. i++;
  3691. } else {
  3692. // skip over the rest of multibyte utf sequence
  3693. i += utf - 1;
  3694. }
  3695. }
  3696. if (!is_tokenizable) {
  3697. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3698. // it's faster to re-filter them here, since there are way less candidates now
  3699. // Calculate a total "utf" length of a token string representation
  3700. size_t utf8_str_len = 0;
  3701. for (unsigned i = 0; i < token.length();) {
  3702. utf8_str_len++;
  3703. i += utf8_len(token.at(i));
  3704. }
  3705. // And skip the ones which are one character
  3706. if (utf8_str_len > 1) {
  3707. // At this point what we have left are special tokens only
  3708. vocab.special_tokens_cache[token] = id;
  3709. // Count manually found special tokens
  3710. special_tokens_count_from_verification++;
  3711. // If this manually found special token is not marked as such, flag a mismatch
  3712. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3713. special_tokens_definition_mismatch = true;
  3714. }
  3715. }
  3716. }
  3717. }
  3718. }
  3719. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3720. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3721. __func__,
  3722. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3723. special_tokens_count_by_type, vocab.id_to_token.size()
  3724. );
  3725. } else {
  3726. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3727. __func__,
  3728. special_tokens_count_from_verification, vocab.id_to_token.size()
  3729. );
  3730. }
  3731. }
  3732. }
  3733. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3734. const auto & hparams = model.hparams;
  3735. const auto & vocab = model.vocab;
  3736. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3737. // hparams
  3738. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3739. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3740. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3741. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3742. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3743. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3744. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3745. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3746. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3747. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3748. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3749. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3750. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3751. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3752. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3753. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3754. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3755. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3756. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3757. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3758. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3759. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3760. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3761. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3762. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3763. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3764. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3765. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3766. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3767. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3768. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3769. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3770. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3771. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3772. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3773. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3774. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3775. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3776. if (ml.n_elements >= 1e12) {
  3777. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3778. } else if (ml.n_elements >= 1e9) {
  3779. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3780. } else if (ml.n_elements >= 1e6) {
  3781. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3782. } else {
  3783. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3784. }
  3785. if (ml.n_bytes < GiB) {
  3786. 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);
  3787. } else {
  3788. 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);
  3789. }
  3790. // general kv
  3791. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3792. // special tokens
  3793. 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() ); }
  3794. 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() ); }
  3795. 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() ); }
  3796. 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() ); }
  3797. 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() ); }
  3798. 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() ); }
  3799. 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() ); }
  3800. 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() ); }
  3801. }
  3802. // Returns false if cancelled by progress_callback
  3803. static bool llm_load_tensors(
  3804. llama_model_loader & ml,
  3805. llama_model & model,
  3806. int n_gpu_layers,
  3807. enum llama_split_mode split_mode,
  3808. int main_gpu,
  3809. const float * tensor_split,
  3810. bool use_mlock,
  3811. llama_progress_callback progress_callback,
  3812. void * progress_callback_user_data) {
  3813. model.t_start_us = ggml_time_us();
  3814. auto & hparams = model.hparams;
  3815. model.split_mode = split_mode;
  3816. model.main_gpu = main_gpu;
  3817. model.n_gpu_layers = n_gpu_layers;
  3818. const int64_t n_layer = hparams.n_layer;
  3819. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3820. bool use_mmap_buffer = true;
  3821. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3822. model.buft_input = llama_default_buffer_type_cpu(true);
  3823. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3824. model.buft_layer.resize(n_layer);
  3825. // assign cpu layers
  3826. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3827. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3828. }
  3829. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3830. // calculate the split points
  3831. int device_count = llama_get_device_count();
  3832. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3833. std::vector<float> splits(device_count);
  3834. if (all_zero) {
  3835. // default split, by free memory
  3836. for (int i = 0; i < device_count; ++i) {
  3837. splits[i] = llama_get_device_memory(i);
  3838. }
  3839. } else {
  3840. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3841. }
  3842. // sum and normalize the splits to get the split points
  3843. float split_sum = 0.0f;
  3844. for (int i = 0; i < device_count; ++i) {
  3845. split_sum += splits[i];
  3846. splits[i] = split_sum;
  3847. }
  3848. for (int i = 0; i < device_count; ++i) {
  3849. splits[i] /= split_sum;
  3850. }
  3851. // assign the repeating layers to the devices according to the splits
  3852. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3853. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3854. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3855. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3856. }
  3857. // assign the output layer
  3858. if (n_gpu_layers > n_layer) {
  3859. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3860. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3861. } else {
  3862. model.buft_output = llama_default_buffer_type_cpu(true);
  3863. }
  3864. } else {
  3865. ggml_backend_buffer_type_t split_buft;
  3866. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3867. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3868. } else {
  3869. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3870. split_buft = llama_default_buffer_type_offload(main_gpu);
  3871. }
  3872. // assign the repeating layers
  3873. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3874. model.buft_layer[i] = {
  3875. split_buft,
  3876. llama_default_buffer_type_offload(main_gpu)
  3877. };
  3878. }
  3879. // assign the output layer
  3880. if (n_gpu_layers > n_layer) {
  3881. model.buft_output = {
  3882. split_buft,
  3883. llama_default_buffer_type_offload(main_gpu)
  3884. };
  3885. } else {
  3886. model.buft_output = llama_default_buffer_type_cpu(true);
  3887. }
  3888. }
  3889. // count used buffer types
  3890. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3891. buft_layer_count[model.buft_input.buft]++;
  3892. buft_layer_count[model.buft_input.buft_matrix]++;
  3893. buft_layer_count[model.buft_output.buft]++;
  3894. buft_layer_count[model.buft_output.buft_matrix]++;
  3895. for (int64_t i = 0; i < n_layer; ++i) {
  3896. buft_layer_count[model.buft_layer[i].buft]++;
  3897. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3898. }
  3899. // create one context per buffer type
  3900. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3901. // for moe merged tensors
  3902. ctx_size += ggml_tensor_overhead()*hparams.n_expert*n_layer;
  3903. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3904. for (auto & it : buft_layer_count) {
  3905. struct ggml_init_params params = {
  3906. /*.mem_size =*/ ctx_size,
  3907. /*.mem_buffer =*/ NULL,
  3908. /*.no_alloc =*/ true,
  3909. };
  3910. ggml_context * ctx = ggml_init(params);
  3911. if (!ctx) {
  3912. throw std::runtime_error(format("failed to create context"));
  3913. }
  3914. ctx_map[it.first] = ctx;
  3915. model.ctxs.push_back(ctx);
  3916. }
  3917. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3918. // create tensors for the weights
  3919. {
  3920. const int64_t n_embd = hparams.n_embd;
  3921. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3922. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3923. const int64_t n_embd_gqa = n_embd_v_gqa;
  3924. const int64_t n_vocab = hparams.n_vocab;
  3925. const int64_t n_vocab_type = hparams.n_vocab_type;
  3926. const int64_t n_ff = hparams.n_ff;
  3927. const int64_t n_expert = hparams.n_expert;
  3928. if (n_expert > 0 && hparams.n_expert_used == 0) {
  3929. throw std::runtime_error("model has expert layers but no expert layers are used");
  3930. }
  3931. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3932. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3933. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3934. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3935. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3936. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3937. model.layers.resize(n_layer);
  3938. const auto tn = LLM_TN(model.arch);
  3939. switch (model.arch) {
  3940. case LLM_ARCH_LLAMA:
  3941. case LLM_ARCH_REFACT:
  3942. case LLM_ARCH_MINICPM:
  3943. {
  3944. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3945. // output
  3946. {
  3947. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3948. if (model.arch != LLM_ARCH_MINICPM){
  3949. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3950. // if output is NULL, init from the input tok embed
  3951. if (model.output == NULL) {
  3952. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3953. ml.n_created--; // artificial tensor
  3954. ml.size_data += ggml_nbytes(model.output);
  3955. }
  3956. }
  3957. }
  3958. for (int i = 0; i < n_layer; ++i) {
  3959. ggml_context * ctx_layer = ctx_for_layer(i);
  3960. ggml_context * ctx_split = ctx_for_layer_split(i);
  3961. auto & layer = model.layers[i];
  3962. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3963. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3964. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3965. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3966. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3967. // optional bias tensors
  3968. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3969. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3970. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3971. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3972. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3973. if (n_expert == 0) {
  3974. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3975. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3976. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3977. } else {
  3978. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  3979. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  3980. if (layer.ffn_gate_exps) {
  3981. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  3982. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  3983. } else {
  3984. // merge split expert into a single tensor for compatibility with older models
  3985. // requires disabling mmap
  3986. use_mmap_buffer = false;
  3987. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  3988. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  3989. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  3990. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  3991. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  3992. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  3993. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  3994. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  3995. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  3996. for (uint32_t x = 0; x < n_expert; ++x) {
  3997. // the individual experts are loaded into a view of the merged tensor
  3998. 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);
  3999. 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);
  4000. 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);
  4001. }
  4002. }
  4003. }
  4004. }
  4005. } break;
  4006. case LLM_ARCH_GROK:
  4007. {
  4008. if (n_expert == 0) {
  4009. throw std::runtime_error("Grok model cannot have zero experts");
  4010. }
  4011. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4012. // output
  4013. {
  4014. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4015. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4016. // if output is NULL, init from the input tok embed
  4017. if (model.output == NULL) {
  4018. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4019. ml.n_created--; // artificial tensor
  4020. ml.size_data += ggml_nbytes(model.output);
  4021. }
  4022. }
  4023. for (int i = 0; i < n_layer; ++i) {
  4024. ggml_context * ctx_layer = ctx_for_layer(i);
  4025. ggml_context * ctx_split = ctx_for_layer_split(i);
  4026. auto & layer = model.layers[i];
  4027. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4028. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4029. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4030. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4031. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4032. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4033. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4034. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4035. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4036. if (layer.ffn_gate_exps) {
  4037. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4038. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4039. } else {
  4040. // merge split expert into a single tensor for compatibility with older models
  4041. // requires disabling mmap
  4042. use_mmap_buffer = false;
  4043. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4044. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4045. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4046. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4047. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4048. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4049. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4050. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4051. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4052. for (uint32_t x = 0; x < n_expert; ++x) {
  4053. // the individual experts are loaded into a view of the merged tensor
  4054. 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);
  4055. 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);
  4056. 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);
  4057. }
  4058. }
  4059. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4060. }
  4061. } break;
  4062. case LLM_ARCH_BAICHUAN:
  4063. {
  4064. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4065. {
  4066. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4067. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4068. }
  4069. for (int i = 0; i < n_layer; ++i) {
  4070. ggml_context * ctx_layer = ctx_for_layer(i);
  4071. ggml_context * ctx_split = ctx_for_layer_split(i);
  4072. auto & layer = model.layers[i];
  4073. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4074. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4075. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4076. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4077. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4078. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4079. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4080. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4081. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4082. }
  4083. } break;
  4084. case LLM_ARCH_FALCON:
  4085. {
  4086. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4087. // output
  4088. {
  4089. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4090. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4091. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4092. if (!model.output) {
  4093. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4094. ml.n_created--; // artificial tensor
  4095. ml.size_data += ggml_nbytes(model.output);
  4096. }
  4097. }
  4098. for (int i = 0; i < n_layer; ++i) {
  4099. ggml_context * ctx_layer = ctx_for_layer(i);
  4100. ggml_context * ctx_split = ctx_for_layer_split(i);
  4101. auto & layer = model.layers[i];
  4102. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4103. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4104. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  4105. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  4106. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4107. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4108. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4109. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4110. }
  4111. } break;
  4112. case LLM_ARCH_STARCODER:
  4113. {
  4114. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4115. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4116. // output
  4117. {
  4118. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4119. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4120. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4121. }
  4122. for (int i = 0; i < n_layer; ++i) {
  4123. ggml_context * ctx_layer = ctx_for_layer(i);
  4124. ggml_context * ctx_split = ctx_for_layer_split(i);
  4125. auto & layer = model.layers[i];
  4126. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4127. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4128. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4129. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4130. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4131. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4132. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4133. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4134. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4135. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4136. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4137. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4138. }
  4139. } break;
  4140. case LLM_ARCH_PERSIMMON:
  4141. {
  4142. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4143. {
  4144. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4145. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4146. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4147. }
  4148. for (int i = 0; i < n_layer; ++i) {
  4149. ggml_context * ctx_layer = ctx_for_layer(i);
  4150. ggml_context * ctx_split = ctx_for_layer_split(i);
  4151. auto & layer = model.layers[i];
  4152. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4153. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4154. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4155. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4156. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4157. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4158. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4159. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4160. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4161. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4162. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4163. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4164. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4165. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4166. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4167. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4168. }
  4169. } break;
  4170. case LLM_ARCH_BERT:
  4171. case LLM_ARCH_NOMIC_BERT:
  4172. {
  4173. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4174. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4175. if (model.arch == LLM_ARCH_BERT) {
  4176. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4177. }
  4178. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4179. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4180. for (int i = 0; i < n_layer; ++i) {
  4181. ggml_context * ctx_layer = ctx_for_layer(i);
  4182. ggml_context * ctx_split = ctx_for_layer_split(i);
  4183. auto & layer = model.layers[i];
  4184. if (model.arch == LLM_ARCH_BERT) {
  4185. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4186. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4187. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4188. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4189. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4190. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4191. } else {
  4192. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4193. }
  4194. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4195. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4196. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4197. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4198. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4199. if (model.arch == LLM_ARCH_BERT) {
  4200. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4201. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4202. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4203. } else {
  4204. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4205. }
  4206. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4207. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4208. }
  4209. } break;
  4210. case LLM_ARCH_BLOOM:
  4211. {
  4212. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4213. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4214. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4215. // output
  4216. {
  4217. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4218. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4219. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4220. }
  4221. for (int i = 0; i < n_layer; ++i) {
  4222. ggml_context * ctx_layer = ctx_for_layer(i);
  4223. ggml_context * ctx_split = ctx_for_layer_split(i);
  4224. auto & layer = model.layers[i];
  4225. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4226. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4227. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4228. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4229. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4230. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4231. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4232. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4233. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4234. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4235. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4236. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4237. }
  4238. } break;
  4239. case LLM_ARCH_MPT:
  4240. {
  4241. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4242. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, false);
  4243. // output
  4244. {
  4245. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4246. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4247. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4248. if (!model.output) {
  4249. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4250. ml.n_created--; // artificial tensor
  4251. ml.size_data += ggml_nbytes(model.output);
  4252. }
  4253. }
  4254. for (int i = 0; i < n_layer; ++i) {
  4255. ggml_context * ctx_layer = ctx_for_layer(i);
  4256. ggml_context * ctx_split = ctx_for_layer_split(i);
  4257. auto & layer = model.layers[i];
  4258. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4259. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4260. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4261. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4262. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4263. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4264. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4265. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4266. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4267. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4268. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4269. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4270. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, false);
  4271. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, false);
  4272. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, false);
  4273. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, false);
  4274. // AWQ ScaleActivation layer
  4275. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4276. }
  4277. } break;
  4278. case LLM_ARCH_STABLELM:
  4279. {
  4280. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4281. // output
  4282. {
  4283. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4284. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4285. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4286. }
  4287. for (int i = 0; i < n_layer; ++i) {
  4288. ggml_context * ctx_layer = ctx_for_layer(i);
  4289. ggml_context * ctx_split = ctx_for_layer_split(i);
  4290. auto & layer = model.layers[i];
  4291. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4292. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4293. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4294. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4295. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4296. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4297. // optional bias tensors, present in Stable LM 2 1.6B
  4298. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4299. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4300. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4301. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4302. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4303. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4304. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4305. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4306. }
  4307. } break;
  4308. case LLM_ARCH_QWEN:
  4309. {
  4310. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4311. // output
  4312. {
  4313. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4314. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4315. }
  4316. for (int i = 0; i < n_layer; ++i) {
  4317. ggml_context * ctx_layer = ctx_for_layer(i);
  4318. ggml_context * ctx_split = ctx_for_layer_split(i);
  4319. auto & layer = model.layers[i];
  4320. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4321. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4322. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4323. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4324. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4325. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4326. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4327. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4328. }
  4329. } break;
  4330. case LLM_ARCH_QWEN2:
  4331. {
  4332. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4333. // output
  4334. {
  4335. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4336. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4337. }
  4338. for (int i = 0; i < n_layer; ++i) {
  4339. ggml_context * ctx_layer = ctx_for_layer(i);
  4340. ggml_context * ctx_split = ctx_for_layer_split(i);
  4341. auto & layer = model.layers[i];
  4342. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4343. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4344. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4345. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4346. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4347. // optional bias tensors
  4348. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4349. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4350. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4351. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4352. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4353. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4354. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4355. }
  4356. } break;
  4357. case LLM_ARCH_PHI2:
  4358. {
  4359. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4360. // output
  4361. {
  4362. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4363. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4364. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4365. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4366. }
  4367. for (int i = 0; i < n_layer; ++i) {
  4368. ggml_context * ctx_layer = ctx_for_layer(i);
  4369. ggml_context * ctx_split = ctx_for_layer_split(i);
  4370. auto & layer = model.layers[i];
  4371. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4372. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4373. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4374. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4375. if (layer.wqkv == nullptr) {
  4376. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4377. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4378. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4379. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4380. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4381. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4382. }
  4383. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4384. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4385. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4386. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4387. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4388. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4389. }
  4390. } break;
  4391. case LLM_ARCH_PLAMO:
  4392. {
  4393. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4394. // output
  4395. {
  4396. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4397. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4398. }
  4399. for (int i = 0; i < n_layer; ++i) {
  4400. ggml_context * ctx_layer = ctx_for_layer(i);
  4401. ggml_context * ctx_split = ctx_for_layer_split(i);
  4402. auto & layer = model.layers[i];
  4403. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4404. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4405. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4406. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4407. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4408. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4409. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4410. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4411. }
  4412. } break;
  4413. case LLM_ARCH_GPT2:
  4414. {
  4415. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4416. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4417. // output
  4418. {
  4419. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4420. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4421. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4422. }
  4423. for (int i = 0; i < n_layer; ++i) {
  4424. ggml_context * ctx_layer = ctx_for_layer(i);
  4425. ggml_context * ctx_split = ctx_for_layer_split(i);
  4426. auto & layer = model.layers[i];
  4427. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4428. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4429. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4430. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4431. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4432. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4433. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4434. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4435. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4436. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4437. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4438. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4439. }
  4440. } break;
  4441. case LLM_ARCH_CODESHELL:
  4442. {
  4443. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4444. // output
  4445. {
  4446. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4447. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4448. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4449. }
  4450. for (int i = 0; i < n_layer; ++i) {
  4451. ggml_context * ctx_layer = ctx_for_layer(i);
  4452. ggml_context * ctx_split = ctx_for_layer_split(i);
  4453. auto & layer = model.layers[i];
  4454. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4455. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4456. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4457. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4458. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4459. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4460. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4461. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4462. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4463. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4464. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4465. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4466. }
  4467. } break;
  4468. case LLM_ARCH_ORION:
  4469. {
  4470. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4471. {
  4472. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4473. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4474. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4475. }
  4476. for (int i = 0; i < n_layer; ++i) {
  4477. ggml_context * ctx_layer = ctx_for_layer(i);
  4478. ggml_context * ctx_split = ctx_for_layer_split(i);
  4479. auto & layer = model.layers[i];
  4480. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4481. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4482. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4483. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4484. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4485. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4486. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4487. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4488. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4489. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4490. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4491. }
  4492. } break;
  4493. case LLM_ARCH_INTERNLM2:
  4494. {
  4495. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4496. // output
  4497. {
  4498. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4499. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4500. }
  4501. for (int i = 0; i < n_layer; ++i) {
  4502. ggml_context * ctx_layer = ctx_for_layer(i);
  4503. ggml_context * ctx_split = ctx_for_layer_split(i);
  4504. auto & layer = model.layers[i];
  4505. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4506. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4507. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4508. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4509. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4510. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4511. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4512. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4513. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4514. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4515. }
  4516. } break;
  4517. case LLM_ARCH_GEMMA:
  4518. {
  4519. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4520. // output
  4521. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4522. 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
  4523. ml.n_created--; // artificial tensor
  4524. ml.size_data += ggml_nbytes(model.output);
  4525. const int64_t n_ff = hparams.n_ff;
  4526. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4527. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4528. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4529. for (uint32_t i = 0; i < n_layer; ++i) {
  4530. ggml_context * ctx_layer = ctx_for_layer(i);
  4531. ggml_context * ctx_split = ctx_for_layer_split(i);
  4532. auto & layer = model.layers[i];
  4533. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4534. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4535. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4536. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4537. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4538. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4539. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4540. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4541. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4542. }
  4543. } break;
  4544. case LLM_ARCH_STARCODER2:
  4545. {
  4546. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4547. // output
  4548. {
  4549. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4550. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4551. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4552. // if output is NULL, init from the input tok embed
  4553. if (model.output == NULL) {
  4554. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4555. ml.n_created--; // artificial tensor
  4556. ml.size_data += ggml_nbytes(model.output);
  4557. }
  4558. }
  4559. for (int i = 0; i < n_layer; ++i) {
  4560. ggml_context * ctx_layer = ctx_for_layer(i);
  4561. ggml_context * ctx_split = ctx_for_layer_split(i);
  4562. auto & layer = model.layers[i];
  4563. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4564. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4565. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4566. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4567. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4568. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4569. // optional bias tensors
  4570. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4571. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4572. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4573. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4574. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4575. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "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_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4578. // optional bias tensors
  4579. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4580. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4581. }
  4582. } break;
  4583. case LLM_ARCH_MAMBA:
  4584. {
  4585. const int64_t d_conv = hparams.ssm_d_conv;
  4586. const int64_t d_inner = hparams.ssm_d_inner;
  4587. const int64_t d_state = hparams.ssm_d_state;
  4588. const int64_t dt_rank = hparams.ssm_dt_rank;
  4589. // only an expansion factor of 2 is supported for now
  4590. GGML_ASSERT(2 * n_embd == d_inner);
  4591. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4592. // output
  4593. {
  4594. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4595. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4596. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4597. if (model.output == NULL) {
  4598. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4599. ml.n_created--; // artificial tensor
  4600. ml.size_data += ggml_nbytes(model.output);
  4601. }
  4602. }
  4603. for (int i = 0; i < n_layer; ++i) {
  4604. ggml_context * ctx_layer = ctx_for_layer(i);
  4605. ggml_context * ctx_split = ctx_for_layer_split(i);
  4606. auto & layer = model.layers[i];
  4607. // norm
  4608. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4609. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4610. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4611. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4612. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4613. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4614. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4615. // no "weight" suffix for these
  4616. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4617. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4618. // out_proj
  4619. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4620. }
  4621. } break;
  4622. case LLM_ARCH_XVERSE:
  4623. {
  4624. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4625. {
  4626. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4627. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4628. }
  4629. for (int i = 0; i < n_layer; ++i) {
  4630. ggml_context * ctx_layer = ctx_for_layer(i);
  4631. ggml_context * ctx_split = ctx_for_layer_split(i);
  4632. auto & layer = model.layers[i];
  4633. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4634. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4635. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4636. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4637. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4638. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4639. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4640. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4641. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4642. }
  4643. } break;
  4644. case LLM_ARCH_COMMAND_R:
  4645. {
  4646. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4647. // output
  4648. {
  4649. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4650. // init output from the input tok embed
  4651. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4652. ml.n_created--; // artificial tensor
  4653. ml.size_data += ggml_nbytes(model.output);
  4654. }
  4655. for (int i = 0; i < n_layer; ++i) {
  4656. ggml_context * ctx_layer = ctx_for_layer(i);
  4657. ggml_context * ctx_split = ctx_for_layer_split(i);
  4658. auto & layer = model.layers[i];
  4659. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4660. if (n_layer >= 64){
  4661. 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});
  4662. 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});
  4663. }
  4664. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4665. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4666. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4667. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4668. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4669. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4670. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4671. }
  4672. } break;
  4673. default:
  4674. throw std::runtime_error("unknown architecture");
  4675. }
  4676. }
  4677. ml.done_getting_tensors();
  4678. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  4679. model.mappings.reserve(ml.mappings.size());
  4680. // create the backend buffers
  4681. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4682. ctx_bufs.reserve(ctx_map.size());
  4683. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4684. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4685. model.bufs.reserve(n_max_backend_buffer);
  4686. for (auto & it : ctx_map) {
  4687. ggml_backend_buffer_type_t buft = it.first;
  4688. ggml_context * ctx = it.second;
  4689. llama_buf_map bufs;
  4690. bufs.reserve(n_max_backend_buffer);
  4691. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4692. // 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
  4693. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4694. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  4695. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4696. void * addr = nullptr;
  4697. size_t first, last;
  4698. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4699. if (first >= last) {
  4700. continue;
  4701. }
  4702. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4703. if (buf == nullptr) {
  4704. throw std::runtime_error("unable to allocate backend CPU buffer");
  4705. }
  4706. model.bufs.push_back(buf);
  4707. bufs.emplace(idx, buf);
  4708. #ifdef GGML_USE_CUDA
  4709. if (n_layer >= n_gpu_layers) {
  4710. ggml_backend_cuda_register_host_buffer(
  4711. ggml_backend_buffer_get_base(buf),
  4712. ggml_backend_buffer_get_size(buf));
  4713. }
  4714. #endif
  4715. }
  4716. }
  4717. #ifdef GGML_USE_METAL
  4718. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  4719. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4720. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4721. void * addr = nullptr;
  4722. size_t first, last;
  4723. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4724. if (first >= last) {
  4725. continue;
  4726. }
  4727. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4728. if (buf == nullptr) {
  4729. throw std::runtime_error("unable to allocate backend metal buffer");
  4730. }
  4731. model.bufs.push_back(buf);
  4732. bufs.emplace(idx, buf);
  4733. }
  4734. }
  4735. #endif
  4736. else {
  4737. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4738. if (buf == nullptr) {
  4739. throw std::runtime_error("unable to allocate backend buffer");
  4740. }
  4741. model.bufs.push_back(buf);
  4742. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4743. model.mlock_bufs.emplace_back(new llama_mlock);
  4744. auto & mlock_buf = model.mlock_bufs.back();
  4745. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4746. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4747. }
  4748. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4749. bufs.emplace(idx, buf);
  4750. }
  4751. }
  4752. if (bufs.empty()) {
  4753. throw std::runtime_error("failed to allocate buffer");
  4754. }
  4755. for (auto & buf : bufs) {
  4756. // indicate that this buffer contains weights
  4757. // 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
  4758. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4759. }
  4760. ctx_bufs.emplace_back(ctx, bufs);
  4761. }
  4762. if (llama_supports_gpu_offload()) {
  4763. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4764. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4765. if (n_gpu_layers > (int) hparams.n_layer) {
  4766. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4767. }
  4768. const int max_backend_supported_layers = hparams.n_layer + 1;
  4769. const int max_offloadable_layers = hparams.n_layer + 1;
  4770. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4771. }
  4772. // print memory requirements
  4773. for (ggml_backend_buffer_t buf : model.bufs) {
  4774. 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);
  4775. }
  4776. // populate tensors_by_name
  4777. for (ggml_context * ctx : model.ctxs) {
  4778. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4779. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4780. }
  4781. }
  4782. // load tensor data
  4783. for (auto & it : ctx_bufs) {
  4784. ggml_context * ctx = it.first;
  4785. auto & bufs = it.second;
  4786. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4787. return false;
  4788. }
  4789. }
  4790. if (use_mmap_buffer) {
  4791. for (auto & mapping : ml.mappings) {
  4792. model.mappings.emplace_back(std::move(mapping));
  4793. }
  4794. }
  4795. // loading time will be recalculate after the first eval, so
  4796. // we take page faults deferred by mmap() into consideration
  4797. model.t_load_us = ggml_time_us() - model.t_start_us;
  4798. return true;
  4799. }
  4800. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4801. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4802. try {
  4803. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4804. model.hparams.vocab_only = params.vocab_only;
  4805. try {
  4806. llm_load_arch(ml, model);
  4807. } catch(const std::exception & e) {
  4808. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4809. }
  4810. try {
  4811. llm_load_hparams(ml, model);
  4812. } catch(const std::exception & e) {
  4813. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4814. }
  4815. try {
  4816. llm_load_vocab(ml, model);
  4817. } catch(const std::exception & e) {
  4818. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4819. }
  4820. llm_load_print_meta(ml, model);
  4821. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4822. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4823. throw std::runtime_error("vocab size mismatch");
  4824. }
  4825. if (params.vocab_only) {
  4826. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4827. return 0;
  4828. }
  4829. #ifdef GGML_USE_KOMPUTE
  4830. if (params.n_gpu_layers > 0 && (
  4831. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4832. || !(
  4833. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4834. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4835. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4836. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4837. )
  4838. )) {
  4839. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4840. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4841. params.n_gpu_layers = 0;
  4842. }
  4843. #endif
  4844. #ifdef GGML_USE_SYCL
  4845. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4846. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4847. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4848. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4849. } else {
  4850. ggml_backend_sycl_set_mul_device_mode();
  4851. }
  4852. #endif
  4853. if (!llm_load_tensors(
  4854. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4855. params.progress_callback, params.progress_callback_user_data
  4856. )) {
  4857. return -2;
  4858. }
  4859. } catch (const std::exception & err) {
  4860. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4861. return -1;
  4862. }
  4863. return 0;
  4864. }
  4865. //
  4866. // llm_build
  4867. //
  4868. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4869. enum llm_ffn_op_type {
  4870. LLM_FFN_SILU,
  4871. LLM_FFN_GELU,
  4872. LLM_FFN_RELU,
  4873. LLM_FFN_RELU_SQR,
  4874. };
  4875. enum llm_ffn_gate_type {
  4876. LLM_FFN_SEQ,
  4877. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4878. };
  4879. enum llm_norm_type {
  4880. LLM_NORM,
  4881. LLM_NORM_RMS,
  4882. };
  4883. static struct ggml_tensor * llm_build_inp_embd(
  4884. struct ggml_context * ctx,
  4885. struct llama_context & lctx,
  4886. const llama_hparams & hparams,
  4887. const llama_batch & batch,
  4888. struct ggml_tensor * tok_embd,
  4889. const llm_build_cb & cb) {
  4890. const int64_t n_embd = hparams.n_embd;
  4891. struct ggml_tensor * inpL;
  4892. if (batch.token) {
  4893. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4894. cb(lctx.inp_tokens, "inp_tokens", -1);
  4895. ggml_set_input(lctx.inp_tokens);
  4896. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4897. } else {
  4898. #ifdef GGML_USE_MPI
  4899. GGML_ASSERT(false && "not implemented");
  4900. #endif
  4901. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4902. inpL = lctx.inp_embd;
  4903. ggml_set_input(lctx.inp_embd);
  4904. }
  4905. cb(inpL, "inp_embd", -1);
  4906. return inpL;
  4907. }
  4908. static void llm_build_kv_store(
  4909. struct ggml_context * ctx,
  4910. const llama_hparams & hparams,
  4911. const llama_kv_cache & kv,
  4912. struct ggml_cgraph * graph,
  4913. struct ggml_tensor * k_cur,
  4914. struct ggml_tensor * v_cur,
  4915. int64_t n_ctx,
  4916. int32_t n_tokens,
  4917. int32_t kv_head,
  4918. const llm_build_cb & cb,
  4919. int64_t il) {
  4920. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4921. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4922. GGML_ASSERT(kv.size == n_ctx);
  4923. // compute the transposed [n_tokens, n_embd] V matrix
  4924. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  4925. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur);
  4926. cb(v_cur_t, "v_cur_t", il);
  4927. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4928. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4929. cb(k_cache_view, "k_cache_view", il);
  4930. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4931. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4932. (kv_head)*ggml_element_size(kv.v_l[il]));
  4933. cb(v_cache_view, "v_cache_view", il);
  4934. // important: storing RoPE-ed version of K in the KV cache!
  4935. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4936. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4937. }
  4938. static struct ggml_tensor * llm_build_norm(
  4939. struct ggml_context * ctx,
  4940. struct ggml_tensor * cur,
  4941. const llama_hparams & hparams,
  4942. struct ggml_tensor * mw,
  4943. struct ggml_tensor * mb,
  4944. llm_norm_type type,
  4945. const llm_build_cb & cb,
  4946. int il) {
  4947. switch (type) {
  4948. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4949. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4950. }
  4951. if (mw || mb) {
  4952. cb(cur, "norm", il);
  4953. }
  4954. if (mw) {
  4955. cur = ggml_mul(ctx, cur, mw);
  4956. if (mb) {
  4957. cb(cur, "norm_w", il);
  4958. }
  4959. }
  4960. if (mb) {
  4961. cur = ggml_add(ctx, cur, mb);
  4962. }
  4963. return cur;
  4964. }
  4965. static struct ggml_tensor * llm_build_ffn(
  4966. struct ggml_context * ctx,
  4967. struct ggml_tensor * cur,
  4968. struct ggml_tensor * up,
  4969. struct ggml_tensor * up_b,
  4970. struct ggml_tensor * gate,
  4971. struct ggml_tensor * gate_b,
  4972. struct ggml_tensor * down,
  4973. struct ggml_tensor * down_b,
  4974. struct ggml_tensor * act_scales,
  4975. llm_ffn_op_type type_op,
  4976. llm_ffn_gate_type type_gate,
  4977. const llm_build_cb & cb,
  4978. int il) {
  4979. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4980. cb(tmp, "ffn_up", il);
  4981. if (up_b) {
  4982. tmp = ggml_add(ctx, tmp, up_b);
  4983. cb(tmp, "ffn_up_b", il);
  4984. }
  4985. if (gate) {
  4986. switch (type_gate) {
  4987. case LLM_FFN_SEQ:
  4988. {
  4989. cur = ggml_mul_mat(ctx, gate, tmp);
  4990. cb(cur, "ffn_gate", il);
  4991. } break;
  4992. case LLM_FFN_PAR:
  4993. {
  4994. cur = ggml_mul_mat(ctx, gate, cur);
  4995. cb(cur, "ffn_gate", il);
  4996. } break;
  4997. }
  4998. if (gate_b) {
  4999. cur = ggml_add(ctx, cur, gate_b);
  5000. cb(cur, "ffn_gate_b", il);
  5001. }
  5002. } else {
  5003. cur = tmp;
  5004. }
  5005. switch (type_op) {
  5006. case LLM_FFN_SILU:
  5007. {
  5008. cur = ggml_silu(ctx, cur);
  5009. cb(cur, "ffn_silu", il);
  5010. } break;
  5011. case LLM_FFN_GELU:
  5012. {
  5013. cur = ggml_gelu(ctx, cur);
  5014. cb(cur, "ffn_gelu", il);
  5015. if (act_scales != NULL) {
  5016. cur = ggml_div(ctx, cur, act_scales);
  5017. cb(cur, "ffn_act", il);
  5018. }
  5019. } break;
  5020. case LLM_FFN_RELU:
  5021. {
  5022. cur = ggml_relu(ctx, cur);
  5023. cb(cur, "ffn_relu", il);
  5024. } break;
  5025. case LLM_FFN_RELU_SQR:
  5026. {
  5027. cur = ggml_relu(ctx, cur);
  5028. cb(cur, "ffn_relu", il);
  5029. cur = ggml_sqr(ctx, cur);
  5030. cb(cur, "ffn_sqr(relu)", il);
  5031. } break;
  5032. }
  5033. if (type_gate == LLM_FFN_PAR) {
  5034. cur = ggml_mul(ctx, cur, tmp);
  5035. cb(cur, "ffn_gate_par", il);
  5036. }
  5037. cur = ggml_mul_mat(ctx, down, cur);
  5038. if (down_b) {
  5039. cb(cur, "ffn_down", il);
  5040. }
  5041. if (down_b) {
  5042. cur = ggml_add(ctx, cur, down_b);
  5043. }
  5044. return cur;
  5045. }
  5046. // if max_alibi_bias > 0 then apply ALiBi
  5047. static struct ggml_tensor * llm_build_kqv(
  5048. struct ggml_context * ctx,
  5049. const llama_model & model,
  5050. const llama_hparams & hparams,
  5051. const llama_kv_cache & kv,
  5052. struct ggml_cgraph * graph,
  5053. struct ggml_tensor * wo,
  5054. struct ggml_tensor * wo_b,
  5055. struct ggml_tensor * q_cur,
  5056. struct ggml_tensor * kq_mask,
  5057. struct ggml_tensor * kq_pos,
  5058. int64_t n_ctx,
  5059. int32_t n_tokens,
  5060. int32_t n_kv,
  5061. float kq_scale,
  5062. const llm_build_cb & cb,
  5063. int il) {
  5064. const int64_t n_head = hparams.n_head;
  5065. const int64_t n_head_kv = hparams.n_head_kv;
  5066. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5067. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5068. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5069. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  5070. cb(q, "q", il);
  5071. struct ggml_tensor * k =
  5072. ggml_view_3d(ctx, kv.k_l[il],
  5073. n_embd_head_k, n_kv, n_head_kv,
  5074. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  5075. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  5076. 0);
  5077. cb(k, "k", il);
  5078. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  5079. cb(kq, "kq", il);
  5080. if (model.arch == LLM_ARCH_PHI2) {
  5081. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  5082. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  5083. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5084. }
  5085. if (model.arch == LLM_ARCH_GROK) {
  5086. // need to do the following:
  5087. // multiply by attn_output_multiplyer of 0.08838834764831845
  5088. // and then :
  5089. // kq = 30 * tanh(kq / 30)
  5090. // before the softmax below
  5091. //try from phi2
  5092. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5093. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  5094. kq = ggml_scale(ctx, kq, 30);
  5095. }
  5096. #if defined(GGML_USE_KOMPUTE)
  5097. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  5098. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  5099. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  5100. if (hparams.f_max_alibi_bias > 0.0f) {
  5101. kq = ggml_scale(ctx, kq, kq_scale);
  5102. cb(kq, "kq_scaled", il);
  5103. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  5104. cb(kq, "kq_scaled_alibi", il);
  5105. kq = ggml_add(ctx, kq, kq_mask);
  5106. cb(kq, "kq_masked", il);
  5107. kq = ggml_soft_max(ctx, kq);
  5108. cb(kq, "kq_soft_max", il);
  5109. } else
  5110. #endif
  5111. {
  5112. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  5113. cb(kq, "kq_soft_max_ext", il);
  5114. }
  5115. GGML_ASSERT(kv.size == n_ctx);
  5116. // split cached v into n_head heads
  5117. struct ggml_tensor * v =
  5118. ggml_view_3d(ctx, kv.v_l[il],
  5119. n_kv, n_embd_head_v, n_head_kv,
  5120. ggml_element_size(kv.v_l[il])*n_ctx,
  5121. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  5122. 0);
  5123. cb(v, "v", il);
  5124. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  5125. cb(kqv, "kqv", il);
  5126. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  5127. cb(kqv_merged, "kqv_merged", il);
  5128. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  5129. cb(cur, "kqv_merged_cont", il);
  5130. ggml_build_forward_expand(graph, cur);
  5131. cur = ggml_mul_mat(ctx, wo, cur);
  5132. if (wo_b) {
  5133. cb(cur, "kqv_wo", il);
  5134. }
  5135. if (wo_b) {
  5136. cur = ggml_add(ctx, cur, wo_b);
  5137. }
  5138. return cur;
  5139. }
  5140. static struct ggml_tensor * llm_build_kv(
  5141. struct ggml_context * ctx,
  5142. const llama_model & model,
  5143. const llama_hparams & hparams,
  5144. const llama_kv_cache & kv,
  5145. struct ggml_cgraph * graph,
  5146. struct ggml_tensor * wo,
  5147. struct ggml_tensor * wo_b,
  5148. struct ggml_tensor * k_cur,
  5149. struct ggml_tensor * v_cur,
  5150. struct ggml_tensor * q_cur,
  5151. struct ggml_tensor * kq_mask,
  5152. struct ggml_tensor * kq_pos,
  5153. int64_t n_ctx,
  5154. int32_t n_tokens,
  5155. int32_t kv_head,
  5156. int32_t n_kv,
  5157. float kq_scale,
  5158. const llm_build_cb & cb,
  5159. int il) {
  5160. // these nodes are added to the graph together so that they are not reordered
  5161. // by doing so, the number of splits in the graph is reduced
  5162. ggml_build_forward_expand(graph, q_cur);
  5163. ggml_build_forward_expand(graph, k_cur);
  5164. ggml_build_forward_expand(graph, v_cur);
  5165. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  5166. struct ggml_tensor * cur;
  5167. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  5168. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  5169. cb(cur, "kqv_out", il);
  5170. return cur;
  5171. }
  5172. struct llm_build_context {
  5173. const llama_model & model;
  5174. llama_context & lctx;
  5175. const llama_hparams & hparams;
  5176. const llama_cparams & cparams;
  5177. const llama_batch & batch;
  5178. const llama_kv_cache & kv_self;
  5179. const int64_t n_embd;
  5180. const int64_t n_layer;
  5181. const int64_t n_rot;
  5182. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5183. const int64_t n_head;
  5184. const int64_t n_head_kv;
  5185. const int64_t n_embd_head_k;
  5186. const int64_t n_embd_k_gqa;
  5187. const int64_t n_embd_head_v;
  5188. const int64_t n_embd_v_gqa;
  5189. const int64_t n_expert;
  5190. const int64_t n_expert_used;
  5191. const float freq_base;
  5192. const float freq_scale;
  5193. const float ext_factor;
  5194. const float attn_factor;
  5195. const float beta_fast;
  5196. const float beta_slow;
  5197. const float norm_eps;
  5198. const float norm_rms_eps;
  5199. const int32_t n_tokens;
  5200. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5201. const int32_t n_outputs;
  5202. const int32_t kv_head; // index of where we store new KV data in the cache
  5203. const int32_t n_orig_ctx;
  5204. const enum llama_pooling_type pooling_type;
  5205. const enum llama_rope_type rope_type;
  5206. const llm_build_cb & cb;
  5207. std::vector<uint8_t> & buf_compute_meta;
  5208. struct ggml_context * ctx0 = nullptr;
  5209. // TODO: consider making the entire interface noexcept
  5210. llm_build_context(
  5211. llama_context & lctx,
  5212. const llama_batch & batch,
  5213. const llm_build_cb & cb,
  5214. bool worst_case) :
  5215. model (lctx.model),
  5216. lctx (lctx),
  5217. hparams (model.hparams),
  5218. cparams (lctx.cparams),
  5219. batch (batch),
  5220. kv_self (lctx.kv_self),
  5221. n_embd (hparams.n_embd),
  5222. n_layer (hparams.n_layer),
  5223. n_rot (hparams.n_rot),
  5224. n_ctx (cparams.n_ctx),
  5225. n_head (hparams.n_head),
  5226. n_head_kv (hparams.n_head_kv),
  5227. n_embd_head_k (hparams.n_embd_head_k),
  5228. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5229. n_embd_head_v (hparams.n_embd_head_v),
  5230. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5231. n_expert (hparams.n_expert),
  5232. n_expert_used (hparams.n_expert_used),
  5233. freq_base (cparams.rope_freq_base),
  5234. freq_scale (cparams.rope_freq_scale),
  5235. ext_factor (cparams.yarn_ext_factor),
  5236. attn_factor (cparams.yarn_attn_factor),
  5237. beta_fast (cparams.yarn_beta_fast),
  5238. beta_slow (cparams.yarn_beta_slow),
  5239. norm_eps (hparams.f_norm_eps),
  5240. norm_rms_eps (hparams.f_norm_rms_eps),
  5241. n_tokens (batch.n_tokens),
  5242. n_kv (worst_case ? kv_self.size : kv_self.n),
  5243. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5244. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5245. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5246. pooling_type (cparams.pooling_type),
  5247. rope_type (hparams.rope_type),
  5248. cb (cb),
  5249. buf_compute_meta (lctx.buf_compute_meta) {
  5250. // all initializations should be done in init()
  5251. }
  5252. void init() {
  5253. struct ggml_init_params params = {
  5254. /*.mem_size =*/ buf_compute_meta.size(),
  5255. /*.mem_buffer =*/ buf_compute_meta.data(),
  5256. /*.no_alloc =*/ true,
  5257. };
  5258. ctx0 = ggml_init(params);
  5259. lctx.inp_tokens = nullptr;
  5260. lctx.inp_embd = nullptr;
  5261. lctx.inp_pos = nullptr;
  5262. lctx.inp_out_ids = nullptr;
  5263. lctx.inp_KQ_mask = nullptr;
  5264. lctx.inp_KQ_pos = nullptr;
  5265. lctx.inp_K_shift = nullptr;
  5266. lctx.inp_mean = nullptr;
  5267. lctx.inp_cls = nullptr;
  5268. lctx.inp_s_copy = nullptr;
  5269. lctx.inp_s_mask = nullptr;
  5270. lctx.inp_s_seq = nullptr;
  5271. }
  5272. void free() {
  5273. if (ctx0) {
  5274. ggml_free(ctx0);
  5275. ctx0 = nullptr;
  5276. }
  5277. }
  5278. struct ggml_cgraph * build_k_shift() {
  5279. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5280. GGML_ASSERT(kv_self.size == n_ctx);
  5281. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5282. cb(lctx.inp_K_shift, "K_shift", -1);
  5283. ggml_set_input(lctx.inp_K_shift);
  5284. for (int il = 0; il < n_layer; ++il) {
  5285. struct ggml_tensor * tmp =
  5286. // we rotate only the first n_rot dimensions
  5287. ggml_rope_custom_inplace(ctx0,
  5288. ggml_view_3d(ctx0, kv_self.k_l[il],
  5289. n_embd_head_k, n_head_kv, n_ctx,
  5290. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5291. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5292. 0),
  5293. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5294. ext_factor, attn_factor, beta_fast, beta_slow);
  5295. cb(tmp, "K_shifted", il);
  5296. ggml_build_forward_expand(gf, tmp);
  5297. }
  5298. return gf;
  5299. }
  5300. struct ggml_cgraph * build_s_copy() {
  5301. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5302. GGML_ASSERT(kv_self.recurrent);
  5303. struct ggml_tensor * state_copy = build_inp_s_copy();
  5304. for (int il = 0; il < n_layer; ++il) {
  5305. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5306. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5307. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5308. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5309. // TODO: name the intermediate tensors with cb()
  5310. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5311. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5312. }
  5313. return gf;
  5314. }
  5315. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5316. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5317. for (uint32_t i = 0; i < ids.size(); ++i) {
  5318. const uint32_t id = ids[i];
  5319. if (i == id || id == ids.size()) {
  5320. continue;
  5321. }
  5322. uint32_t nm = 1;
  5323. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5324. nm++;
  5325. }
  5326. for (int il = 0; il < n_layer; ++il) {
  5327. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5328. n_embd_k_gqa, nm,
  5329. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5330. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5331. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5332. n_embd_k_gqa, nm,
  5333. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5334. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5335. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5336. nm, n_embd_v_gqa,
  5337. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5338. ggml_row_size(kv_self.v_l[il]->type, i));
  5339. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5340. nm, n_embd_v_gqa,
  5341. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5342. ggml_row_size(kv_self.v_l[il]->type, id));
  5343. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5344. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5345. }
  5346. i += nm - 1;
  5347. }
  5348. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5349. return gf;
  5350. }
  5351. struct ggml_tensor * build_inp_pos() {
  5352. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5353. cb(lctx.inp_pos, "inp_pos", -1);
  5354. ggml_set_input(lctx.inp_pos);
  5355. return lctx.inp_pos;
  5356. }
  5357. struct ggml_tensor * build_inp_out_ids() {
  5358. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5359. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5360. ggml_set_input(lctx.inp_out_ids);
  5361. return lctx.inp_out_ids;
  5362. }
  5363. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5364. if (causal) {
  5365. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5366. } else {
  5367. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5368. }
  5369. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5370. ggml_set_input(lctx.inp_KQ_mask);
  5371. return lctx.inp_KQ_mask;
  5372. }
  5373. struct ggml_tensor * build_inp_KQ_pos() {
  5374. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5375. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5376. ggml_set_input(lctx.inp_KQ_pos);
  5377. return lctx.inp_KQ_pos;
  5378. }
  5379. struct ggml_tensor * build_inp_mean() {
  5380. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5381. cb(lctx.inp_mean, "inp_mean", -1);
  5382. ggml_set_input(lctx.inp_mean);
  5383. return lctx.inp_mean;
  5384. }
  5385. struct ggml_tensor * build_inp_cls() {
  5386. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5387. cb(lctx.inp_cls, "inp_cls", -1);
  5388. ggml_set_input(lctx.inp_cls);
  5389. return lctx.inp_cls;
  5390. }
  5391. struct ggml_tensor * build_inp_s_copy() {
  5392. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5393. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5394. ggml_set_input(lctx.inp_s_copy);
  5395. return lctx.inp_s_copy;
  5396. }
  5397. struct ggml_tensor * build_inp_s_mask() {
  5398. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5399. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5400. ggml_set_input(lctx.inp_s_mask);
  5401. return lctx.inp_s_mask;
  5402. }
  5403. struct ggml_tensor * build_inp_s_seq() {
  5404. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5405. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5406. ggml_set_input(lctx.inp_s_seq);
  5407. return lctx.inp_s_seq;
  5408. }
  5409. struct ggml_cgraph * build_llama() {
  5410. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5411. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5412. int32_t n_tokens = this->n_tokens;
  5413. const int64_t n_embd_head = hparams.n_embd_head_v;
  5414. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5415. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5416. struct ggml_tensor * cur;
  5417. struct ggml_tensor * inpL;
  5418. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5419. // inp_pos - contains the positions
  5420. struct ggml_tensor * inp_pos = build_inp_pos();
  5421. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5422. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5423. for (int il = 0; il < n_layer; ++il) {
  5424. struct ggml_tensor * inpSA = inpL;
  5425. // norm
  5426. cur = llm_build_norm(ctx0, inpL, hparams,
  5427. model.layers[il].attn_norm, NULL,
  5428. LLM_NORM_RMS, cb, il);
  5429. cb(cur, "attn_norm", il);
  5430. // self-attention
  5431. {
  5432. // compute Q and K and RoPE them
  5433. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5434. cb(Qcur, "Qcur", il);
  5435. if (model.layers[il].bq) {
  5436. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5437. cb(Qcur, "Qcur", il);
  5438. }
  5439. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5440. cb(Kcur, "Kcur", il);
  5441. if (model.layers[il].bk) {
  5442. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5443. cb(Kcur, "Kcur", il);
  5444. }
  5445. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5446. cb(Vcur, "Vcur", il);
  5447. if (model.layers[il].bv) {
  5448. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5449. cb(Vcur, "Vcur", il);
  5450. }
  5451. Qcur = ggml_rope_custom(
  5452. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5453. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5454. ext_factor, attn_factor, beta_fast, beta_slow
  5455. );
  5456. cb(Qcur, "Qcur", il);
  5457. Kcur = ggml_rope_custom(
  5458. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5459. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5460. ext_factor, attn_factor, beta_fast, beta_slow
  5461. );
  5462. cb(Kcur, "Kcur", il);
  5463. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5464. model.layers[il].wo, model.layers[il].bo,
  5465. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5466. }
  5467. if (il == n_layer - 1) {
  5468. // skip computing output for unused tokens
  5469. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5470. n_tokens = n_outputs;
  5471. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5472. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5473. }
  5474. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5475. cb(ffn_inp, "ffn_inp", il);
  5476. // feed-forward network
  5477. if (model.layers[il].ffn_gate_inp == nullptr) {
  5478. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5479. model.layers[il].ffn_norm, NULL,
  5480. LLM_NORM_RMS, cb, il);
  5481. cb(cur, "ffn_norm", il);
  5482. cur = llm_build_ffn(ctx0, cur,
  5483. model.layers[il].ffn_up, NULL,
  5484. model.layers[il].ffn_gate, NULL,
  5485. model.layers[il].ffn_down, NULL,
  5486. NULL,
  5487. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5488. cb(cur, "ffn_out", il);
  5489. } else {
  5490. // MoE branch
  5491. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5492. model.layers[il].ffn_norm, NULL,
  5493. LLM_NORM_RMS, cb, il);
  5494. cb(cur, "ffn_norm", il);
  5495. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5496. cb(logits, "ffn_moe_logits", il);
  5497. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5498. cb(probs, "ffn_moe_probs", il);
  5499. // select experts
  5500. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5501. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5502. ggml_tensor * weights = ggml_get_rows(ctx0,
  5503. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5504. cb(weights, "ffn_moe_weights", il);
  5505. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5506. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5507. cb(weights_sum, "ffn_moe_weights_sum", il);
  5508. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5509. cb(weights, "ffn_moe_weights_norm", il);
  5510. // compute expert outputs
  5511. ggml_tensor * moe_out = nullptr;
  5512. for (int i = 0; i < n_expert_used; ++i) {
  5513. ggml_tensor * cur_expert;
  5514. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exps, selected_experts, i, cur);
  5515. cb(cur_up, "ffn_moe_up", il);
  5516. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exps, selected_experts, i, cur);
  5517. cb(cur_gate, "ffn_moe_gate", il);
  5518. cur_gate = ggml_silu(ctx0, cur_gate);
  5519. cb(cur_gate, "ffn_moe_silu", il);
  5520. cur_expert = ggml_mul(ctx0, cur_up, cur_gate);
  5521. cb(cur_expert, "ffn_moe_gate_par", il);
  5522. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exps, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5523. cb(cur_expert, "ffn_moe_down", il);
  5524. cur_expert = ggml_mul(ctx0, cur_expert,
  5525. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5526. cb(cur_expert, "ffn_moe_weighted", il);
  5527. if (i == 0) {
  5528. moe_out = cur_expert;
  5529. } else {
  5530. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5531. cb(moe_out, "ffn_moe_out", il);
  5532. }
  5533. }
  5534. cur = moe_out;
  5535. }
  5536. cur = ggml_add(ctx0, cur, ffn_inp);
  5537. cb(cur, "ffn_out", il);
  5538. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5539. if (layer_dir != nullptr) {
  5540. cur = ggml_add(ctx0, cur, layer_dir);
  5541. }
  5542. cb(cur, "l_out", il);
  5543. // input for next layer
  5544. inpL = cur;
  5545. }
  5546. cur = inpL;
  5547. cur = llm_build_norm(ctx0, cur, hparams,
  5548. model.output_norm, NULL,
  5549. LLM_NORM_RMS, cb, -1);
  5550. cb(cur, "result_norm", -1);
  5551. // lm_head
  5552. cur = ggml_mul_mat(ctx0, model.output, cur);
  5553. cb(cur, "result_output", -1);
  5554. ggml_build_forward_expand(gf, cur);
  5555. return gf;
  5556. }
  5557. struct ggml_cgraph * build_baichuan() {
  5558. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5559. const int64_t n_embd_head = hparams.n_embd_head_v;
  5560. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5561. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5562. struct ggml_tensor * cur;
  5563. struct ggml_tensor * inpL;
  5564. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5565. // inp_pos - contains the positions
  5566. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5567. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5568. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5569. // positions of the tokens in the KV cache
  5570. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5571. for (int il = 0; il < n_layer; ++il) {
  5572. struct ggml_tensor * inpSA = inpL;
  5573. cur = llm_build_norm(ctx0, inpL, hparams,
  5574. model.layers[il].attn_norm, NULL,
  5575. LLM_NORM_RMS, cb, il);
  5576. cb(cur, "attn_norm", il);
  5577. // self-attention
  5578. {
  5579. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5580. cb(Qcur, "Qcur", il);
  5581. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5582. cb(Kcur, "Kcur", il);
  5583. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5584. cb(Vcur, "Vcur", il);
  5585. switch (model.type) {
  5586. case MODEL_7B:
  5587. Qcur = ggml_rope_custom(
  5588. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5589. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5590. ext_factor, attn_factor, beta_fast, beta_slow
  5591. );
  5592. Kcur = ggml_rope_custom(
  5593. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5594. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5595. ext_factor, attn_factor, beta_fast, beta_slow
  5596. );
  5597. break;
  5598. case MODEL_13B:
  5599. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5600. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5601. break;
  5602. default:
  5603. GGML_ASSERT(false);
  5604. }
  5605. cb(Qcur, "Qcur", il);
  5606. cb(Kcur, "Kcur", il);
  5607. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5608. model.layers[il].wo, NULL,
  5609. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5610. }
  5611. if (il == n_layer - 1) {
  5612. // skip computing output for unused tokens
  5613. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5614. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5615. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5616. }
  5617. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5618. cb(ffn_inp, "ffn_inp", il);
  5619. // feed-forward network
  5620. {
  5621. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5622. model.layers[il].ffn_norm, NULL,
  5623. LLM_NORM_RMS, cb, il);
  5624. cb(cur, "ffn_norm", il);
  5625. cur = llm_build_ffn(ctx0, cur,
  5626. model.layers[il].ffn_up, NULL,
  5627. model.layers[il].ffn_gate, NULL,
  5628. model.layers[il].ffn_down, NULL,
  5629. NULL,
  5630. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5631. cb(cur, "ffn_out", il);
  5632. }
  5633. cur = ggml_add(ctx0, cur, ffn_inp);
  5634. cb(cur, "l_out", il);
  5635. // input for next layer
  5636. inpL = cur;
  5637. }
  5638. cur = inpL;
  5639. cur = llm_build_norm(ctx0, cur, hparams,
  5640. model.output_norm, NULL,
  5641. LLM_NORM_RMS, cb, -1);
  5642. cb(cur, "result_norm", -1);
  5643. // lm_head
  5644. cur = ggml_mul_mat(ctx0, model.output, cur);
  5645. cb(cur, "result_output", -1);
  5646. ggml_build_forward_expand(gf, cur);
  5647. return gf;
  5648. }
  5649. struct ggml_cgraph * build_xverse() {
  5650. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5651. const int64_t n_embd_head = hparams.n_embd_head_v;
  5652. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5653. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5654. struct ggml_tensor * cur;
  5655. struct ggml_tensor * inpL;
  5656. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5657. // inp_pos - contains the positions
  5658. struct ggml_tensor * inp_pos = build_inp_pos();
  5659. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5660. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5661. // positions of the tokens in the KV cache
  5662. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5663. for (int il = 0; il < n_layer; ++il) {
  5664. struct ggml_tensor * inpSA = inpL;
  5665. cur = llm_build_norm(ctx0, inpL, hparams,
  5666. model.layers[il].attn_norm, NULL,
  5667. LLM_NORM_RMS, cb, il);
  5668. cb(cur, "attn_norm", il);
  5669. // self-attention
  5670. {
  5671. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5672. cb(Qcur, "Qcur", il);
  5673. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5674. cb(Kcur, "Kcur", il);
  5675. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5676. cb(Vcur, "Vcur", il);
  5677. Qcur = ggml_rope_custom(
  5678. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5679. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5680. ext_factor, attn_factor, beta_fast, beta_slow
  5681. );
  5682. cb(Qcur, "Qcur", il);
  5683. Kcur = ggml_rope_custom(
  5684. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5685. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5686. ext_factor, attn_factor, beta_fast, beta_slow
  5687. );
  5688. cb(Kcur, "Kcur", il);
  5689. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5690. model.layers[il].wo, NULL,
  5691. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5692. }
  5693. if (il == n_layer - 1) {
  5694. // skip computing output for unused tokens
  5695. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5696. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5697. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5698. }
  5699. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5700. cb(ffn_inp, "ffn_inp", il);
  5701. // feed-forward network
  5702. {
  5703. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5704. model.layers[il].ffn_norm, NULL,
  5705. LLM_NORM_RMS, cb, il);
  5706. cb(cur, "ffn_norm", il);
  5707. cur = llm_build_ffn(ctx0, cur,
  5708. model.layers[il].ffn_up, NULL,
  5709. model.layers[il].ffn_gate, NULL,
  5710. model.layers[il].ffn_down, NULL,
  5711. NULL,
  5712. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5713. cb(cur, "ffn_out", il);
  5714. }
  5715. cur = ggml_add(ctx0, cur, ffn_inp);
  5716. cb(cur, "l_out", il);
  5717. // input for next layer
  5718. inpL = cur;
  5719. }
  5720. cur = inpL;
  5721. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  5722. cb(cur, "result_norm", -1);
  5723. // lm_head
  5724. cur = ggml_mul_mat(ctx0, model.output, cur);
  5725. cb(cur, "result_output", -1);
  5726. ggml_build_forward_expand(gf, cur);
  5727. return gf;
  5728. }
  5729. struct ggml_cgraph * build_falcon() {
  5730. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5731. const int64_t n_embd_head = hparams.n_embd_head_v;
  5732. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5733. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5734. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5735. struct ggml_tensor * cur;
  5736. struct ggml_tensor * inpL;
  5737. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5738. // inp_pos - contains the positions
  5739. struct ggml_tensor * inp_pos = build_inp_pos();
  5740. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5741. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5742. for (int il = 0; il < n_layer; ++il) {
  5743. struct ggml_tensor * attn_norm;
  5744. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5745. model.layers[il].attn_norm,
  5746. model.layers[il].attn_norm_b,
  5747. LLM_NORM, cb, il);
  5748. cb(attn_norm, "attn_norm", il);
  5749. // self-attention
  5750. {
  5751. if (model.layers[il].attn_norm_2) {
  5752. // Falcon-40B
  5753. cur = llm_build_norm(ctx0, inpL, hparams,
  5754. model.layers[il].attn_norm_2,
  5755. model.layers[il].attn_norm_2_b,
  5756. LLM_NORM, cb, il);
  5757. cb(cur, "attn_norm_2", il);
  5758. } else {
  5759. cur = attn_norm;
  5760. }
  5761. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5762. cb(cur, "wqkv", il);
  5763. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5764. 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)));
  5765. 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)));
  5766. cb(Qcur, "Qcur", il);
  5767. cb(Kcur, "Kcur", il);
  5768. cb(Vcur, "Vcur", il);
  5769. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5770. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5771. // using mode = 2 for neox mode
  5772. Qcur = ggml_rope_custom(
  5773. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5774. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5775. );
  5776. cb(Qcur, "Qcur", il);
  5777. Kcur = ggml_rope_custom(
  5778. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5779. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5780. );
  5781. cb(Kcur, "Kcur", il);
  5782. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5783. model.layers[il].wo, NULL,
  5784. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5785. }
  5786. if (il == n_layer - 1) {
  5787. // skip computing output for unused tokens
  5788. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5789. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5790. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5791. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5792. }
  5793. struct ggml_tensor * ffn_inp = cur;
  5794. // feed forward
  5795. {
  5796. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5797. model.layers[il].ffn_up, NULL,
  5798. NULL, NULL,
  5799. model.layers[il].ffn_down, NULL,
  5800. NULL,
  5801. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5802. cb(cur, "ffn_out", il);
  5803. }
  5804. cur = ggml_add(ctx0, cur, ffn_inp);
  5805. cb(cur, "l_out", il);
  5806. cur = ggml_add(ctx0, cur, inpL);
  5807. cb(cur, "l_out", il);
  5808. // input for next layer
  5809. inpL = cur;
  5810. }
  5811. cur = inpL;
  5812. // norm
  5813. cur = llm_build_norm(ctx0, cur, hparams,
  5814. model.output_norm,
  5815. model.output_norm_b,
  5816. LLM_NORM, cb, -1);
  5817. cb(cur, "result_norm", -1);
  5818. cur = ggml_mul_mat(ctx0, model.output, cur);
  5819. cb(cur, "result_output", -1);
  5820. ggml_build_forward_expand(gf, cur);
  5821. return gf;
  5822. }
  5823. struct ggml_cgraph * build_grok() {
  5824. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5825. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5826. int32_t n_tokens = this->n_tokens;
  5827. const int64_t n_embd_head = hparams.n_embd_head_v;
  5828. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5829. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5830. struct ggml_tensor * cur;
  5831. struct ggml_tensor * inpL;
  5832. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5833. // multiply by embedding_multiplier_scale of 78.38367176906169
  5834. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5835. // inp_pos - contains the positions
  5836. struct ggml_tensor * inp_pos = build_inp_pos();
  5837. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5838. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5839. for (int il = 0; il < n_layer; ++il) {
  5840. struct ggml_tensor * inpSA = inpL;
  5841. // norm
  5842. cur = llm_build_norm(ctx0, inpL, hparams,
  5843. model.layers[il].attn_norm, NULL,
  5844. LLM_NORM_RMS, cb, il);
  5845. cb(cur, "attn_norm", il);
  5846. // self-attention
  5847. {
  5848. // compute Q and K and RoPE them
  5849. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5850. cb(Qcur, "Qcur", il);
  5851. if (model.layers[il].bq) {
  5852. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5853. cb(Qcur, "Qcur", il);
  5854. }
  5855. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5856. cb(Kcur, "Kcur", il);
  5857. if (model.layers[il].bk) {
  5858. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5859. cb(Kcur, "Kcur", il);
  5860. }
  5861. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5862. cb(Vcur, "Vcur", il);
  5863. if (model.layers[il].bv) {
  5864. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5865. cb(Vcur, "Vcur", il);
  5866. }
  5867. Qcur = ggml_rope_custom(
  5868. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5869. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5870. ext_factor, attn_factor, beta_fast, beta_slow
  5871. );
  5872. cb(Qcur, "Qcur", il);
  5873. Kcur = ggml_rope_custom(
  5874. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5875. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5876. ext_factor, attn_factor, beta_fast, beta_slow
  5877. );
  5878. cb(Kcur, "Kcur", il);
  5879. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5880. model.layers[il].wo, model.layers[il].bo,
  5881. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5882. }
  5883. if (il == n_layer - 1) {
  5884. // skip computing output for unused tokens
  5885. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5886. n_tokens = n_outputs;
  5887. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5888. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5889. }
  5890. // Grok
  5891. // if attn_out_norm is present then apply it before adding the input
  5892. if (model.layers[il].attn_out_norm) {
  5893. cur = llm_build_norm(ctx0, cur, hparams,
  5894. model.layers[il].attn_out_norm, NULL,
  5895. LLM_NORM_RMS, cb, il);
  5896. cb(cur, "attn_out_norm", il);
  5897. }
  5898. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5899. cb(ffn_inp, "ffn_inp", il);
  5900. // feed-forward network
  5901. // MoE branch
  5902. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5903. model.layers[il].ffn_norm, NULL,
  5904. LLM_NORM_RMS, cb, il);
  5905. cb(cur, "ffn_norm", il);
  5906. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5907. cb(logits, "ffn_moe_logits", il);
  5908. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5909. cb(probs, "ffn_moe_probs", il);
  5910. // select experts
  5911. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5912. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5913. ggml_tensor * weights = ggml_get_rows(ctx0,
  5914. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5915. cb(weights, "ffn_moe_weights", il);
  5916. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5917. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5918. cb(weights_sum, "ffn_moe_weights_sum", il);
  5919. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5920. cb(weights, "ffn_moe_weights_norm", il);
  5921. // compute expert outputs
  5922. ggml_tensor * moe_out = nullptr;
  5923. for (int i = 0; i < n_expert_used; ++i) {
  5924. ggml_tensor * cur_expert;
  5925. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exps, selected_experts, i, cur);
  5926. cb(cur_up, "ffn_moe_up", il);
  5927. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exps, selected_experts, i, cur);
  5928. cb(cur_gate, "ffn_moe_gate", il);
  5929. //GeLU
  5930. cur_gate = ggml_gelu(ctx0, cur_gate);
  5931. cb(cur_gate, "ffn_moe_gelu", il);
  5932. cur_expert = ggml_mul(ctx0, cur_up, cur_gate);
  5933. cb(cur_expert, "ffn_moe_gate_par", il);
  5934. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exps, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5935. cb(cur_expert, "ffn_moe_down", il);
  5936. cur_expert = ggml_mul(ctx0, cur_expert,
  5937. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5938. cb(cur_expert, "ffn_moe_weighted", il);
  5939. if (i == 0) {
  5940. moe_out = cur_expert;
  5941. } else {
  5942. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5943. cb(moe_out, "ffn_moe_out", il);
  5944. }
  5945. }
  5946. cur = moe_out;
  5947. // Grok
  5948. // if layer_out_norm is present then apply it before adding the input
  5949. // Idea: maybe ffn_out_norm is a better name
  5950. if (model.layers[il].layer_out_norm) {
  5951. cur = llm_build_norm(ctx0, cur, hparams,
  5952. model.layers[il].layer_out_norm, NULL,
  5953. LLM_NORM_RMS, cb, il);
  5954. cb(cur, "layer_out_norm", il);
  5955. }
  5956. cur = ggml_add(ctx0, cur, ffn_inp);
  5957. cb(cur, "ffn_out", il);
  5958. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5959. if (layer_dir != nullptr) {
  5960. cur = ggml_add(ctx0, cur, layer_dir);
  5961. }
  5962. cb(cur, "l_out", il);
  5963. // input for next layer
  5964. inpL = cur;
  5965. }
  5966. cur = inpL;
  5967. cur = llm_build_norm(ctx0, cur, hparams,
  5968. model.output_norm, NULL,
  5969. LLM_NORM_RMS, cb, -1);
  5970. cb(cur, "result_norm", -1);
  5971. // lm_head
  5972. cur = ggml_mul_mat(ctx0, model.output, cur);
  5973. // Grok
  5974. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5975. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5976. cb(cur, "result_output", -1);
  5977. ggml_build_forward_expand(gf, cur);
  5978. return gf;
  5979. }
  5980. struct ggml_cgraph * build_starcoder() {
  5981. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5982. const int64_t n_embd_head = hparams.n_embd_head_v;
  5983. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5984. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5985. struct ggml_tensor * cur;
  5986. struct ggml_tensor * inpL;
  5987. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5988. // inp_pos - contains the positions
  5989. struct ggml_tensor * inp_pos = build_inp_pos();
  5990. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5991. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5992. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5993. cb(pos, "pos_embd", -1);
  5994. inpL = ggml_add(ctx0, inpL, pos);
  5995. cb(inpL, "inpL", -1);
  5996. for (int il = 0; il < n_layer; ++il) {
  5997. cur = llm_build_norm(ctx0, inpL, hparams,
  5998. model.layers[il].attn_norm,
  5999. model.layers[il].attn_norm_b,
  6000. LLM_NORM, cb, il);
  6001. cb(cur, "attn_norm", il);
  6002. // self-attention
  6003. {
  6004. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6005. cb(cur, "wqkv", il);
  6006. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6007. cb(cur, "bqkv", il);
  6008. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6009. 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)));
  6010. 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)));
  6011. cb(Qcur, "Qcur", il);
  6012. cb(Kcur, "Kcur", il);
  6013. cb(Vcur, "Vcur", il);
  6014. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6015. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6016. model.layers[il].wo, model.layers[il].bo,
  6017. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6018. }
  6019. if (il == n_layer - 1) {
  6020. // skip computing output for unused tokens
  6021. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6022. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6023. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6024. }
  6025. // add the input
  6026. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6027. cb(ffn_inp, "ffn_inp", il);
  6028. // FF
  6029. {
  6030. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6031. model.layers[il].ffn_norm,
  6032. model.layers[il].ffn_norm_b,
  6033. LLM_NORM, cb, il);
  6034. cb(cur, "ffn_norm", il);
  6035. cur = llm_build_ffn(ctx0, cur,
  6036. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6037. NULL, NULL,
  6038. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6039. NULL,
  6040. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6041. cb(cur, "ffn_out", il);
  6042. }
  6043. inpL = ggml_add(ctx0, cur, ffn_inp);
  6044. cb(inpL, "l_out", il);
  6045. }
  6046. cur = llm_build_norm(ctx0, inpL, hparams,
  6047. model.output_norm,
  6048. model.output_norm_b,
  6049. LLM_NORM, cb, -1);
  6050. cb(cur, "result_norm", -1);
  6051. cur = ggml_mul_mat(ctx0, model.output, cur);
  6052. cb(cur, "result_output", -1);
  6053. ggml_build_forward_expand(gf, cur);
  6054. return gf;
  6055. }
  6056. struct ggml_cgraph * build_persimmon() {
  6057. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6058. const int64_t n_embd_head = hparams.n_embd_head_v;
  6059. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6060. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  6061. struct ggml_tensor * cur;
  6062. struct ggml_tensor * inpL;
  6063. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6064. // inp_pos - contains the positions
  6065. struct ggml_tensor * inp_pos = build_inp_pos();
  6066. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6067. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6068. for (int il = 0; il < n_layer; ++il) {
  6069. struct ggml_tensor * residual = inpL;
  6070. cur = llm_build_norm(ctx0, inpL, hparams,
  6071. model.layers[il].attn_norm,
  6072. model.layers[il].attn_norm_b,
  6073. LLM_NORM, cb, il);
  6074. cb(cur, "attn_norm", il);
  6075. // self attention
  6076. {
  6077. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6078. cb(cur, "wqkv", il);
  6079. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6080. cb(cur, "bqkv", il);
  6081. // split qkv
  6082. GGML_ASSERT(n_head_kv == n_head);
  6083. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  6084. cb(tmpqkv, "tmpqkv", il);
  6085. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  6086. cb(tmpqkv_perm, "tmpqkv", il);
  6087. struct ggml_tensor * tmpq = ggml_view_3d(
  6088. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6089. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6090. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6091. 0
  6092. );
  6093. cb(tmpq, "tmpq", il);
  6094. struct ggml_tensor * tmpk = ggml_view_3d(
  6095. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6096. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6097. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6098. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  6099. );
  6100. cb(tmpk, "tmpk", il);
  6101. // Q/K Layernorm
  6102. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  6103. model.layers[il].attn_q_norm,
  6104. model.layers[il].attn_q_norm_b,
  6105. LLM_NORM, cb, il);
  6106. cb(tmpq, "tmpq", il);
  6107. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  6108. model.layers[il].attn_k_norm,
  6109. model.layers[il].attn_k_norm_b,
  6110. LLM_NORM, cb, il);
  6111. cb(tmpk, "tmpk", il);
  6112. // RoPE the first n_rot of q/k, pass the other half, and concat.
  6113. struct ggml_tensor * qrot = ggml_view_3d(
  6114. ctx0, tmpq, n_rot, n_head, n_tokens,
  6115. ggml_element_size(tmpq) * n_embd_head,
  6116. ggml_element_size(tmpq) * n_embd_head * n_head,
  6117. 0
  6118. );
  6119. cb(qrot, "qrot", il);
  6120. struct ggml_tensor * krot = ggml_view_3d(
  6121. ctx0, tmpk, n_rot, n_head, n_tokens,
  6122. ggml_element_size(tmpk) * n_embd_head,
  6123. ggml_element_size(tmpk) * n_embd_head * n_head,
  6124. 0
  6125. );
  6126. cb(krot, "krot", il);
  6127. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  6128. struct ggml_tensor * qpass = ggml_view_3d(
  6129. ctx0, tmpq, n_rot, n_head, n_tokens,
  6130. ggml_element_size(tmpq) * n_embd_head,
  6131. ggml_element_size(tmpq) * n_embd_head * n_head,
  6132. ggml_element_size(tmpq) * n_rot
  6133. );
  6134. cb(qpass, "qpass", il);
  6135. struct ggml_tensor * kpass = ggml_view_3d(
  6136. ctx0, tmpk, n_rot, n_head, n_tokens,
  6137. ggml_element_size(tmpk) * n_embd_head,
  6138. ggml_element_size(tmpk) * n_embd_head * n_head,
  6139. ggml_element_size(tmpk) * n_rot
  6140. );
  6141. cb(kpass, "kpass", il);
  6142. struct ggml_tensor * qrotated = ggml_rope_custom(
  6143. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6144. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6145. );
  6146. cb(qrotated, "qrotated", il);
  6147. struct ggml_tensor * krotated = ggml_rope_custom(
  6148. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6149. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6150. );
  6151. cb(krotated, "krotated", il);
  6152. // ggml currently only supports concatenation on dim=2
  6153. // so we need to permute qrot, qpass, concat, then permute back.
  6154. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6155. cb(qrotated, "qrotated", il);
  6156. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6157. cb(krotated, "krotated", il);
  6158. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6159. cb(qpass, "qpass", il);
  6160. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6161. cb(kpass, "kpass", il);
  6162. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6163. cb(Qcur, "Qcur", il);
  6164. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6165. cb(Kcur, "Kcur", il);
  6166. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6167. cb(Q, "Q", il);
  6168. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6169. cb(Kcur, "Kcur", il);
  6170. struct ggml_tensor * Vcur = ggml_view_3d(
  6171. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6172. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6173. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6174. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6175. );
  6176. cb(Vcur, "Vcur", il);
  6177. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6178. model.layers[il].wo, model.layers[il].bo,
  6179. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6180. }
  6181. if (il == n_layer - 1) {
  6182. // skip computing output for unused tokens
  6183. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6184. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6185. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6186. }
  6187. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6188. cb(ffn_inp, "ffn_inp", il);
  6189. // feed-forward network
  6190. {
  6191. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6192. model.layers[il].ffn_norm,
  6193. model.layers[il].ffn_norm_b,
  6194. LLM_NORM, cb, il);
  6195. cb(cur, "ffn_norm", il);
  6196. cur = llm_build_ffn(ctx0, cur,
  6197. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6198. NULL, NULL,
  6199. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6200. NULL,
  6201. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6202. cb(cur, "ffn_out", il);
  6203. }
  6204. cur = ggml_add(ctx0, cur, ffn_inp);
  6205. cb(cur, "l_out", il);
  6206. inpL = cur;
  6207. }
  6208. cur = inpL;
  6209. cur = llm_build_norm(ctx0, cur, hparams,
  6210. model.output_norm,
  6211. model.output_norm_b,
  6212. LLM_NORM, cb, -1);
  6213. cb(cur, "result_norm", -1);
  6214. cur = ggml_mul_mat(ctx0, model.output, cur);
  6215. cb(cur, "result_output", -1);
  6216. ggml_build_forward_expand(gf, cur);
  6217. return gf;
  6218. }
  6219. struct ggml_cgraph * build_refact() {
  6220. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6221. const int64_t n_embd_head = hparams.n_embd_head_v;
  6222. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6223. struct ggml_tensor * cur;
  6224. struct ggml_tensor * inpL;
  6225. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6226. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6227. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6228. // positions of the tokens in the KV cache
  6229. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6230. for (int il = 0; il < n_layer; ++il) {
  6231. struct ggml_tensor * inpSA = inpL;
  6232. cur = llm_build_norm(ctx0, inpL, hparams,
  6233. model.layers[il].attn_norm, NULL,
  6234. LLM_NORM_RMS, cb, il);
  6235. cb(cur, "attn_norm", il);
  6236. // self-attention
  6237. {
  6238. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6239. cb(Qcur, "Qcur", il);
  6240. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6241. cb(Kcur, "Kcur", il);
  6242. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6243. cb(Vcur, "Vcur", il);
  6244. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6245. cb(Kcur, "Kcur", il);
  6246. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6247. cb(Qcur, "Qcur", il);
  6248. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6249. model.layers[il].wo, NULL,
  6250. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6251. }
  6252. if (il == n_layer - 1) {
  6253. // skip computing output for unused tokens
  6254. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6255. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6256. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6257. }
  6258. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6259. cb(ffn_inp, "ffn_inp", il);
  6260. // feed-forward network
  6261. {
  6262. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6263. model.layers[il].ffn_norm, NULL,
  6264. LLM_NORM_RMS, cb, il);
  6265. cb(cur, "ffn_norm", il);
  6266. cur = llm_build_ffn(ctx0, cur,
  6267. model.layers[il].ffn_up, NULL,
  6268. model.layers[il].ffn_gate, NULL,
  6269. model.layers[il].ffn_down, NULL,
  6270. NULL,
  6271. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6272. cb(cur, "ffn_out", il);
  6273. }
  6274. cur = ggml_add(ctx0, cur, ffn_inp);
  6275. cb(cur, "l_out", il);
  6276. // input for next layer
  6277. inpL = cur;
  6278. }
  6279. cur = inpL;
  6280. cur = llm_build_norm(ctx0, cur, hparams,
  6281. model.output_norm, NULL,
  6282. LLM_NORM_RMS, cb, -1);
  6283. cb(cur, "result_norm", -1);
  6284. // lm_head
  6285. cur = ggml_mul_mat(ctx0, model.output, cur);
  6286. cb(cur, "result_output", -1);
  6287. ggml_build_forward_expand(gf, cur);
  6288. return gf;
  6289. }
  6290. struct ggml_cgraph * build_bert() {
  6291. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6292. const int64_t n_embd_head = hparams.n_embd_head_v;
  6293. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6294. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6295. struct ggml_tensor * cur;
  6296. struct ggml_tensor * inpL;
  6297. struct ggml_tensor * inp_pos = build_inp_pos();
  6298. struct ggml_tensor * inp_mean = build_inp_mean();
  6299. struct ggml_tensor * inp_cls = build_inp_cls();
  6300. // construct input embeddings (token, type, position)
  6301. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6302. // token types are hardcoded to zero ("Sentence A")
  6303. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6304. inpL = ggml_add(ctx0, inpL, type_row0);
  6305. if (model.arch == LLM_ARCH_BERT) {
  6306. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6307. }
  6308. cb(inpL, "inp_embd", -1);
  6309. // embed layer norm
  6310. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6311. cb(inpL, "inp_norm", -1);
  6312. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6313. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6314. // iterate layers
  6315. for (int il = 0; il < n_layer; ++il) {
  6316. struct ggml_tensor * cur = inpL;
  6317. struct ggml_tensor * Qcur;
  6318. struct ggml_tensor * Kcur;
  6319. struct ggml_tensor * Vcur;
  6320. // self-attention
  6321. if (model.arch == LLM_ARCH_BERT) {
  6322. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6323. cb(Qcur, "Qcur", il);
  6324. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6325. cb(Kcur, "Kcur", il);
  6326. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6327. cb(Vcur, "Vcur", il);
  6328. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6329. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6330. } else {
  6331. // compute Q and K and RoPE them
  6332. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6333. cb(cur, "wqkv", il);
  6334. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6335. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6336. 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)));
  6337. cb(Qcur, "Qcur", il);
  6338. cb(Kcur, "Kcur", il);
  6339. cb(Vcur, "Vcur", il);
  6340. Qcur = ggml_rope_custom(
  6341. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6342. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6343. ext_factor, attn_factor, beta_fast, beta_slow
  6344. );
  6345. cb(Qcur, "Qcur", il);
  6346. Kcur = ggml_rope_custom(
  6347. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6348. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6349. ext_factor, attn_factor, beta_fast, beta_slow
  6350. );
  6351. cb(Kcur, "Kcur", il);
  6352. }
  6353. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6354. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6355. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6356. cb(kq, "kq", il);
  6357. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6358. cb(kq, "kq_soft_max_ext", il);
  6359. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6360. cb(v, "v", il);
  6361. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6362. cb(kqv, "kqv", il);
  6363. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6364. cb(kqv_merged, "kqv_merged", il);
  6365. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6366. cb(cur, "kqv_merged_cont", il);
  6367. ggml_build_forward_expand(gf, cur);
  6368. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6369. if (model.layers[il].bo) {
  6370. cb(cur, "kqv_wo", il);
  6371. }
  6372. if (model.layers[il].bo) {
  6373. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6374. }
  6375. cb(cur, "kqv_out", il);
  6376. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6377. // skip computing output for unused tokens
  6378. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6379. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6380. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6381. }
  6382. // re-add the layer input
  6383. cur = ggml_add(ctx0, cur, inpL);
  6384. // attention layer norm
  6385. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6386. struct ggml_tensor * ffn_inp = cur;
  6387. cb(ffn_inp, "ffn_inp", il);
  6388. // feed-forward network
  6389. if (model.arch == LLM_ARCH_BERT) {
  6390. cur = llm_build_ffn(ctx0, cur,
  6391. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6392. NULL, NULL,
  6393. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6394. NULL,
  6395. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6396. } else {
  6397. cur = llm_build_ffn(ctx0, cur,
  6398. model.layers[il].ffn_up, NULL,
  6399. model.layers[il].ffn_gate, NULL,
  6400. model.layers[il].ffn_down, NULL,
  6401. NULL,
  6402. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6403. }
  6404. cb(cur, "ffn_out", il);
  6405. // attentions bypass the intermediate layer
  6406. cur = ggml_add(ctx0, cur, ffn_inp);
  6407. // output layer norm
  6408. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6409. // input for next layer
  6410. inpL = cur;
  6411. }
  6412. // final output
  6413. cur = inpL;
  6414. cb(cur, "result_embd", -1);
  6415. // pooling layer
  6416. switch (pooling_type) {
  6417. case LLAMA_POOLING_TYPE_NONE:
  6418. {
  6419. // nop
  6420. } break;
  6421. case LLAMA_POOLING_TYPE_MEAN:
  6422. {
  6423. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6424. cb(cur, "result_embd_pooled", -1);
  6425. } break;
  6426. case LLAMA_POOLING_TYPE_CLS:
  6427. {
  6428. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6429. cb(cur, "result_embd_pooled", -1);
  6430. } break;
  6431. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6432. {
  6433. GGML_ASSERT(false && "Invalid pooling type");
  6434. } break;
  6435. }
  6436. ggml_build_forward_expand(gf, cur);
  6437. return gf;
  6438. }
  6439. struct ggml_cgraph * build_bloom() {
  6440. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6441. const int64_t n_embd_head = hparams.n_embd_head_v;
  6442. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6443. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6444. struct ggml_tensor * cur;
  6445. struct ggml_tensor * inpL;
  6446. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6447. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6448. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6449. // positions of the tokens in the KV cache
  6450. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6451. inpL = llm_build_norm(ctx0, inpL, hparams,
  6452. model.tok_norm,
  6453. model.tok_norm_b,
  6454. LLM_NORM, cb, -1);
  6455. cb(inpL, "inp_norm", -1);
  6456. for (int il = 0; il < n_layer; ++il) {
  6457. cur = llm_build_norm(ctx0, inpL, hparams,
  6458. model.layers[il].attn_norm,
  6459. model.layers[il].attn_norm_b,
  6460. LLM_NORM, cb, il);
  6461. cb(cur, "attn_norm", il);
  6462. // self-attention
  6463. {
  6464. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6465. cb(cur, "wqkv", il);
  6466. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6467. cb(cur, "bqkv", il);
  6468. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6469. 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)));
  6470. 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)));
  6471. cb(Qcur, "Qcur", il);
  6472. cb(Kcur, "Kcur", il);
  6473. cb(Vcur, "Vcur", il);
  6474. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6475. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6476. model.layers[il].wo, model.layers[il].bo,
  6477. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), 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. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6483. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6484. }
  6485. // Add the input
  6486. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6487. cb(ffn_inp, "ffn_inp", il);
  6488. // FF
  6489. {
  6490. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6491. model.layers[il].ffn_norm,
  6492. model.layers[il].ffn_norm_b,
  6493. LLM_NORM, cb, il);
  6494. cb(cur, "ffn_norm", il);
  6495. cur = llm_build_ffn(ctx0, cur,
  6496. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6497. NULL, NULL,
  6498. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6499. NULL,
  6500. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6501. cb(cur, "ffn_out", il);
  6502. }
  6503. inpL = ggml_add(ctx0, cur, ffn_inp);
  6504. cb(inpL, "l_out", il);
  6505. }
  6506. cur = llm_build_norm(ctx0, inpL, hparams,
  6507. model.output_norm,
  6508. model.output_norm_b,
  6509. LLM_NORM, cb, -1);
  6510. cb(cur, "result_norm", -1);
  6511. cur = ggml_mul_mat(ctx0, model.output, cur);
  6512. cb(cur, "result_output", -1);
  6513. ggml_build_forward_expand(gf, cur);
  6514. return gf;
  6515. }
  6516. struct ggml_cgraph * build_mpt() {
  6517. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6518. const int64_t n_embd_head = hparams.n_embd_head_v;
  6519. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6520. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6521. struct ggml_tensor * cur;
  6522. struct ggml_tensor * pos;
  6523. struct ggml_tensor * inpL;
  6524. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6525. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6526. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6527. // positions of the tokens in the KV cache
  6528. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6529. if (model.pos_embd) {
  6530. // inp_pos - contains the positions
  6531. struct ggml_tensor * inp_pos = build_inp_pos();
  6532. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6533. cb(pos, "pos_embd", -1);
  6534. inpL = ggml_add(ctx0, inpL, pos);
  6535. cb(inpL, "inpL", -1);
  6536. }
  6537. for (int il = 0; il < n_layer; ++il) {
  6538. struct ggml_tensor * attn_norm;
  6539. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6540. model.layers[il].attn_norm,
  6541. model.layers[il].attn_norm_b,
  6542. LLM_NORM, cb, il);
  6543. cb(attn_norm, "attn_norm", il);
  6544. // self-attention
  6545. {
  6546. cur = attn_norm;
  6547. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6548. cb(cur, "wqkv", il);
  6549. if (model.layers[il].bqkv){
  6550. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6551. cb(cur, "bqkv", il);
  6552. }
  6553. if (hparams.f_clamp_kqv > 0.0f) {
  6554. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6555. cb(cur, "wqkv_clamped", il);
  6556. }
  6557. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6558. 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)));
  6559. 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)));
  6560. cb(Qcur, "Qcur", il);
  6561. cb(Kcur, "Kcur", il);
  6562. cb(Vcur, "Vcur", il);
  6563. // Q/K Layernorm
  6564. if (model.layers[il].attn_q_norm) {
  6565. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  6566. model.layers[il].attn_q_norm,
  6567. model.layers[il].attn_q_norm_b,
  6568. LLM_NORM, cb, il);
  6569. cb(Qcur, "Qcur", il);
  6570. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  6571. model.layers[il].attn_k_norm,
  6572. model.layers[il].attn_k_norm_b,
  6573. LLM_NORM, cb, il);
  6574. cb(Kcur, "Kcur", il);
  6575. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6576. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6577. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6578. model.layers[il].wo, model.layers[il].bo,
  6579. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6580. } else {
  6581. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6582. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6583. model.layers[il].wo, model.layers[il].bo,
  6584. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6585. }
  6586. }
  6587. if (il == n_layer - 1) {
  6588. // skip computing output for unused tokens
  6589. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6590. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6591. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6592. }
  6593. // Add the input
  6594. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6595. cb(ffn_inp, "ffn_inp", il);
  6596. // feed forward
  6597. {
  6598. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6599. model.layers[il].ffn_norm,
  6600. model.layers[il].ffn_norm_b,
  6601. LLM_NORM, cb, il);
  6602. cb(cur, "ffn_norm", il);
  6603. cur = llm_build_ffn(ctx0, cur,
  6604. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6605. NULL, NULL,
  6606. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6607. model.layers[il].ffn_act,
  6608. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6609. cb(cur, "ffn_out", il);
  6610. }
  6611. cur = ggml_add(ctx0, cur, ffn_inp);
  6612. cb(cur, "l_out", il);
  6613. // input for next layer
  6614. inpL = cur;
  6615. }
  6616. cur = inpL;
  6617. cur = llm_build_norm(ctx0, cur, hparams,
  6618. model.output_norm,
  6619. model.output_norm_b,
  6620. LLM_NORM, cb, -1);
  6621. cb(cur, "result_norm", -1);
  6622. cur = ggml_mul_mat(ctx0, model.output, cur);
  6623. cb(cur, "result_output", -1);
  6624. ggml_build_forward_expand(gf, cur);
  6625. return gf;
  6626. }
  6627. struct ggml_cgraph * build_stablelm() {
  6628. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6629. const int64_t n_embd_head = hparams.n_embd_head_v;
  6630. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6631. struct ggml_tensor * cur;
  6632. struct ggml_tensor * inpL;
  6633. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6634. // inp_pos - contains the positions
  6635. struct ggml_tensor * inp_pos = build_inp_pos();
  6636. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6637. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6638. for (int il = 0; il < n_layer; ++il) {
  6639. struct ggml_tensor * inpSA = inpL;
  6640. // norm
  6641. cur = llm_build_norm(ctx0, inpL, hparams,
  6642. model.layers[il].attn_norm,
  6643. model.layers[il].attn_norm_b,
  6644. LLM_NORM, cb, il);
  6645. cb(cur, "attn_norm", il);
  6646. // self-attention
  6647. {
  6648. // compute Q and K and RoPE them
  6649. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6650. cb(Qcur, "Qcur", il);
  6651. if (model.layers[il].bq) {
  6652. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6653. cb(Qcur, "Qcur", il);
  6654. }
  6655. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6656. cb(Kcur, "Kcur", il);
  6657. if (model.layers[il].bk) {
  6658. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6659. cb(Kcur, "Kcur", il);
  6660. }
  6661. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6662. cb(Vcur, "Vcur", il);
  6663. if (model.layers[il].bv) {
  6664. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6665. cb(Vcur, "Vcur", il);
  6666. }
  6667. Qcur = ggml_rope_custom(
  6668. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6669. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6670. ext_factor, attn_factor, beta_fast, beta_slow
  6671. );
  6672. cb(Qcur, "Qcur", il);
  6673. Kcur = ggml_rope_custom(
  6674. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6675. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6676. ext_factor, attn_factor, beta_fast, beta_slow
  6677. );
  6678. cb(Kcur, "Kcur", il);
  6679. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6680. model.layers[il].wo, NULL,
  6681. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6682. }
  6683. if (il == n_layer - 1) {
  6684. // skip computing output for unused tokens
  6685. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6686. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6687. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6688. }
  6689. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6690. cb(ffn_inp, "ffn_inp", il);
  6691. // feed-forward network
  6692. {
  6693. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6694. model.layers[il].ffn_norm,
  6695. model.layers[il].ffn_norm_b,
  6696. LLM_NORM, cb, il);
  6697. cb(cur, "ffn_norm", il);
  6698. cur = llm_build_ffn(ctx0, cur,
  6699. model.layers[il].ffn_up, NULL,
  6700. model.layers[il].ffn_gate, NULL,
  6701. model.layers[il].ffn_down, NULL,
  6702. NULL,
  6703. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6704. cb(cur, "ffn_out", il);
  6705. }
  6706. cur = ggml_add(ctx0, cur, ffn_inp);
  6707. cb(cur, "l_out", il);
  6708. // input for next layer
  6709. inpL = cur;
  6710. }
  6711. cur = inpL;
  6712. cur = llm_build_norm(ctx0, cur, hparams,
  6713. model.output_norm,
  6714. model.output_norm_b,
  6715. LLM_NORM, cb, -1);
  6716. cb(cur, "result_norm", -1);
  6717. // lm_head
  6718. cur = ggml_mul_mat(ctx0, model.output, cur);
  6719. cb(cur, "result_output", -1);
  6720. ggml_build_forward_expand(gf, cur);
  6721. return gf;
  6722. }
  6723. struct ggml_cgraph * build_qwen() {
  6724. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6725. const int64_t n_embd_head = hparams.n_embd_head_v;
  6726. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6727. struct ggml_tensor * cur;
  6728. struct ggml_tensor * inpL;
  6729. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6730. // inp_pos - contains the positions
  6731. struct ggml_tensor * inp_pos = build_inp_pos();
  6732. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6733. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6734. for (int il = 0; il < n_layer; ++il) {
  6735. struct ggml_tensor * inpSA = inpL;
  6736. cur = llm_build_norm(ctx0, inpL, hparams,
  6737. model.layers[il].attn_norm, NULL,
  6738. LLM_NORM_RMS, cb, il);
  6739. cb(cur, "attn_norm", il);
  6740. // self-attention
  6741. {
  6742. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6743. cb(cur, "wqkv", il);
  6744. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6745. cb(cur, "bqkv", il);
  6746. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6747. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6748. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6749. cb(Qcur, "Qcur", il);
  6750. cb(Kcur, "Kcur", il);
  6751. cb(Vcur, "Vcur", il);
  6752. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6753. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6754. // using mode = 2 for neox mode
  6755. Qcur = ggml_rope_custom(
  6756. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6757. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6758. );
  6759. cb(Qcur, "Qcur", il);
  6760. Kcur = ggml_rope_custom(
  6761. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6762. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6763. );
  6764. cb(Kcur, "Kcur", il);
  6765. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6766. model.layers[il].wo, NULL,
  6767. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6768. }
  6769. if (il == n_layer - 1) {
  6770. // skip computing output for unused tokens
  6771. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6772. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6773. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6774. }
  6775. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6776. cb(ffn_inp, "ffn_inp", il);
  6777. // feed-forward forward
  6778. {
  6779. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6780. model.layers[il].ffn_norm, NULL,
  6781. LLM_NORM_RMS, cb, il);
  6782. cb(cur, "ffn_norm", il);
  6783. cur = llm_build_ffn(ctx0, cur,
  6784. model.layers[il].ffn_up, NULL,
  6785. model.layers[il].ffn_gate, NULL,
  6786. model.layers[il].ffn_down, NULL,
  6787. NULL,
  6788. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6789. cb(cur, "ffn_out", il);
  6790. }
  6791. cur = ggml_add(ctx0, cur, ffn_inp);
  6792. cb(cur, "l_out", il);
  6793. // input for next layer
  6794. inpL = cur;
  6795. }
  6796. cur = inpL;
  6797. cur = llm_build_norm(ctx0, cur, hparams,
  6798. model.output_norm, NULL,
  6799. LLM_NORM_RMS, cb, -1);
  6800. cb(cur, "result_norm", -1);
  6801. // lm_head
  6802. cur = ggml_mul_mat(ctx0, model.output, cur);
  6803. cb(cur, "result_output", -1);
  6804. ggml_build_forward_expand(gf, cur);
  6805. return gf;
  6806. }
  6807. struct ggml_cgraph * build_qwen2() {
  6808. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6809. const int64_t n_embd_head = hparams.n_embd_head_v;
  6810. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6811. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6812. struct ggml_tensor * cur;
  6813. struct ggml_tensor * inpL;
  6814. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6815. // inp_pos - contains the positions
  6816. struct ggml_tensor * inp_pos = build_inp_pos();
  6817. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6818. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6819. for (int il = 0; il < n_layer; ++il) {
  6820. struct ggml_tensor * inpSA = inpL;
  6821. // norm
  6822. cur = llm_build_norm(ctx0, inpL, hparams,
  6823. model.layers[il].attn_norm, NULL,
  6824. LLM_NORM_RMS, cb, il);
  6825. cb(cur, "attn_norm", il);
  6826. // self-attention
  6827. {
  6828. // compute Q and K and RoPE them
  6829. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6830. cb(Qcur, "Qcur", il);
  6831. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6832. cb(Qcur, "Qcur", il);
  6833. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6834. cb(Kcur, "Kcur", il);
  6835. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6836. cb(Kcur, "Kcur", il);
  6837. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6838. cb(Vcur, "Vcur", il);
  6839. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6840. cb(Vcur, "Vcur", il);
  6841. // these nodes are added to the graph together so that they are not reordered
  6842. // by doing so, the number of splits in the graph is reduced
  6843. ggml_build_forward_expand(gf, Qcur);
  6844. ggml_build_forward_expand(gf, Kcur);
  6845. ggml_build_forward_expand(gf, Vcur);
  6846. Qcur = ggml_rope_custom(
  6847. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6848. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6849. ext_factor, attn_factor, beta_fast, beta_slow
  6850. );
  6851. cb(Qcur, "Qcur", il);
  6852. Kcur = ggml_rope_custom(
  6853. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6854. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6855. ext_factor, attn_factor, beta_fast, beta_slow
  6856. );
  6857. cb(Kcur, "Kcur", il);
  6858. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6859. model.layers[il].wo, model.layers[il].bo,
  6860. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6861. }
  6862. if (il == n_layer - 1) {
  6863. // skip computing output for unused tokens
  6864. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6865. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6866. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6867. }
  6868. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6869. cb(ffn_inp, "ffn_inp", il);
  6870. // feed-forward network
  6871. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6872. model.layers[il].ffn_norm, NULL,
  6873. LLM_NORM_RMS, cb, il);
  6874. cb(cur, "ffn_norm", il);
  6875. cur = llm_build_ffn(ctx0, cur,
  6876. model.layers[il].ffn_up, NULL,
  6877. model.layers[il].ffn_gate, NULL,
  6878. model.layers[il].ffn_down, NULL,
  6879. NULL,
  6880. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6881. cb(cur, "ffn_out", il);
  6882. cur = ggml_add(ctx0, cur, ffn_inp);
  6883. cb(cur, "l_out", il);
  6884. // input for next layer
  6885. inpL = cur;
  6886. }
  6887. cur = inpL;
  6888. cur = llm_build_norm(ctx0, cur, hparams,
  6889. model.output_norm, NULL,
  6890. LLM_NORM_RMS, cb, -1);
  6891. cb(cur, "result_norm", -1);
  6892. // lm_head
  6893. cur = ggml_mul_mat(ctx0, model.output, cur);
  6894. cb(cur, "result_output", -1);
  6895. ggml_build_forward_expand(gf, cur);
  6896. return gf;
  6897. }
  6898. struct ggml_cgraph * build_phi2() {
  6899. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6900. const int64_t n_embd_head = hparams.n_embd_head_v;
  6901. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6902. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6903. struct ggml_tensor * cur;
  6904. struct ggml_tensor * attn_norm_output;
  6905. struct ggml_tensor * ffn_output;
  6906. struct ggml_tensor * inpL;
  6907. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6908. // inp_pos - contains the positions
  6909. struct ggml_tensor * inp_pos = build_inp_pos();
  6910. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6911. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6912. for (int il = 0; il < n_layer; ++il) {
  6913. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6914. model.layers[il].attn_norm,
  6915. model.layers[il].attn_norm_b,
  6916. LLM_NORM, cb, il);
  6917. cb(attn_norm_output, "attn_norm", il);
  6918. // self-attention
  6919. {
  6920. struct ggml_tensor * Qcur = nullptr;
  6921. struct ggml_tensor * Kcur = nullptr;
  6922. struct ggml_tensor * Vcur = nullptr;
  6923. if (model.layers[il].wqkv) {
  6924. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6925. cb(cur, "wqkv", il);
  6926. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6927. cb(cur, "bqkv", il);
  6928. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6929. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6930. 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)));
  6931. } else {
  6932. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6933. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6934. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6935. }
  6936. cb(Qcur, "Qcur", il);
  6937. cb(Kcur, "Kcur", il);
  6938. cb(Vcur, "Vcur", il);
  6939. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6940. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6941. Qcur = ggml_rope_custom(
  6942. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6943. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6944. );
  6945. cb(Qcur, "Qcur", il);
  6946. // with phi2, we scale the Q to avoid precision issues
  6947. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6948. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6949. cb(Qcur, "Qcur", il);
  6950. Kcur = ggml_rope_custom(
  6951. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6952. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6953. );
  6954. cb(Kcur, "Kcur", il);
  6955. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6956. model.layers[il].wo, model.layers[il].bo,
  6957. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6958. }
  6959. if (il == n_layer - 1) {
  6960. // skip computing output for unused tokens
  6961. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6962. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6963. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6964. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  6965. }
  6966. // FF
  6967. {
  6968. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6969. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6970. NULL, NULL,
  6971. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6972. NULL,
  6973. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6974. cb(ffn_output, "ffn_out", il);
  6975. }
  6976. cur = ggml_add(ctx0, cur, ffn_output);
  6977. cb(cur, "l_out", il);
  6978. cur = ggml_add(ctx0, cur, inpL);
  6979. cb(cur, "l_out", il);
  6980. inpL = cur;
  6981. }
  6982. cur = llm_build_norm(ctx0, inpL, hparams,
  6983. model.output_norm,
  6984. model.output_norm_b,
  6985. LLM_NORM, cb, -1);
  6986. cb(cur, "result_norm", -1);
  6987. cur = ggml_mul_mat(ctx0, model.output, cur);
  6988. cb(cur, "result_output_no_bias", -1);
  6989. cur = ggml_add(ctx0, cur, model.output_b);
  6990. cb(cur, "result_output", -1);
  6991. ggml_build_forward_expand(gf, cur);
  6992. return gf;
  6993. }
  6994. struct ggml_cgraph * build_plamo() {
  6995. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6996. const int64_t n_embd_head = hparams.n_embd_head_v;
  6997. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6998. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6999. struct ggml_tensor * cur;
  7000. struct ggml_tensor * inpL;
  7001. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7002. // inp_pos - contains the positions
  7003. struct ggml_tensor * inp_pos = build_inp_pos();
  7004. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7005. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7006. for (int il = 0; il < n_layer; ++il) {
  7007. // norm
  7008. cur = llm_build_norm(ctx0, inpL, hparams,
  7009. model.layers[il].attn_norm, NULL,
  7010. LLM_NORM_RMS, cb, il);
  7011. cb(cur, "attn_norm", il);
  7012. struct ggml_tensor * attention_norm = cur;
  7013. // self-attention
  7014. {
  7015. // compute Q and K and RoPE them
  7016. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7017. cb(Qcur, "Qcur", il);
  7018. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7019. cb(Kcur, "Kcur", il);
  7020. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7021. cb(Vcur, "Vcur", il);
  7022. Qcur = ggml_rope_custom(
  7023. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  7024. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7025. ext_factor, attn_factor, beta_fast, beta_slow);
  7026. cb(Qcur, "Qcur", il);
  7027. Kcur = ggml_rope_custom(
  7028. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  7029. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7030. ext_factor, attn_factor, beta_fast, beta_slow);
  7031. cb(Kcur, "Kcur", il);
  7032. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7033. model.layers[il].wo, NULL,
  7034. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7035. }
  7036. struct ggml_tensor * sa_out = cur;
  7037. cur = attention_norm;
  7038. if (il == n_layer - 1) {
  7039. // skip computing output for unused tokens
  7040. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7041. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7042. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  7043. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7044. }
  7045. // feed-forward network
  7046. {
  7047. cur = llm_build_ffn(ctx0, cur,
  7048. model.layers[il].ffn_up, NULL,
  7049. model.layers[il].ffn_gate, NULL,
  7050. model.layers[il].ffn_down, NULL,
  7051. NULL,
  7052. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7053. cb(cur, "ffn_out", il);
  7054. }
  7055. cur = ggml_add(ctx0, cur, sa_out);
  7056. cb(cur, "l_out", il);
  7057. cur = ggml_add(ctx0, cur, inpL);
  7058. cb(cur, "l_out", il);
  7059. // input for next layer
  7060. inpL = cur;
  7061. }
  7062. cur = inpL;
  7063. cur = llm_build_norm(ctx0, cur, hparams,
  7064. model.output_norm, NULL,
  7065. LLM_NORM_RMS, cb, -1);
  7066. cb(cur, "result_norm", -1);
  7067. // lm_head
  7068. cur = ggml_mul_mat(ctx0, model.output, cur);
  7069. cb(cur, "result_output", -1);
  7070. ggml_build_forward_expand(gf, cur);
  7071. return gf;
  7072. }
  7073. struct ggml_cgraph * build_gpt2() {
  7074. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7075. const int64_t n_embd_head = hparams.n_embd_head_v;
  7076. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7077. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7078. struct ggml_tensor * cur;
  7079. struct ggml_tensor * pos;
  7080. struct ggml_tensor * inpL;
  7081. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7082. // inp_pos - contains the positions
  7083. struct ggml_tensor * inp_pos = build_inp_pos();
  7084. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7085. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7086. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7087. cb(pos, "pos_embd", -1);
  7088. inpL = ggml_add(ctx0, inpL, pos);
  7089. cb(inpL, "inpL", -1);
  7090. for (int il = 0; il < n_layer; ++il) {
  7091. cur = llm_build_norm(ctx0, inpL, hparams,
  7092. model.layers[il].attn_norm,
  7093. model.layers[il].attn_norm_b,
  7094. LLM_NORM, cb, il);
  7095. cb(cur, "attn_norm", il);
  7096. // self-attention
  7097. {
  7098. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7099. cb(cur, "wqkv", il);
  7100. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7101. cb(cur, "bqkv", il);
  7102. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7103. 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)));
  7104. 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)));
  7105. cb(Qcur, "Qcur", il);
  7106. cb(Kcur, "Kcur", il);
  7107. cb(Vcur, "Vcur", il);
  7108. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7109. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7110. model.layers[il].wo, model.layers[il].bo,
  7111. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7112. }
  7113. if (il == n_layer - 1) {
  7114. // skip computing output for unused tokens
  7115. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7116. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7117. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7118. }
  7119. // add the input
  7120. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7121. cb(ffn_inp, "ffn_inp", il);
  7122. // FF
  7123. {
  7124. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7125. model.layers[il].ffn_norm,
  7126. model.layers[il].ffn_norm_b,
  7127. LLM_NORM, cb, il);
  7128. cb(cur, "ffn_norm", il);
  7129. cur = llm_build_ffn(ctx0, cur,
  7130. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7131. NULL, NULL,
  7132. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7133. NULL,
  7134. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7135. cb(cur, "ffn_out", il);
  7136. }
  7137. inpL = ggml_add(ctx0, cur, ffn_inp);
  7138. cb(inpL, "l_out", il);
  7139. }
  7140. cur = llm_build_norm(ctx0, inpL, hparams,
  7141. model.output_norm,
  7142. model.output_norm_b,
  7143. LLM_NORM, cb, -1);
  7144. cb(cur, "result_norm", -1);
  7145. cur = ggml_mul_mat(ctx0, model.output, cur);
  7146. cb(cur, "result_output", -1);
  7147. ggml_build_forward_expand(gf, cur);
  7148. return gf;
  7149. }
  7150. struct ggml_cgraph * build_codeshell() {
  7151. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7152. const int64_t n_embd_head = hparams.n_embd_head_v;
  7153. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7154. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7155. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7156. struct ggml_tensor * cur;
  7157. struct ggml_tensor * inpL;
  7158. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7159. // inp_pos - contains the positions
  7160. struct ggml_tensor * inp_pos = build_inp_pos();
  7161. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7162. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7163. for (int il = 0; il < n_layer; ++il) {
  7164. cur = llm_build_norm(ctx0, inpL, hparams,
  7165. model.layers[il].attn_norm,
  7166. model.layers[il].attn_norm_b,
  7167. LLM_NORM, cb, il);
  7168. cb(cur, "attn_norm", il);
  7169. // self-attention
  7170. {
  7171. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7172. cb(cur, "wqkv", il);
  7173. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7174. cb(cur, "bqkv", il);
  7175. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7176. 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)));
  7177. 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)));
  7178. cb(tmpq, "tmpq", il);
  7179. cb(tmpk, "tmpk", il);
  7180. cb(Vcur, "Vcur", il);
  7181. struct ggml_tensor * Qcur = ggml_rope_custom(
  7182. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  7183. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7184. ext_factor, attn_factor, beta_fast, beta_slow
  7185. );
  7186. cb(Qcur, "Qcur", il);
  7187. struct ggml_tensor * Kcur = ggml_rope_custom(
  7188. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7189. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7190. ext_factor, attn_factor, beta_fast, beta_slow
  7191. );
  7192. cb(Kcur, "Kcur", il);
  7193. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7194. model.layers[il].wo, model.layers[il].bo,
  7195. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7196. }
  7197. if (il == n_layer - 1) {
  7198. // skip computing output for unused tokens
  7199. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7200. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7201. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7202. }
  7203. // add the input
  7204. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7205. cb(ffn_inp, "ffn_inp", il);
  7206. // FF
  7207. {
  7208. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7209. model.layers[il].ffn_norm,
  7210. model.layers[il].ffn_norm_b,
  7211. LLM_NORM, cb, il);
  7212. cb(cur, "ffn_norm", il);
  7213. cur = llm_build_ffn(ctx0, cur,
  7214. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7215. NULL, NULL,
  7216. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7217. NULL,
  7218. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7219. cb(cur, "ffn_out", il);
  7220. }
  7221. inpL = ggml_add(ctx0, cur, ffn_inp);
  7222. cb(inpL, "l_out", il);
  7223. }
  7224. cur = llm_build_norm(ctx0, inpL, hparams,
  7225. model.output_norm,
  7226. model.output_norm_b,
  7227. LLM_NORM, cb, -1);
  7228. cb(cur, "result_norm", -1);
  7229. cur = ggml_mul_mat(ctx0, model.output, cur);
  7230. cb(cur, "result_output", -1);
  7231. ggml_build_forward_expand(gf, cur);
  7232. return gf;
  7233. }
  7234. struct ggml_cgraph * build_orion() {
  7235. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7236. const int64_t n_embd_head = hparams.n_embd_head_v;
  7237. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7238. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7239. struct ggml_tensor * cur;
  7240. struct ggml_tensor * inpL;
  7241. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7242. // inp_pos - contains the positions
  7243. struct ggml_tensor * inp_pos = build_inp_pos();
  7244. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7245. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7246. for (int il = 0; il < n_layer; ++il) {
  7247. struct ggml_tensor * inpSA = inpL;
  7248. // norm
  7249. cur = llm_build_norm(ctx0, inpL, hparams,
  7250. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7251. LLM_NORM, cb, il);
  7252. cb(cur, "attn_norm", il);
  7253. // self-attention
  7254. {
  7255. // compute Q and K and RoPE them
  7256. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7257. cb(Qcur, "Qcur", il);
  7258. // if (model.layers[il].bq) {
  7259. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7260. // cb(Qcur, "Qcur", il);
  7261. // }
  7262. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7263. cb(Kcur, "Kcur", il);
  7264. // if (model.layers[il].bk) {
  7265. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7266. // cb(Kcur, "Kcur", il);
  7267. // }
  7268. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7269. cb(Vcur, "Vcur", il);
  7270. // if (model.layers[il].bv) {
  7271. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7272. // cb(Vcur, "Vcur", il);
  7273. // }
  7274. Qcur = ggml_rope_custom(
  7275. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7276. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7277. ext_factor, attn_factor, beta_fast, beta_slow
  7278. );
  7279. cb(Qcur, "Qcur", il);
  7280. Kcur = ggml_rope_custom(
  7281. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7282. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7283. ext_factor, attn_factor, beta_fast, beta_slow
  7284. );
  7285. cb(Kcur, "Kcur", il);
  7286. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7287. model.layers[il].wo, NULL,
  7288. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7289. }
  7290. if (il == n_layer - 1) {
  7291. // skip computing output for unused tokens
  7292. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7293. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7294. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7295. }
  7296. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7297. cb(ffn_inp, "ffn_inp", il);
  7298. // feed-forward network
  7299. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7300. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7301. LLM_NORM, cb, il);
  7302. cb(cur, "ffn_norm", il);
  7303. cur = llm_build_ffn(ctx0, cur,
  7304. model.layers[il].ffn_up, NULL,
  7305. model.layers[il].ffn_gate, NULL,
  7306. model.layers[il].ffn_down, NULL,
  7307. NULL,
  7308. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7309. cb(cur, "ffn_out", il);
  7310. cur = ggml_add(ctx0, cur, ffn_inp);
  7311. cb(cur, "l_out", il);
  7312. // input for next layer
  7313. inpL = cur;
  7314. }
  7315. cur = inpL;
  7316. cur = llm_build_norm(ctx0, cur, hparams,
  7317. model.output_norm, model.output_norm_b,
  7318. LLM_NORM, cb, -1);
  7319. cb(cur, "result_norm", -1);
  7320. // lm_head
  7321. cur = ggml_mul_mat(ctx0, model.output, cur);
  7322. cb(cur, "result_output", -1);
  7323. ggml_build_forward_expand(gf, cur);
  7324. return gf;
  7325. }
  7326. struct ggml_cgraph * build_internlm2() {
  7327. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7328. const int64_t n_embd_head = hparams.n_embd_head_v;
  7329. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7330. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7331. struct ggml_tensor * cur;
  7332. struct ggml_tensor * inpL;
  7333. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7334. // inp_pos - contains the positions
  7335. struct ggml_tensor * inp_pos = build_inp_pos();
  7336. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7337. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7338. for (int il = 0; il < n_layer; ++il) {
  7339. struct ggml_tensor * inpSA = inpL;
  7340. // norm
  7341. cur = llm_build_norm(ctx0, inpL, hparams,
  7342. model.layers[il].attn_norm, NULL,
  7343. LLM_NORM_RMS, cb, il);
  7344. cb(cur, "attn_norm", il);
  7345. // self-attention
  7346. {
  7347. // compute Q and K and RoPE them
  7348. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7349. cb(Qcur, "Qcur", il);
  7350. if (model.layers[il].bq) {
  7351. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7352. cb(Qcur, "Qcur", il);
  7353. }
  7354. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7355. cb(Kcur, "Kcur", il);
  7356. if (model.layers[il].bk) {
  7357. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7358. cb(Kcur, "Kcur", il);
  7359. }
  7360. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7361. cb(Vcur, "Vcur", il);
  7362. if (model.layers[il].bv) {
  7363. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7364. cb(Vcur, "Vcur", il);
  7365. }
  7366. Qcur = ggml_rope_custom(
  7367. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7368. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7369. ext_factor, attn_factor, beta_fast, beta_slow
  7370. );
  7371. cb(Qcur, "Qcur", il);
  7372. Kcur = ggml_rope_custom(
  7373. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7374. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7375. ext_factor, attn_factor, beta_fast, beta_slow
  7376. );
  7377. cb(Kcur, "Kcur", il);
  7378. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7379. model.layers[il].wo, model.layers[il].bo,
  7380. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7381. }
  7382. if (il == n_layer - 1) {
  7383. // skip computing output for unused tokens
  7384. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7385. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7386. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7387. }
  7388. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7389. cb(ffn_inp, "ffn_inp", il);
  7390. // feed-forward network
  7391. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7392. model.layers[il].ffn_norm, NULL,
  7393. LLM_NORM_RMS, cb, il);
  7394. cb(cur, "ffn_norm", il);
  7395. cur = llm_build_ffn(ctx0, cur,
  7396. model.layers[il].ffn_up, NULL,
  7397. model.layers[il].ffn_gate, NULL,
  7398. model.layers[il].ffn_down, NULL,
  7399. NULL,
  7400. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7401. cb(cur, "ffn_out", il);
  7402. cur = ggml_add(ctx0, cur, ffn_inp);
  7403. cb(cur, "l_out", il);
  7404. // input for next layer
  7405. inpL = cur;
  7406. }
  7407. cur = inpL;
  7408. cur = llm_build_norm(ctx0, cur, hparams,
  7409. model.output_norm, NULL,
  7410. LLM_NORM_RMS, cb, -1);
  7411. cb(cur, "result_norm", -1);
  7412. // lm_head
  7413. cur = ggml_mul_mat(ctx0, model.output, cur);
  7414. cb(cur, "result_output", -1);
  7415. ggml_build_forward_expand(gf, cur);
  7416. return gf;
  7417. }
  7418. // ref: https://arxiv.org/abs/2203.03466
  7419. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7420. // based on the original build_llama() function
  7421. struct ggml_cgraph * build_minicpm() {
  7422. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7423. const int64_t n_embd_head = hparams.n_embd_head_v;
  7424. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7425. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7426. const int64_t n_embd = hparams.n_embd;
  7427. //TODO: if the model varies, these parameters need to be read from the model
  7428. const int64_t n_embd_base = 256;
  7429. const float scale_embd = 12.0f;
  7430. const float scale_depth = 1.4f;
  7431. struct ggml_tensor * cur;
  7432. struct ggml_tensor * inpL;
  7433. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7434. // scale the input embeddings
  7435. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7436. cb(inpL, "inp_scaled", -1);
  7437. // inp_pos - contains the positions
  7438. struct ggml_tensor * inp_pos = build_inp_pos();
  7439. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7440. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7441. for (int il = 0; il < n_layer; ++il) {
  7442. struct ggml_tensor * inpSA = inpL;
  7443. // norm
  7444. cur = llm_build_norm(ctx0, inpL, hparams,
  7445. model.layers[il].attn_norm, NULL,
  7446. LLM_NORM_RMS, cb, il);
  7447. cb(cur, "attn_norm", il);
  7448. // self-attention
  7449. {
  7450. // compute Q and K and RoPE them
  7451. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7452. cb(Qcur, "Qcur", il);
  7453. if (model.layers[il].bq) {
  7454. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7455. cb(Qcur, "Qcur", il);
  7456. }
  7457. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7458. cb(Kcur, "Kcur", il);
  7459. if (model.layers[il].bk) {
  7460. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7461. cb(Kcur, "Kcur", il);
  7462. }
  7463. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7464. cb(Vcur, "Vcur", il);
  7465. if (model.layers[il].bv) {
  7466. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7467. cb(Vcur, "Vcur", il);
  7468. }
  7469. Qcur = ggml_rope_custom(
  7470. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7471. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7472. ext_factor, attn_factor, beta_fast, beta_slow
  7473. );
  7474. cb(Qcur, "Qcur", il);
  7475. Kcur = ggml_rope_custom(
  7476. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7477. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7478. ext_factor, attn_factor, beta_fast, beta_slow
  7479. );
  7480. cb(Kcur, "Kcur", il);
  7481. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7482. model.layers[il].wo, model.layers[il].bo,
  7483. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7484. }
  7485. if (il == n_layer - 1) {
  7486. // skip computing output for unused tokens
  7487. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7488. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7489. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7490. }
  7491. // scale_res - scale the hidden states for residual connection
  7492. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7493. cur = ggml_scale(ctx0, cur, scale_res);
  7494. cb(cur, "hidden_scaled", -1);
  7495. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7496. cb(ffn_inp, "ffn_inp", il);
  7497. // feed-forward network
  7498. {
  7499. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7500. model.layers[il].ffn_norm, NULL,
  7501. LLM_NORM_RMS, cb, il);
  7502. cb(cur, "ffn_norm", il);
  7503. cur = llm_build_ffn(ctx0, cur,
  7504. model.layers[il].ffn_up, NULL,
  7505. model.layers[il].ffn_gate, NULL,
  7506. model.layers[il].ffn_down, NULL,
  7507. NULL,
  7508. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7509. cb(cur, "ffn_out", il);
  7510. }
  7511. // scale the hidden states for residual connection
  7512. cur = ggml_scale(ctx0, cur, scale_res);
  7513. cb(cur, "hidden_scaled_ffn", -1);
  7514. cur = ggml_add(ctx0, cur, ffn_inp);
  7515. cb(cur, "l_out", il);
  7516. // input for next layer
  7517. inpL = cur;
  7518. }
  7519. cur = inpL;
  7520. cur = llm_build_norm(ctx0, cur, hparams,
  7521. model.output_norm, NULL,
  7522. LLM_NORM_RMS, cb, -1);
  7523. cb(cur, "result_norm", -1);
  7524. // lm_head scaling
  7525. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7526. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7527. cb(cur, "lmhead_scaling", -1);
  7528. // lm_head
  7529. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7530. cb(cur, "result_output", -1);
  7531. ggml_build_forward_expand(gf, cur);
  7532. return gf;
  7533. }
  7534. struct ggml_cgraph * build_gemma() {
  7535. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7536. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7537. struct ggml_tensor * cur;
  7538. struct ggml_tensor * inpL;
  7539. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7540. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7541. cb(inpL, "inp_scaled", -1);
  7542. // inp_pos - contains the positions
  7543. struct ggml_tensor * inp_pos = build_inp_pos();
  7544. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7545. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7546. for (int il = 0; il < n_layer; ++il) {
  7547. // norm
  7548. cur = llm_build_norm(ctx0, inpL, hparams,
  7549. model.layers[il].attn_norm, NULL,
  7550. LLM_NORM_RMS, cb, il);
  7551. cb(cur, "attn_norm", il);
  7552. // self-attention
  7553. {
  7554. // compute Q and K and RoPE them
  7555. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7556. cb(Qcur, "Qcur", il);
  7557. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7558. cb(Kcur, "Kcur", il);
  7559. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7560. cb(Vcur, "Vcur", il);
  7561. Qcur = ggml_rope_custom(
  7562. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7563. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7564. ext_factor, attn_factor, beta_fast, beta_slow);
  7565. cb(Qcur, "Qcur", il);
  7566. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7567. cb(Qcur, "Qcur_scaled", il);
  7568. Kcur = ggml_rope_custom(
  7569. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7570. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7571. ext_factor, attn_factor, beta_fast, beta_slow);
  7572. cb(Kcur, "Kcur", il);
  7573. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7574. model.layers[il].wo, NULL,
  7575. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7576. }
  7577. if (il == n_layer - 1) {
  7578. // skip computing output for unused tokens
  7579. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7580. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7581. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7582. }
  7583. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7584. cb(sa_out, "sa_out", il);
  7585. cur = llm_build_norm(ctx0, sa_out, hparams,
  7586. model.layers[il].ffn_norm, NULL,
  7587. LLM_NORM_RMS, cb, il);
  7588. cb(cur, "ffn_norm", il);
  7589. // feed-forward network
  7590. {
  7591. cur = llm_build_ffn(ctx0, cur,
  7592. model.layers[il].ffn_up, NULL,
  7593. model.layers[il].ffn_gate, NULL,
  7594. model.layers[il].ffn_down, NULL,
  7595. NULL,
  7596. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7597. cb(cur, "ffn_out", il);
  7598. }
  7599. cur = ggml_add(ctx0, cur, sa_out);
  7600. cb(cur, "l_out", il);
  7601. // input for next layer
  7602. inpL = cur;
  7603. }
  7604. cur = inpL;
  7605. cur = llm_build_norm(ctx0, cur, hparams,
  7606. model.output_norm, NULL,
  7607. LLM_NORM_RMS, cb, -1);
  7608. cb(cur, "result_norm", -1);
  7609. // lm_head
  7610. cur = ggml_mul_mat(ctx0, model.output, cur);
  7611. cb(cur, "result_output", -1);
  7612. ggml_build_forward_expand(gf, cur);
  7613. return gf;
  7614. }
  7615. struct ggml_cgraph * build_starcoder2() {
  7616. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7617. const int64_t n_embd_head = hparams.n_embd_head_v;
  7618. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7619. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7620. struct ggml_tensor * cur;
  7621. struct ggml_tensor * inpL;
  7622. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7623. // inp_pos - contains the positions
  7624. struct ggml_tensor * inp_pos = build_inp_pos();
  7625. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7626. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7627. for (int il = 0; il < n_layer; ++il) {
  7628. struct ggml_tensor * inpSA = inpL;
  7629. // norm
  7630. cur = llm_build_norm(ctx0, inpL, hparams,
  7631. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7632. LLM_NORM, cb, il);
  7633. cb(cur, "attn_norm", il);
  7634. // self-attention
  7635. {
  7636. // compute Q and K and RoPE them
  7637. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7638. cb(Qcur, "Qcur", il);
  7639. if (model.layers[il].bq) {
  7640. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7641. cb(Qcur, "Qcur", il);
  7642. }
  7643. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7644. cb(Kcur, "Kcur", il);
  7645. if (model.layers[il].bk) {
  7646. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7647. cb(Kcur, "Kcur", il);
  7648. }
  7649. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7650. cb(Vcur, "Vcur", il);
  7651. if (model.layers[il].bv) {
  7652. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7653. cb(Vcur, "Vcur", il);
  7654. }
  7655. Qcur = ggml_rope_custom(
  7656. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7657. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7658. ext_factor, attn_factor, beta_fast, beta_slow
  7659. );
  7660. cb(Qcur, "Qcur", il);
  7661. Kcur = ggml_rope_custom(
  7662. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7663. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7664. ext_factor, attn_factor, beta_fast, beta_slow
  7665. );
  7666. cb(Kcur, "Kcur", il);
  7667. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7668. model.layers[il].wo, model.layers[il].bo,
  7669. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7670. }
  7671. if (il == n_layer - 1) {
  7672. // skip computing output for unused tokens
  7673. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7674. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7675. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7676. }
  7677. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7678. cb(ffn_inp, "ffn_inp", il);
  7679. // feed-forward network
  7680. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7681. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7682. LLM_NORM, cb, il);
  7683. cb(cur, "ffn_norm", il);
  7684. cur = llm_build_ffn(ctx0, cur,
  7685. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7686. NULL, NULL,
  7687. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7688. NULL,
  7689. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7690. cb(cur, "ffn_out", il);
  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, model.output_norm_b,
  7699. LLM_NORM, 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_mamba() {
  7708. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7709. const int64_t d_model = n_embd;
  7710. const int64_t d_conv = hparams.ssm_d_conv;
  7711. const int64_t d_inner = hparams.ssm_d_inner;
  7712. GGML_ASSERT(2 * d_model == d_inner);
  7713. const int64_t d_state = hparams.ssm_d_state;
  7714. const int64_t dt_rank = hparams.ssm_dt_rank;
  7715. struct ggml_tensor * cur;
  7716. struct ggml_tensor * inpL;
  7717. // {n_embd, n_tokens}
  7718. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7719. struct ggml_tensor * state_mask = build_inp_s_mask();
  7720. struct ggml_tensor * state_seq = build_inp_s_seq();
  7721. for (int il = 0; il < n_layer; ++il) {
  7722. // (ab)using the KV cache to store the states
  7723. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7724. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7725. // clear states of sequences which are starting at the beginning of this batch
  7726. {
  7727. conv_states = ggml_mul(ctx0,
  7728. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7729. state_mask);
  7730. ssm_states = ggml_mul(ctx0,
  7731. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7732. state_mask);
  7733. }
  7734. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7735. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7736. // norm
  7737. cur = llm_build_norm(ctx0, inpL, hparams,
  7738. model.layers[il].attn_norm, NULL,
  7739. LLM_NORM_RMS, cb, il);
  7740. cb(cur, "attn_norm", il);
  7741. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7742. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7743. // split the above in two
  7744. // => {d_inner, n_tokens}
  7745. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7746. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7747. // conv
  7748. {
  7749. // Custom operator which is needed only to ease simultaneous sequence processing.
  7750. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7751. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7752. // then element-wise multiply that with the conv1d weigth,
  7753. // then sum the elements of each row,
  7754. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7755. // then permute away the ne[0] dimension,
  7756. // and then you're left with the resulting x tensor.
  7757. // The new conv_states is the last (d_conv - 1) columns
  7758. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7759. // For simultaneous sequences, it's more complicated.
  7760. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7761. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7762. ggml_build_forward_expand(gf,
  7763. ggml_cpy(ctx0,
  7764. 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)),
  7765. 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))));
  7766. // extract x from x_conv
  7767. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7768. // bias
  7769. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7770. x = ggml_silu(ctx0, x);
  7771. }
  7772. // ssm
  7773. {
  7774. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7775. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7776. // split
  7777. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7778. 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);
  7779. 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));
  7780. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7781. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7782. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7783. // Custom operator to optimize the parallel associative scan
  7784. // as described in the Annex D of the Mamba paper.
  7785. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7786. // because only a single tensor can be returned.
  7787. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7788. // store last states (the second part of y_ssm_states)
  7789. ggml_build_forward_expand(gf,
  7790. ggml_cpy(ctx0,
  7791. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7792. 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))));
  7793. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7794. if (il == n_layer - 1) {
  7795. // skip computing output for unused tokens
  7796. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7797. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7798. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7799. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7800. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7801. }
  7802. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7803. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7804. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7805. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7806. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7807. }
  7808. // residual
  7809. cur = ggml_add(ctx0, cur, inpL);
  7810. cb(cur, "l_out", il);
  7811. // input for next layer
  7812. inpL = cur;
  7813. }
  7814. // final rmsnorm
  7815. cur = llm_build_norm(ctx0, inpL, hparams,
  7816. model.output_norm, NULL,
  7817. LLM_NORM_RMS, cb, -1);
  7818. cb(cur, "result_norm", -1);
  7819. // lm_head
  7820. cur = ggml_mul_mat(ctx0, model.output, cur);
  7821. cb(cur, "result_output", -1);
  7822. ggml_build_forward_expand(gf, cur);
  7823. return gf;
  7824. }
  7825. struct ggml_cgraph * build_command_r() {
  7826. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7827. const int64_t n_embd_head = hparams.n_embd_head_v;
  7828. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7829. const float f_logit_scale = hparams.f_logit_scale;
  7830. struct ggml_tensor * cur;
  7831. struct ggml_tensor * inpL;
  7832. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7833. // inp_pos - contains the positions
  7834. struct ggml_tensor * inp_pos = build_inp_pos();
  7835. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7836. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7837. for (int il = 0; il < n_layer; ++il) {
  7838. // norm
  7839. cur = llm_build_norm(ctx0, inpL, hparams,
  7840. model.layers[il].attn_norm, NULL,
  7841. LLM_NORM, cb, il);
  7842. cb(cur, "attn_norm", il);
  7843. struct ggml_tensor * ffn_inp = cur;
  7844. // self-attention
  7845. {
  7846. // compute Q and K and RoPE them
  7847. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7848. cb(Qcur, "Qcur", il);
  7849. if (model.layers[il].bq) {
  7850. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7851. cb(Qcur, "Qcur", il);
  7852. }
  7853. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7854. cb(Kcur, "Kcur", il);
  7855. if (model.layers[il].bk) {
  7856. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7857. cb(Kcur, "Kcur", il);
  7858. }
  7859. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7860. cb(Vcur, "Vcur", il);
  7861. if (model.layers[il].bv) {
  7862. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7863. cb(Vcur, "Vcur", il);
  7864. }
  7865. if (model.layers[il].attn_q_norm) {
  7866. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  7867. ggml_element_size(Qcur) * n_embd_head,
  7868. ggml_element_size(Qcur) * n_embd_head * n_head,
  7869. 0);
  7870. cb(Qcur, "Qcur", il);
  7871. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  7872. ggml_element_size(Kcur) * n_embd_head,
  7873. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  7874. 0);
  7875. cb(Kcur, "Kcur", il);
  7876. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7877. model.layers[il].attn_q_norm,
  7878. NULL,
  7879. LLM_NORM, cb, il);
  7880. cb(Qcur, "Qcur", il);
  7881. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7882. model.layers[il].attn_k_norm,
  7883. NULL,
  7884. LLM_NORM, cb, il);
  7885. cb(Kcur, "Kcur", il);
  7886. }
  7887. Qcur = ggml_rope_custom(
  7888. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7889. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7890. ext_factor, attn_factor, beta_fast, beta_slow
  7891. );
  7892. cb(Qcur, "Qcur", il);
  7893. Kcur = ggml_rope_custom(
  7894. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7895. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7896. ext_factor, attn_factor, beta_fast, beta_slow
  7897. );
  7898. cb(Kcur, "Kcur", il);
  7899. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7900. model.layers[il].wo, model.layers[il].bo,
  7901. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7902. }
  7903. if (il == n_layer - 1) {
  7904. // skip computing output for unused tokens
  7905. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7906. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7907. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7908. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  7909. }
  7910. struct ggml_tensor * attn_out = cur;
  7911. // feed-forward network
  7912. {
  7913. cur = llm_build_ffn(ctx0, ffn_inp,
  7914. model.layers[il].ffn_up, NULL,
  7915. model.layers[il].ffn_gate, NULL,
  7916. model.layers[il].ffn_down, NULL,
  7917. NULL,
  7918. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7919. cb(cur, "ffn_out", il);
  7920. }
  7921. // add together residual + FFN + self-attention
  7922. cur = ggml_add(ctx0, cur, inpL);
  7923. cur = ggml_add(ctx0, cur, attn_out);
  7924. cb(cur, "l_out", il);
  7925. // input for next layer
  7926. inpL = cur;
  7927. }
  7928. cur = inpL;
  7929. cur = llm_build_norm(ctx0, cur, hparams,
  7930. model.output_norm, NULL,
  7931. LLM_NORM, cb, -1);
  7932. cb(cur, "result_norm", -1);
  7933. // lm_head
  7934. cur = ggml_mul_mat(ctx0, model.output, cur);
  7935. if (f_logit_scale) {
  7936. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7937. }
  7938. cb(cur, "result_output", -1);
  7939. ggml_build_forward_expand(gf, cur);
  7940. return gf;
  7941. }
  7942. };
  7943. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7944. llama_batch dummy;
  7945. dummy.n_tokens = 0;
  7946. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7947. struct llm_build_context llm(lctx, dummy, cb, false);
  7948. llm.init();
  7949. struct ggml_cgraph * result = llm.build_defrag(ids);
  7950. llm.free();
  7951. return result;
  7952. }
  7953. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7954. llama_batch dummy;
  7955. dummy.n_tokens = 0;
  7956. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7957. struct llm_build_context llm(lctx, dummy, cb, false);
  7958. llm.init();
  7959. struct ggml_cgraph * result = llm.build_k_shift();
  7960. llm.free();
  7961. return result;
  7962. }
  7963. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7964. llama_batch dummy;
  7965. dummy.n_tokens = 0;
  7966. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7967. struct llm_build_context llm(lctx, dummy, cb, false);
  7968. llm.init();
  7969. struct ggml_cgraph * result = llm.build_s_copy();
  7970. llm.free();
  7971. return result;
  7972. }
  7973. static struct ggml_cgraph * llama_build_graph(
  7974. llama_context & lctx,
  7975. const llama_batch & batch,
  7976. bool worst_case) {
  7977. const auto & model = lctx.model;
  7978. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7979. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7980. if (il >= 0) {
  7981. ggml_format_name(cur, "%s-%d", name, il);
  7982. } else {
  7983. ggml_set_name(cur, name);
  7984. }
  7985. if (!lctx.cparams.offload_kqv) {
  7986. if (strcmp(name, "kqv_merged_cont") == 0) {
  7987. // all nodes between the KV store and the attention output are run on the CPU
  7988. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7989. }
  7990. }
  7991. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7992. // FIXME: fix in ggml_backend_sched
  7993. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7994. if (batch.n_tokens < 32 || full_offload) {
  7995. if (il != -1 && strcmp(name, "norm") == 0) {
  7996. for (auto * backend : lctx.backends) {
  7997. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7998. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7999. break;
  8000. }
  8001. }
  8002. }
  8003. }
  8004. };
  8005. struct ggml_cgraph * result = NULL;
  8006. struct llm_build_context llm(lctx, batch, cb, worst_case);
  8007. llm.init();
  8008. switch (model.arch) {
  8009. case LLM_ARCH_LLAMA:
  8010. {
  8011. result = llm.build_llama();
  8012. } break;
  8013. case LLM_ARCH_BAICHUAN:
  8014. {
  8015. result = llm.build_baichuan();
  8016. } break;
  8017. case LLM_ARCH_FALCON:
  8018. {
  8019. result = llm.build_falcon();
  8020. } break;
  8021. case LLM_ARCH_GROK:
  8022. {
  8023. result = llm.build_grok();
  8024. } break;
  8025. case LLM_ARCH_STARCODER:
  8026. {
  8027. result = llm.build_starcoder();
  8028. } break;
  8029. case LLM_ARCH_PERSIMMON:
  8030. {
  8031. result = llm.build_persimmon();
  8032. } break;
  8033. case LLM_ARCH_REFACT:
  8034. {
  8035. result = llm.build_refact();
  8036. } break;
  8037. case LLM_ARCH_BERT:
  8038. case LLM_ARCH_NOMIC_BERT:
  8039. {
  8040. result = llm.build_bert();
  8041. } break;
  8042. case LLM_ARCH_BLOOM:
  8043. {
  8044. result = llm.build_bloom();
  8045. } break;
  8046. case LLM_ARCH_MPT:
  8047. {
  8048. result = llm.build_mpt();
  8049. } break;
  8050. case LLM_ARCH_STABLELM:
  8051. {
  8052. result = llm.build_stablelm();
  8053. } break;
  8054. case LLM_ARCH_QWEN:
  8055. {
  8056. result = llm.build_qwen();
  8057. } break;
  8058. case LLM_ARCH_QWEN2:
  8059. {
  8060. result = llm.build_qwen2();
  8061. } break;
  8062. case LLM_ARCH_PHI2:
  8063. {
  8064. result = llm.build_phi2();
  8065. } break;
  8066. case LLM_ARCH_PLAMO:
  8067. {
  8068. result = llm.build_plamo();
  8069. } break;
  8070. case LLM_ARCH_GPT2:
  8071. {
  8072. result = llm.build_gpt2();
  8073. } break;
  8074. case LLM_ARCH_CODESHELL:
  8075. {
  8076. result = llm.build_codeshell();
  8077. } break;
  8078. case LLM_ARCH_ORION:
  8079. {
  8080. result = llm.build_orion();
  8081. } break;
  8082. case LLM_ARCH_INTERNLM2:
  8083. {
  8084. result = llm.build_internlm2();
  8085. } break;
  8086. case LLM_ARCH_MINICPM:
  8087. {
  8088. result = llm.build_minicpm();
  8089. } break;
  8090. case LLM_ARCH_GEMMA:
  8091. {
  8092. result = llm.build_gemma();
  8093. } break;
  8094. case LLM_ARCH_STARCODER2:
  8095. {
  8096. result = llm.build_starcoder2();
  8097. } break;
  8098. case LLM_ARCH_MAMBA:
  8099. {
  8100. result = llm.build_mamba();
  8101. } break;
  8102. case LLM_ARCH_XVERSE:
  8103. {
  8104. result = llm.build_xverse();
  8105. } break;
  8106. case LLM_ARCH_COMMAND_R:
  8107. {
  8108. result = llm.build_command_r();
  8109. } break;
  8110. default:
  8111. GGML_ASSERT(false);
  8112. }
  8113. llm.free();
  8114. return result;
  8115. }
  8116. static void llama_set_k_shift(llama_context & lctx) {
  8117. const int64_t kv_size = lctx.kv_self.size;
  8118. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  8119. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  8120. for (int i = 0; i < kv_size; ++i) {
  8121. data[i] = lctx.kv_self.cells[i].delta;
  8122. }
  8123. }
  8124. static void llama_set_s_copy(llama_context & lctx) {
  8125. const int64_t kv_size = lctx.kv_self.size;
  8126. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  8127. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  8128. for (int i = 0; i < kv_size; ++i) {
  8129. data[i] = lctx.kv_self.cells[i].src;
  8130. }
  8131. }
  8132. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  8133. //
  8134. // set input data
  8135. //
  8136. const auto & hparams = lctx.model.hparams;
  8137. const auto & cparams = lctx.cparams;
  8138. const auto & kv_self = lctx.kv_self;
  8139. if (batch.token) {
  8140. const int64_t n_tokens = batch.n_tokens;
  8141. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  8142. }
  8143. if (batch.embd) {
  8144. const int64_t n_embd = hparams.n_embd;
  8145. const int64_t n_tokens = batch.n_tokens;
  8146. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  8147. }
  8148. if (batch.pos && lctx.inp_pos) {
  8149. const int64_t n_tokens = batch.n_tokens;
  8150. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  8151. }
  8152. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8153. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  8154. const int64_t n_tokens = batch.n_tokens;
  8155. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  8156. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  8157. if (lctx.n_outputs == n_tokens) {
  8158. for (int i = 0; i < n_tokens; ++i) {
  8159. data[i] = i;
  8160. }
  8161. } else if (batch.logits) {
  8162. int32_t n_outputs = 0;
  8163. for (int i = 0; i < n_tokens; ++i) {
  8164. if (batch.logits[i]) {
  8165. data[n_outputs++] = i;
  8166. }
  8167. }
  8168. // the graph needs to have been passed the correct number of outputs
  8169. GGML_ASSERT(lctx.n_outputs == n_outputs);
  8170. } else if (lctx.n_outputs == 1) {
  8171. // only keep last output
  8172. data[0] = n_tokens - 1;
  8173. } else {
  8174. GGML_ASSERT(lctx.n_outputs == 0);
  8175. }
  8176. }
  8177. GGML_ASSERT(
  8178. // (!a || b) is a logical implication (a -> b)
  8179. // !hparams.causal_attn -> !cparams.causal_attn
  8180. (hparams.causal_attn || !cparams.causal_attn) &&
  8181. "causal attention with embedding models is not supported"
  8182. );
  8183. if (lctx.inp_KQ_mask) {
  8184. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  8185. if (cparams.causal_attn) {
  8186. const int64_t n_kv = kv_self.n;
  8187. const int64_t n_tokens = batch.n_tokens;
  8188. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8189. float * data = (float *) lctx.inp_KQ_mask->data;
  8190. // For causal attention, use only the previous KV cells
  8191. // of the correct sequence for each token of the batch.
  8192. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  8193. for (int h = 0; h < 1; ++h) {
  8194. for (int j = 0; j < n_tokens; ++j) {
  8195. const llama_pos pos = batch.pos[j];
  8196. const llama_seq_id seq_id = batch.seq_id[j][0];
  8197. for (int i = 0; i < n_kv; ++i) {
  8198. float f;
  8199. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  8200. f = -INFINITY;
  8201. } else {
  8202. f = 0.0f;
  8203. }
  8204. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  8205. }
  8206. }
  8207. }
  8208. } else {
  8209. // when using kv cache, the mask needs to match the kv cache size
  8210. const int64_t n_tokens = batch.n_tokens;
  8211. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  8212. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8213. float * data = (float *) lctx.inp_KQ_mask->data;
  8214. for (int h = 0; h < 1; ++h) {
  8215. for (int j = 0; j < n_tokens; ++j) {
  8216. const llama_seq_id seq_id = batch.seq_id[j][0];
  8217. for (int i = 0; i < n_tokens; ++i) {
  8218. float f = -INFINITY;
  8219. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  8220. if (batch.seq_id[i][s] == seq_id) {
  8221. f = 0.0f;
  8222. break;
  8223. }
  8224. }
  8225. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  8226. }
  8227. for (int i = n_tokens; i < n_stride; ++i) {
  8228. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  8229. }
  8230. }
  8231. }
  8232. }
  8233. }
  8234. if (hparams.need_kq_pos) {
  8235. const int64_t n_kv = kv_self.n;
  8236. GGML_ASSERT(lctx.inp_KQ_pos);
  8237. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  8238. float * data = (float *) lctx.inp_KQ_pos->data;
  8239. for (int i = 0; i < n_kv; ++i) {
  8240. data[i] = float(lctx.kv_self.cells[i].pos);
  8241. }
  8242. }
  8243. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  8244. const int64_t n_tokens = batch.n_tokens;
  8245. GGML_ASSERT(lctx.inp_mean);
  8246. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  8247. float * data = (float *) lctx.inp_mean->data;
  8248. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  8249. std::vector<uint64_t> sum(n_tokens, 0);
  8250. for (int i = 0; i < n_tokens; ++i) {
  8251. const llama_seq_id seq_id = batch.seq_id[i][0];
  8252. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  8253. sum[seq_id] += 1;
  8254. }
  8255. std::vector<float> div(n_tokens, 0.0f);
  8256. for (int i = 0; i < n_tokens; ++i) {
  8257. const uint64_t s = sum[i];
  8258. if (s > 0) {
  8259. div[i] = 1.0f/float(s);
  8260. }
  8261. }
  8262. for (int i = 0; i < n_tokens; ++i) {
  8263. const llama_seq_id seq_id = batch.seq_id[i][0];
  8264. data[seq_id*n_tokens + i] = div[seq_id];
  8265. }
  8266. }
  8267. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  8268. const int64_t n_tokens = batch.n_tokens;
  8269. GGML_ASSERT(lctx.inp_cls);
  8270. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  8271. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  8272. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  8273. for (int i = 0; i < n_tokens; ++i) {
  8274. const llama_seq_id seq_id = batch.seq_id[i][0];
  8275. const llama_pos pos = batch.pos[i];
  8276. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  8277. if (pos == 0) {
  8278. data[seq_id] = i;
  8279. }
  8280. }
  8281. }
  8282. if (kv_self.recurrent) {
  8283. const int64_t n_kv = kv_self.n;
  8284. if (lctx.inp_s_mask) {
  8285. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  8286. float * data = (float *) lctx.inp_s_mask->data;
  8287. // states which are not affected by the current batch are left untouched
  8288. for (int i = 0; i < n_kv; ++i) {
  8289. llama_seq_id seq_id = i + lctx.kv_self.head;
  8290. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  8291. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  8292. data[i] = (float) has_self_seq;
  8293. // ensure current sequences will be kept
  8294. if (!has_self_seq && kv_cell.pos >= 0) {
  8295. kv_cell.seq_id.insert(seq_id);
  8296. }
  8297. }
  8298. }
  8299. // For Mamba (and other recurrent architectures),
  8300. // update the correct state(s)/sequence(s) for each token of the batch.
  8301. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  8302. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  8303. if (lctx.inp_s_seq) {
  8304. const int64_t n_tokens = batch.n_tokens;
  8305. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  8306. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  8307. for (int j = 0; j < n_tokens; ++j) {
  8308. const int32_t n_seq = batch.n_seq_id[j];
  8309. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  8310. for (int i = 0; i < n_kv; ++i) {
  8311. if (i < n_seq) {
  8312. // for this type of model, the head is the minimum seq_id of the batch
  8313. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  8314. } else {
  8315. data[j*n_kv + i] = -1;
  8316. }
  8317. }
  8318. }
  8319. }
  8320. }
  8321. }
  8322. // Make sure enough space is available for outputs.
  8323. // Returns max number of outputs for which space was reserved.
  8324. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  8325. const auto & cparams = lctx.cparams;
  8326. const auto & hparams = lctx.model.hparams;
  8327. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  8328. const auto n_batch = cparams.n_batch;
  8329. const auto n_vocab = hparams.n_vocab;
  8330. const auto n_embd = hparams.n_embd;
  8331. // TODO: use a per-batch flag for logits presence instead
  8332. const bool has_logits = cparams.causal_attn;
  8333. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  8334. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  8335. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8336. if (lctx.output_ids.empty()) {
  8337. // init, never resized afterwards
  8338. lctx.output_ids.resize(n_batch);
  8339. }
  8340. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8341. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8342. // alloc only when more than the current capacity is required
  8343. // TODO: also consider shrinking the buffer
  8344. if (!lctx.buf_output || prev_size < new_size) {
  8345. if (lctx.buf_output) {
  8346. #ifndef NDEBUG
  8347. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8348. 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);
  8349. #endif
  8350. ggml_backend_buffer_free(lctx.buf_output);
  8351. lctx.buf_output = nullptr;
  8352. lctx.logits = nullptr;
  8353. lctx.embd = nullptr;
  8354. }
  8355. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8356. if (lctx.buf_output == nullptr) {
  8357. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8358. return 0;
  8359. }
  8360. }
  8361. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8362. lctx.logits = has_logits ? output_base : nullptr;
  8363. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8364. lctx.output_size = n_outputs_max;
  8365. lctx.logits_size = logits_size;
  8366. lctx.embd_size = embd_size;
  8367. // set all ids as invalid (negative)
  8368. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8369. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8370. lctx.n_outputs = 0;
  8371. return n_outputs_max;
  8372. }
  8373. static void llama_graph_compute(
  8374. llama_context & lctx,
  8375. ggml_cgraph * gf,
  8376. int n_threads) {
  8377. #ifdef GGML_USE_MPI
  8378. const int64_t n_layer = lctx.model.hparams.n_layer;
  8379. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8380. #endif
  8381. #ifdef GGML_USE_METAL
  8382. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8383. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8384. }
  8385. #endif
  8386. if (lctx.backend_cpu != nullptr) {
  8387. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8388. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8389. }
  8390. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8391. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8392. #ifdef GGML_USE_MPI
  8393. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8394. #endif
  8395. }
  8396. // decode a batch of tokens by evaluating the transformer
  8397. //
  8398. // - lctx: llama context
  8399. // - batch: batch to evaluate
  8400. //
  8401. // return 0 on success
  8402. // return positive int on warning
  8403. // return negative int on error
  8404. //
  8405. static int llama_decode_internal(
  8406. llama_context & lctx,
  8407. llama_batch batch_all) { // TODO: rename back to batch
  8408. const uint32_t n_tokens_all = batch_all.n_tokens;
  8409. if (n_tokens_all == 0) {
  8410. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8411. return -1;
  8412. }
  8413. const auto & model = lctx.model;
  8414. const auto & hparams = model.hparams;
  8415. const auto & cparams = lctx.cparams;
  8416. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8417. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8418. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8419. if (lctx.t_compute_start_us == 0) {
  8420. lctx.t_compute_start_us = ggml_time_us();
  8421. }
  8422. lctx.n_queued_tokens += n_tokens_all;
  8423. #ifdef GGML_USE_MPI
  8424. // TODO: needs fix after #3228
  8425. GGML_ASSERT(false && "not implemented");
  8426. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8427. #endif
  8428. auto & kv_self = lctx.kv_self;
  8429. const int64_t n_embd = hparams.n_embd;
  8430. const int64_t n_vocab = hparams.n_vocab;
  8431. uint32_t n_outputs = 0;
  8432. uint32_t n_outputs_prev = 0;
  8433. const auto n_ubatch = cparams.n_ubatch;
  8434. std::vector<llama_pos> pos;
  8435. std::vector<int32_t> n_seq_id;
  8436. std::vector<llama_seq_id *> seq_id_arr;
  8437. std::vector<std::vector<llama_seq_id>> seq_id;
  8438. // count outputs
  8439. if (batch_all.logits) {
  8440. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8441. n_outputs += batch_all.logits[i] != 0;
  8442. }
  8443. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8444. n_outputs = n_tokens_all;
  8445. } else {
  8446. // keep last output only
  8447. n_outputs = 1;
  8448. }
  8449. // reserve output buffer
  8450. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8451. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8452. return -2;
  8453. };
  8454. // set output mappings
  8455. if (batch_all.logits) {
  8456. int32_t i_logits = 0;
  8457. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8458. if (batch_all.logits[i]) {
  8459. lctx.output_ids[i] = i_logits++;
  8460. }
  8461. }
  8462. } else {
  8463. for (uint32_t i = 0; i < n_outputs; ++i) {
  8464. lctx.output_ids[i] = i;
  8465. }
  8466. }
  8467. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8468. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8469. llama_batch u_batch = {
  8470. /* .n_tokens = */ (int32_t) n_tokens,
  8471. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8472. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8473. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8474. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8475. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8476. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8477. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8478. /* .all_pos_1 = */ batch_all.all_pos_1,
  8479. /* .all_seq_id = */ batch_all.all_seq_id,
  8480. };
  8481. // count the outputs in this u_batch
  8482. {
  8483. int32_t n_outputs_new = 0;
  8484. if (u_batch.logits) {
  8485. for (uint32_t i = 0; i < n_tokens; i++) {
  8486. n_outputs_new += u_batch.logits[i] != 0;
  8487. }
  8488. } else if (n_outputs == n_tokens_all) {
  8489. n_outputs_new = n_tokens;
  8490. } else {
  8491. // keep last output only
  8492. if (cur_token + n_tokens >= n_tokens_all) {
  8493. n_outputs_new = 1;
  8494. }
  8495. }
  8496. // needs to happen before the graph is built
  8497. lctx.n_outputs = n_outputs_new;
  8498. }
  8499. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8500. GGML_ASSERT(n_threads > 0);
  8501. // helpers for smoother batch API transition
  8502. // after deprecating the llama_eval calls, these will be removed
  8503. if (u_batch.pos == nullptr) {
  8504. pos.resize(n_tokens);
  8505. for (uint32_t i = 0; i < n_tokens; i++) {
  8506. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8507. }
  8508. u_batch.pos = pos.data();
  8509. }
  8510. if (u_batch.seq_id == nullptr) {
  8511. n_seq_id.resize(n_tokens);
  8512. seq_id.resize(n_tokens);
  8513. seq_id_arr.resize(n_tokens);
  8514. for (uint32_t i = 0; i < n_tokens; i++) {
  8515. n_seq_id[i] = 1;
  8516. seq_id[i].resize(1);
  8517. seq_id[i][0] = u_batch.all_seq_id;
  8518. seq_id_arr[i] = seq_id[i].data();
  8519. }
  8520. u_batch.n_seq_id = n_seq_id.data();
  8521. u_batch.seq_id = seq_id_arr.data();
  8522. }
  8523. // non-causal masks do not use the KV cache
  8524. if (hparams.causal_attn) {
  8525. llama_kv_cache_update(&lctx);
  8526. // if we have enough unused cells before the current head ->
  8527. // better to start searching from the beginning of the cache, hoping to fill it
  8528. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8529. kv_self.head = 0;
  8530. }
  8531. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8532. return 1;
  8533. }
  8534. if (!kv_self.recurrent) {
  8535. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8536. // after enough generations, the benefit from this heuristic disappears
  8537. // if we start defragmenting the cache, the benefit from this will be more important
  8538. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8539. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8540. }
  8541. }
  8542. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8543. ggml_backend_sched_reset(lctx.sched);
  8544. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8545. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8546. // the output is always the last tensor in the graph
  8547. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8548. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8549. if (lctx.n_outputs == 0) {
  8550. // no output
  8551. res = nullptr;
  8552. embd = nullptr;
  8553. } else if (!hparams.causal_attn) {
  8554. res = nullptr; // do not extract logits for embedding models such as BERT
  8555. // token or sequence embeddings
  8556. embd = gf->nodes[gf->n_nodes - 1];
  8557. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8558. } else if (cparams.embeddings) {
  8559. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8560. int i_embd = gf->n_nodes - 2;
  8561. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8562. i_embd = gf->n_nodes - i;
  8563. if (i_embd < 0) { break; }
  8564. embd = gf->nodes[i_embd];
  8565. }
  8566. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8567. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8568. if (!cparams.causal_attn) {
  8569. res = nullptr; // do not extract logits when not needed
  8570. // skip computing logits
  8571. // TODO: is this safe?
  8572. gf->n_nodes = i_embd + 1;
  8573. }
  8574. } else {
  8575. embd = nullptr; // do not extract embeddings when not needed
  8576. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8577. }
  8578. // 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);
  8579. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8580. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8581. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8582. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8583. // with the BLAS calls. need a better solution
  8584. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8585. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8586. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8587. n_threads = std::min(4, n_threads);
  8588. }
  8589. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8590. llama_set_inputs(lctx, u_batch);
  8591. llama_graph_compute(lctx, gf, n_threads);
  8592. // update the kv ring buffer
  8593. {
  8594. kv_self.head += n_tokens;
  8595. // Ensure kv cache head points to a valid index.
  8596. if (kv_self.head >= kv_self.size) {
  8597. kv_self.head = 0;
  8598. }
  8599. }
  8600. #ifdef GGML_PERF
  8601. // print timing information per ggml operation (for debugging purposes)
  8602. // requires GGML_PERF to be defined
  8603. ggml_graph_print(gf);
  8604. #endif
  8605. // plot the computation graph in dot format (for debugging purposes)
  8606. //if (n_past%100 == 0) {
  8607. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8608. //}
  8609. // extract logits
  8610. if (res) {
  8611. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8612. GGML_ASSERT(backend_res != nullptr);
  8613. GGML_ASSERT(lctx.logits != nullptr);
  8614. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8615. const int32_t n_outputs_new = lctx.n_outputs;
  8616. if (n_outputs_new) {
  8617. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8618. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8619. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8620. }
  8621. }
  8622. // extract embeddings
  8623. if (embd) {
  8624. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8625. GGML_ASSERT(backend_embd != nullptr);
  8626. switch (cparams.pooling_type) {
  8627. case LLAMA_POOLING_TYPE_NONE:
  8628. {
  8629. // extract token embeddings
  8630. GGML_ASSERT(lctx.embd != nullptr);
  8631. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8632. const int32_t n_outputs_new = lctx.n_outputs;
  8633. if (n_outputs_new) {
  8634. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8635. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8636. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8637. }
  8638. } break;
  8639. case LLAMA_POOLING_TYPE_CLS:
  8640. case LLAMA_POOLING_TYPE_MEAN:
  8641. {
  8642. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8643. // extract sequence embeddings
  8644. auto & embd_seq_out = lctx.embd_seq;
  8645. embd_seq_out.clear();
  8646. for (uint32_t i = 0; i < n_tokens; i++) {
  8647. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8648. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8649. continue;
  8650. }
  8651. embd_seq_out[seq_id].resize(n_embd);
  8652. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8653. }
  8654. } break;
  8655. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8656. {
  8657. GGML_ASSERT(false && "unknown pooling type");
  8658. } break;
  8659. }
  8660. }
  8661. n_outputs_prev += lctx.n_outputs;
  8662. }
  8663. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  8664. lctx.n_outputs = n_outputs;
  8665. // wait for the computation to finish (automatically done when obtaining the model output)
  8666. //llama_synchronize(&lctx);
  8667. // decide if we need to defrag the kv cache
  8668. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8669. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8670. // queue defragmentation for next llama_kv_cache_update
  8671. if (fragmentation > cparams.defrag_thold) {
  8672. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8673. llama_kv_cache_defrag(kv_self);
  8674. }
  8675. }
  8676. return 0;
  8677. }
  8678. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8679. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8680. auto & kv_self = lctx.kv_self;
  8681. const auto & hparams = lctx.model.hparams;
  8682. const uint32_t n_layer = hparams.n_layer;
  8683. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8684. const uint32_t n_used = kv_self.used;
  8685. assert(n_used <= n_kv);
  8686. //const int64_t t_start = ggml_time_us();
  8687. // number of cells moved
  8688. uint32_t n_moves = 0;
  8689. // each move requires 6*n_layer tensors (see build_defrag)
  8690. // - source view, destination view, copy operation
  8691. // - x2 for keys and values
  8692. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8693. // determine which KV cells to move where
  8694. //
  8695. // cell i moves to ids[i]
  8696. //
  8697. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8698. //
  8699. std::vector<uint32_t> ids(n_kv, n_kv);
  8700. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8701. const auto & cell0 = kv_self.cells[i0];
  8702. if (!cell0.is_empty()) {
  8703. ids[i0] = i0;
  8704. continue;
  8705. }
  8706. // found a hole - fill it with data from the end of the cache
  8707. uint32_t nh = 1;
  8708. // determine the size of the hole
  8709. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8710. nh++;
  8711. }
  8712. uint32_t nf = 0;
  8713. uint32_t is = n_kv - 1;
  8714. // starting from the end, find nh non-empty cells
  8715. for (; is > i0; --is) {
  8716. const auto & cell1 = kv_self.cells[is];
  8717. if (cell1.is_empty() || ids[is] != n_kv) {
  8718. continue;
  8719. }
  8720. // non-empty cell which is not yet moved
  8721. nf++;
  8722. if (nf == nh) {
  8723. break;
  8724. }
  8725. }
  8726. // this can only happen if `n_used` is not accurate, which would be a bug
  8727. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8728. nf = 0;
  8729. uint32_t i1 = is;
  8730. // are we moving a continuous block of memory?
  8731. bool cont = false;
  8732. // should we stop searching for the next move?
  8733. bool stop = false;
  8734. // go back and move the nf cells to the hole
  8735. for (; i1 < n_kv; ++i1) {
  8736. auto & cell1 = kv_self.cells[i1];
  8737. if (cell1.is_empty() || ids[i1] != n_kv) {
  8738. if (n_moves == max_moves) {
  8739. stop = true;
  8740. break;
  8741. }
  8742. cont = false;
  8743. continue;
  8744. }
  8745. // this cell goes to (i0 + nf)
  8746. ids[i1] = i0 + nf;
  8747. // move the cell meta data
  8748. kv_self.cells[i0 + nf] = cell1;
  8749. // clear the old cell and move the head there
  8750. cell1 = llama_kv_cell();
  8751. kv_self.head = n_used;
  8752. if (!cont) {
  8753. n_moves++;
  8754. cont = true;
  8755. }
  8756. nf++;
  8757. if (nf == nh) {
  8758. break;
  8759. }
  8760. }
  8761. if (stop || n_moves == max_moves) {
  8762. break;
  8763. }
  8764. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8765. i0 += nh - 1;
  8766. }
  8767. if (n_moves == 0) {
  8768. return;
  8769. }
  8770. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8771. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8772. #if 0
  8773. // CPU defrag
  8774. //
  8775. // TODO: optimizations are possible:
  8776. // - multiple threads
  8777. // - avoid copying to the host memory when already there
  8778. //
  8779. // likely not worth the effort, as we have ggml_graph based defrag
  8780. //
  8781. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8782. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8783. const uint32_t kv_size = kv_self.size;
  8784. std::vector<uint8_t> buf_k;
  8785. std::vector<uint8_t> buf_v;
  8786. for (uint32_t il = 0; il < n_layer; ++il) {
  8787. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8788. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8789. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8790. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8791. buf_k.resize(k_size);
  8792. buf_v.resize(v_size);
  8793. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8794. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8795. // batch move [i, i+nm) to [id, id+nm)
  8796. // note: cells can move only to a lower index
  8797. for (uint32_t i = 0; i < n_kv; ++i) {
  8798. const uint32_t id = ids[i];
  8799. if (i == id || id == n_kv) {
  8800. continue;
  8801. }
  8802. uint32_t nm = 1;
  8803. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8804. nm++;
  8805. }
  8806. // move keys
  8807. {
  8808. const int64_t os = i*k_size_row;
  8809. const int64_t od = id*k_size_row;
  8810. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8811. }
  8812. // move values (note: they are transposed)
  8813. {
  8814. const int64_t os = i;
  8815. const int64_t od = id;
  8816. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8817. 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);
  8818. }
  8819. }
  8820. i += nm - 1;
  8821. }
  8822. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8823. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8824. }
  8825. #else
  8826. // ggml_graph defrag
  8827. ggml_backend_sched_reset(lctx.sched);
  8828. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8829. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8830. #endif
  8831. //const int64_t t_end = ggml_time_us();
  8832. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8833. }
  8834. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8835. bool need_reserve = false;
  8836. // apply K-shift if needed
  8837. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8838. {
  8839. ggml_backend_sched_reset(lctx.sched);
  8840. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8841. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8842. llama_set_k_shift(lctx);
  8843. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8844. need_reserve = true;
  8845. }
  8846. {
  8847. auto & kv_self = lctx.kv_self;
  8848. kv_self.has_shift = false;
  8849. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8850. kv_self.cells[i].delta = 0;
  8851. }
  8852. }
  8853. }
  8854. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8855. {
  8856. ggml_backend_sched_reset(lctx.sched);
  8857. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8858. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8859. llama_set_s_copy(lctx);
  8860. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8861. need_reserve = true;
  8862. }
  8863. {
  8864. auto & kv_self = lctx.kv_self;
  8865. kv_self.do_copy = false;
  8866. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8867. kv_self.cells[i].src = i;
  8868. }
  8869. }
  8870. }
  8871. // defragment the KV cache if needed
  8872. if (lctx.kv_self.do_defrag) {
  8873. llama_kv_cache_defrag_internal(lctx);
  8874. need_reserve = true;
  8875. lctx.kv_self.do_defrag = false;
  8876. }
  8877. // reserve a worst case graph again
  8878. if (need_reserve) {
  8879. // TODO: extract to a function
  8880. // build worst-case graph
  8881. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8882. int n_past = lctx.cparams.n_ctx - n_tokens;
  8883. 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
  8884. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8885. // initialize scheduler with the worst-case graph
  8886. ggml_backend_sched_reset(lctx.sched);
  8887. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8888. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8889. }
  8890. }
  8891. }
  8892. //
  8893. // tokenizer
  8894. //
  8895. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8896. return vocab.type;
  8897. }
  8898. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8899. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8900. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8901. }
  8902. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8903. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8904. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8905. }
  8906. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8907. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8908. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8909. }
  8910. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8911. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8912. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8913. }
  8914. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8915. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8916. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8917. }
  8918. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8919. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8920. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8921. const auto& token_data = vocab.id_to_token.at(id);
  8922. switch (llama_vocab_get_type(vocab)) {
  8923. case LLAMA_VOCAB_TYPE_SPM: {
  8924. auto buf = token_data.text.substr(3, 2);
  8925. return strtol(buf.c_str(), NULL, 16);
  8926. }
  8927. case LLAMA_VOCAB_TYPE_BPE: {
  8928. GGML_ASSERT(false);
  8929. return unicode_utf8_to_byte(token_data.text);
  8930. }
  8931. case LLAMA_VOCAB_TYPE_WPM: {
  8932. GGML_ASSERT(false);
  8933. }
  8934. default:
  8935. GGML_ASSERT(false);
  8936. }
  8937. }
  8938. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8939. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8940. static const char * hex = "0123456789ABCDEF";
  8941. switch (llama_vocab_get_type(vocab)) {
  8942. case LLAMA_VOCAB_TYPE_SPM: {
  8943. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8944. auto token = vocab.token_to_id.find(buf);
  8945. if (token != vocab.token_to_id.end()) {
  8946. return (*token).second;
  8947. }
  8948. // Try to fall back to just the byte as a string
  8949. const char buf2[2] = { (char)ch, 0 };
  8950. return vocab.token_to_id.at(buf2);
  8951. }
  8952. case LLAMA_VOCAB_TYPE_WPM:
  8953. case LLAMA_VOCAB_TYPE_BPE: {
  8954. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8955. }
  8956. default:
  8957. GGML_ASSERT(false);
  8958. }
  8959. }
  8960. static void llama_escape_whitespace(std::string & text) {
  8961. replace_all(text, " ", "\xe2\x96\x81");
  8962. }
  8963. static void llama_unescape_whitespace(std::string & word) {
  8964. replace_all(word, "\xe2\x96\x81", " ");
  8965. }
  8966. struct llm_symbol {
  8967. using index = int;
  8968. index prev;
  8969. index next;
  8970. const char * text;
  8971. size_t n;
  8972. };
  8973. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8974. // SPM tokenizer
  8975. // original implementation:
  8976. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8977. struct llm_bigram_spm {
  8978. struct comparator {
  8979. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8980. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8981. }
  8982. };
  8983. using queue_storage = std::vector<llm_bigram_spm>;
  8984. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8985. llm_symbol::index left;
  8986. llm_symbol::index right;
  8987. float score;
  8988. size_t size;
  8989. };
  8990. struct llm_tokenizer_spm {
  8991. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8992. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8993. // split string into utf8 chars
  8994. int index = 0;
  8995. size_t offs = 0;
  8996. while (offs < text.size()) {
  8997. llm_symbol sym;
  8998. size_t len = utf8_len(text[offs]);
  8999. sym.text = text.c_str() + offs;
  9000. sym.n = std::min(len, text.size() - offs);
  9001. offs += sym.n;
  9002. sym.prev = index - 1;
  9003. sym.next = offs == text.size() ? -1 : index + 1;
  9004. index++;
  9005. symbols.emplace_back(sym);
  9006. }
  9007. // seed the work queue with all possible 2-character tokens.
  9008. for (size_t i = 1; i < symbols.size(); ++i) {
  9009. try_add_bigram(i - 1, i);
  9010. }
  9011. // keep substituting the highest frequency pairs for as long as we can.
  9012. while (!work_queue.empty()) {
  9013. auto bigram = work_queue.top();
  9014. work_queue.pop();
  9015. auto & left_sym = symbols[bigram.left];
  9016. auto & right_sym = symbols[bigram.right];
  9017. // if one of the symbols already got merged, skip it.
  9018. if (left_sym.n == 0 || right_sym.n == 0 ||
  9019. left_sym.n + right_sym.n != bigram.size) {
  9020. continue;
  9021. }
  9022. // merge the right sym into the left one
  9023. left_sym.n += right_sym.n;
  9024. right_sym.n = 0;
  9025. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  9026. // remove the right sym from the chain
  9027. left_sym.next = right_sym.next;
  9028. if (right_sym.next >= 0) {
  9029. symbols[right_sym.next].prev = bigram.left;
  9030. }
  9031. // find more substitutions
  9032. try_add_bigram(left_sym.prev, bigram.left);
  9033. try_add_bigram(bigram.left, left_sym.next);
  9034. }
  9035. for (int i = 0; i != -1; i = symbols[i].next) {
  9036. auto & symbol = symbols[i];
  9037. resegment(symbol, output);
  9038. }
  9039. }
  9040. private:
  9041. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  9042. auto text = std::string(symbol.text, symbol.n);
  9043. auto token = vocab.token_to_id.find(text);
  9044. // Do we need to support is_unused?
  9045. if (token != vocab.token_to_id.end()) {
  9046. output.push_back((*token).second);
  9047. return;
  9048. }
  9049. const auto p = rev_merge.find(text);
  9050. if (p == rev_merge.end()) {
  9051. // output any symbols that did not form tokens as bytes.
  9052. output.reserve(output.size() + symbol.n);
  9053. for (int j = 0; j < (int)symbol.n; ++j) {
  9054. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  9055. output.push_back(token_id);
  9056. }
  9057. return;
  9058. }
  9059. resegment(symbols[p->second.first], output);
  9060. resegment(symbols[p->second.second], output);
  9061. }
  9062. void try_add_bigram(int left, int right) {
  9063. if (left == -1 || right == -1) {
  9064. return;
  9065. }
  9066. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  9067. auto token = vocab.token_to_id.find(text);
  9068. if (token == vocab.token_to_id.end()) {
  9069. return;
  9070. }
  9071. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  9072. return;
  9073. }
  9074. const auto & tok_data = vocab.id_to_token[(*token).second];
  9075. llm_bigram_spm bigram;
  9076. bigram.left = left;
  9077. bigram.right = right;
  9078. bigram.score = tok_data.score;
  9079. bigram.size = text.size();
  9080. work_queue.push(bigram);
  9081. // Do we need to support is_unused?
  9082. rev_merge[text] = std::make_pair(left, right);
  9083. }
  9084. const llama_vocab & vocab;
  9085. std::vector<llm_symbol> symbols;
  9086. llm_bigram_spm::queue work_queue;
  9087. std::map<std::string, std::pair<int, int>> rev_merge;
  9088. };
  9089. // BPE tokenizer
  9090. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  9091. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  9092. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  9093. struct llm_bigram_bpe {
  9094. struct comparator {
  9095. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  9096. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  9097. }
  9098. };
  9099. using queue_storage = std::vector<llm_bigram_bpe>;
  9100. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  9101. llm_symbol::index left;
  9102. llm_symbol::index right;
  9103. std::string text;
  9104. int rank;
  9105. size_t size;
  9106. };
  9107. struct llm_tokenizer_bpe {
  9108. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  9109. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9110. int final_prev_index = -1;
  9111. auto word_collection = bpe_gpt2_preprocess(text);
  9112. symbols_final.clear();
  9113. for (auto & word : word_collection) {
  9114. work_queue = llm_bigram_bpe::queue();
  9115. symbols.clear();
  9116. int index = 0;
  9117. size_t offset = 0;
  9118. while (offset < word.size()) {
  9119. llm_symbol sym;
  9120. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  9121. sym.text = word.c_str() + offset;
  9122. sym.n = char_len;
  9123. offset += sym.n;
  9124. sym.prev = index - 1;
  9125. sym.next = offset == word.size() ? -1 : index + 1;
  9126. index++;
  9127. symbols.emplace_back(sym);
  9128. }
  9129. for (size_t i = 1; i < symbols.size(); ++i) {
  9130. add_new_bigram(i - 1, i);
  9131. }
  9132. // build token(s)
  9133. while (!work_queue.empty()) {
  9134. auto bigram = work_queue.top();
  9135. work_queue.pop();
  9136. auto & left_symbol = symbols[bigram.left];
  9137. auto & right_symbol = symbols[bigram.right];
  9138. if (left_symbol.n == 0 || right_symbol.n == 0) {
  9139. continue;
  9140. }
  9141. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  9142. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  9143. if (left_token + right_token != bigram.text) {
  9144. continue; // Skip this bigram if it's outdated
  9145. }
  9146. // merge the right sym into the left one
  9147. left_symbol.n += right_symbol.n;
  9148. right_symbol.n = 0;
  9149. // remove the right sym from the chain
  9150. left_symbol.next = right_symbol.next;
  9151. if (right_symbol.next >= 0) {
  9152. symbols[right_symbol.next].prev = bigram.left;
  9153. }
  9154. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  9155. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  9156. }
  9157. // add the finished tokens to the final list keeping correct order for next and prev
  9158. for (auto & sym : symbols) {
  9159. if (sym.n > 0) {
  9160. sym.prev = final_prev_index;
  9161. sym.next = -1;
  9162. if (final_prev_index != -1) {
  9163. symbols_final[final_prev_index].next = symbols_final.size();
  9164. }
  9165. symbols_final.emplace_back(sym);
  9166. final_prev_index = symbols_final.size() - 1;
  9167. }
  9168. }
  9169. }
  9170. symbols = symbols_final;
  9171. if (!symbols.empty()) {
  9172. for (int i = 0; i != -1; i = symbols[i].next) {
  9173. auto & symbol = symbols[i];
  9174. if (symbol.n == 0) {
  9175. continue;
  9176. }
  9177. const std::string str = std::string(symbol.text, symbol.n);
  9178. const auto token = vocab.token_to_id.find(str);
  9179. if (token == vocab.token_to_id.end()) {
  9180. for (auto j = str.begin(); j != str.end(); ++j) {
  9181. std::string byte_str(1, *j);
  9182. auto token_multibyte = vocab.token_to_id.find(byte_str);
  9183. if (token_multibyte == vocab.token_to_id.end()) {
  9184. throw std::runtime_error("ERROR: byte not found in vocab");
  9185. }
  9186. output.push_back((*token_multibyte).second);
  9187. }
  9188. } else {
  9189. output.push_back((*token).second);
  9190. }
  9191. }
  9192. }
  9193. }
  9194. private:
  9195. void add_new_bigram(int left, int right) {
  9196. if (left == -1 || right == -1) {
  9197. return;
  9198. }
  9199. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  9200. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  9201. int rank_found = -1;
  9202. rank_found = vocab.find_bpe_rank(left_token, right_token);
  9203. if (rank_found < 0) {
  9204. return;
  9205. }
  9206. llm_bigram_bpe bigram;
  9207. bigram.left = left;
  9208. bigram.right = right;
  9209. bigram.text = left_token + right_token;
  9210. bigram.size = left_token.size() + right_token.size();
  9211. bigram.rank = rank_found;
  9212. work_queue.push(bigram);
  9213. }
  9214. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  9215. std::vector<std::string> bpe_words;
  9216. std::vector<std::string> bpe_encoded_words;
  9217. std::string token = "";
  9218. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  9219. bool collecting_numeric = false;
  9220. bool collecting_letter = false;
  9221. bool collecting_special = false;
  9222. bool collecting_whitespace_lookahead = false;
  9223. bool collecting = false;
  9224. std::vector<std::string> text_utf;
  9225. text_utf.reserve(text.size());
  9226. bpe_words.reserve(text.size());
  9227. bpe_encoded_words.reserve(text.size());
  9228. const auto cpts = unicode_cpts_from_utf8(text);
  9229. for (size_t i = 0; i < cpts.size(); ++i)
  9230. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  9231. for (int i = 0; i < (int)text_utf.size(); i++) {
  9232. const std::string & utf_char = text_utf[i];
  9233. bool split_condition = false;
  9234. int bytes_remain = text_utf.size() - i;
  9235. // forward backward lookups
  9236. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  9237. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  9238. // handling contractions
  9239. if (!split_condition && bytes_remain >= 2) {
  9240. // 's|'t|'m|'d
  9241. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  9242. split_condition = true;
  9243. }
  9244. if (split_condition) {
  9245. if (token.size()) {
  9246. bpe_words.emplace_back(token); // push previous content as token
  9247. }
  9248. token = utf_char + utf_char_next;
  9249. bpe_words.emplace_back(token);
  9250. token = "";
  9251. i++;
  9252. continue;
  9253. }
  9254. }
  9255. if (!split_condition && bytes_remain >= 3) {
  9256. // 're|'ve|'ll
  9257. if (utf_char == "\'" && (
  9258. (utf_char_next == "r" && utf_char_next_next == "e") ||
  9259. (utf_char_next == "v" && utf_char_next_next == "e") ||
  9260. (utf_char_next == "l" && utf_char_next_next == "l"))
  9261. ) {
  9262. split_condition = true;
  9263. }
  9264. if (split_condition) {
  9265. // current token + next token can be defined
  9266. if (token.size()) {
  9267. bpe_words.emplace_back(token); // push previous content as token
  9268. }
  9269. token = utf_char + utf_char_next + utf_char_next_next;
  9270. bpe_words.emplace_back(token); // the contraction
  9271. token = "";
  9272. i += 2;
  9273. continue;
  9274. }
  9275. }
  9276. if (!split_condition && !collecting) {
  9277. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  9278. collecting_letter = true;
  9279. collecting = true;
  9280. }
  9281. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9282. collecting_numeric = true;
  9283. collecting = true;
  9284. }
  9285. else if (
  9286. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  9287. (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  9288. ) {
  9289. collecting_special = true;
  9290. collecting = true;
  9291. }
  9292. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  9293. collecting_whitespace_lookahead = true;
  9294. collecting = true;
  9295. }
  9296. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  9297. split_condition = true;
  9298. }
  9299. }
  9300. else if (!split_condition && collecting) {
  9301. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  9302. split_condition = true;
  9303. }
  9304. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  9305. split_condition = true;
  9306. }
  9307. else if (collecting_special && (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  9308. split_condition = true;
  9309. }
  9310. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9311. split_condition = true;
  9312. }
  9313. }
  9314. if (utf_char_next == "") {
  9315. split_condition = true; // final
  9316. token += utf_char;
  9317. }
  9318. if (split_condition) {
  9319. if (token.size()) {
  9320. bpe_words.emplace_back(token);
  9321. }
  9322. token = utf_char;
  9323. collecting = false;
  9324. collecting_letter = false;
  9325. collecting_numeric = false;
  9326. collecting_special = false;
  9327. collecting_whitespace_lookahead = false;
  9328. }
  9329. else {
  9330. token += utf_char;
  9331. }
  9332. }
  9333. for (std::string & word : bpe_words) {
  9334. std::string encoded_token = "";
  9335. for (char & c : word) {
  9336. encoded_token += unicode_byte_to_utf8(c);
  9337. }
  9338. bpe_encoded_words.emplace_back(encoded_token);
  9339. }
  9340. return bpe_encoded_words;
  9341. }
  9342. const llama_vocab & vocab;
  9343. std::vector<llm_symbol> symbols;
  9344. std::vector<llm_symbol> symbols_final;
  9345. llm_bigram_bpe::queue work_queue;
  9346. };
  9347. struct llm_tokenizer_wpm {
  9348. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9349. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9350. auto * token_map = &vocab.token_to_id;
  9351. // normalize and split by whitespace
  9352. std::vector<std::string> words = preprocess(text);
  9353. // bos token prepended already
  9354. // find the longest tokens that form the words
  9355. for (const std::string &word : words) {
  9356. // skip empty words
  9357. if (word.size() == 0) {
  9358. continue;
  9359. }
  9360. // prepend phantom space
  9361. std::string word1 = "\xe2\x96\x81" + word;
  9362. int n = word1.size();
  9363. // we're at the start of a new word
  9364. int i = 0;
  9365. bool match_any = false;
  9366. // move through character position in word
  9367. while (i < n) {
  9368. // loop through possible match length
  9369. bool match = false;
  9370. for (int j = n; j > i; j--) {
  9371. auto it = token_map->find(word1.substr(i, j - i));
  9372. if (it != token_map->end()) {
  9373. output.push_back(it->second);
  9374. match = true;
  9375. match_any = true;
  9376. i = j;
  9377. break;
  9378. }
  9379. }
  9380. // must be an unknown character
  9381. if (!match) {
  9382. i++;
  9383. }
  9384. }
  9385. // we didn't find any matches for this word
  9386. if (!match_any) {
  9387. output.push_back(vocab.special_unk_id);
  9388. }
  9389. }
  9390. }
  9391. std::vector<std::string> preprocess(const std::string & text) {
  9392. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9393. // strip accents, strip control, uniformize whitespace,
  9394. // to lowercase, pad chinese characters, pad punctuation
  9395. std::string new_str = "";
  9396. for (uint32_t code : cpts_nfd) {
  9397. int type = unicode_cpt_type(code);
  9398. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9399. continue;
  9400. }
  9401. code = unicode_tolower(code);
  9402. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9403. code = ' ';
  9404. }
  9405. std::string s = unicode_cpt_to_utf8(code);
  9406. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9407. new_str += " ";
  9408. new_str += s;
  9409. new_str += " ";
  9410. } else {
  9411. new_str += s;
  9412. }
  9413. }
  9414. // split by whitespace
  9415. uint64_t l = 0;
  9416. uint64_t r = 0;
  9417. std::vector<std::string> words;
  9418. while (r < new_str.size()) {
  9419. // if is whitespace
  9420. if (isspace(new_str[r], std::locale::classic())) {
  9421. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9422. l = r + 1;
  9423. r = l;
  9424. } else {
  9425. r += 1;
  9426. }
  9427. }
  9428. if (r > l) {
  9429. words.push_back(new_str.substr(l, (r - l)));
  9430. }
  9431. return words;
  9432. }
  9433. bool is_ascii_punct(uint32_t code) {
  9434. if (code > 0xFF) {
  9435. return false;
  9436. }
  9437. auto c = char(static_cast<unsigned char>(code));
  9438. return ispunct(c, std::locale::classic());
  9439. }
  9440. bool is_chinese_char(uint32_t cpt) {
  9441. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9442. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9443. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9444. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9445. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9446. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9447. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9448. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9449. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9450. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9451. return true; // NOLINT
  9452. }
  9453. return false;
  9454. }
  9455. const llama_vocab & vocab;
  9456. };
  9457. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9458. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9459. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9460. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9461. struct fragment_buffer_variant {
  9462. fragment_buffer_variant(llama_vocab::id _token)
  9463. :
  9464. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9465. token(_token),
  9466. raw_text(_dummy),
  9467. offset(0),
  9468. length(0) {}
  9469. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9470. :
  9471. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9472. token((llama_vocab::id) - 1),
  9473. raw_text(_raw_text),
  9474. offset(_offset),
  9475. length(_length){
  9476. GGML_ASSERT(_offset >= 0);
  9477. GGML_ASSERT(_length >= 1);
  9478. GGML_ASSERT(offset + length <= raw_text.length());
  9479. }
  9480. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9481. const llama_vocab::id token;
  9482. const std::string _dummy;
  9483. const std::string & raw_text;
  9484. const uint64_t offset;
  9485. const uint64_t length;
  9486. };
  9487. // #define PRETOKENIZERDEBUG
  9488. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9489. // for each special token
  9490. for (const auto & st: vocab.special_tokens_cache) {
  9491. const auto & special_token = st.first;
  9492. const auto & special_id = st.second;
  9493. // for each text fragment
  9494. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9495. while (it != buffer.end()) {
  9496. auto & fragment = (*it);
  9497. // if a fragment is text ( not yet processed )
  9498. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9499. auto * raw_text = &(fragment.raw_text);
  9500. auto raw_text_base_offset = fragment.offset;
  9501. auto raw_text_base_length = fragment.length;
  9502. // loop over the text
  9503. while (true) {
  9504. // find the first occurrence of a given special token in this fragment
  9505. // passing offset argument only limit the "search area" but match coordinates
  9506. // are still relative to the source full raw_text
  9507. auto match = raw_text->find(special_token, raw_text_base_offset);
  9508. // no occurrences found, stop processing this fragment for a given special token
  9509. if (match == std::string::npos) break;
  9510. // check if match is within bounds of offset <-> length
  9511. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9512. #ifdef PRETOKENIZERDEBUG
  9513. 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());
  9514. #endif
  9515. auto source = std::distance(buffer.begin(), it);
  9516. // if match is further than base offset
  9517. // then we have some text to the left of it
  9518. if (match > raw_text_base_offset) {
  9519. // left
  9520. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9521. const int64_t left_reminder_length = match - raw_text_base_offset;
  9522. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9523. #ifdef PRETOKENIZERDEBUG
  9524. 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());
  9525. #endif
  9526. it++;
  9527. }
  9528. // special token
  9529. buffer.emplace_after(it, special_id);
  9530. it++;
  9531. // right
  9532. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9533. const int64_t right_reminder_offset = match + special_token.length();
  9534. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9535. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9536. #ifdef PRETOKENIZERDEBUG
  9537. 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());
  9538. #endif
  9539. it++;
  9540. if (source == 0) {
  9541. buffer.erase_after(buffer.before_begin());
  9542. } else {
  9543. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9544. }
  9545. // repeat for the right side
  9546. raw_text_base_offset = right_reminder_offset;
  9547. raw_text_base_length = right_reminder_length;
  9548. #ifdef PRETOKENIZERDEBUG
  9549. 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());
  9550. #endif
  9551. } else {
  9552. if (source == 0) {
  9553. buffer.erase_after(buffer.before_begin());
  9554. } else {
  9555. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9556. }
  9557. break;
  9558. }
  9559. }
  9560. }
  9561. it++;
  9562. }
  9563. }
  9564. }
  9565. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special) {
  9566. std::vector<llama_vocab::id> output;
  9567. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9568. if (!raw_text.empty()) {
  9569. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9570. if (parse_special) tokenizer_st_partition(vocab, fragment_buffer);
  9571. }
  9572. switch (vocab.type) {
  9573. case LLAMA_VOCAB_TYPE_SPM:
  9574. {
  9575. // OG tokenizer behavior:
  9576. //
  9577. // tokenizer.encode('', add_special_tokens=True) returns [1]
  9578. // tokenizer.encode('', add_special_tokens=False) returns []
  9579. if (add_special && vocab.special_add_bos != 0) {
  9580. GGML_ASSERT(vocab.special_bos_id != -1);
  9581. output.push_back(vocab.special_bos_id);
  9582. }
  9583. for (const auto & fragment : fragment_buffer) {
  9584. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9585. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9586. // TODO: It's likely possible to get rid of this string copy entirely
  9587. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9588. // and passing 'add space prefix' as bool argument
  9589. //
  9590. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9591. if (&fragment == &fragment_buffer.front()) {
  9592. if (vocab.add_space_prefix) {
  9593. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9594. }
  9595. }
  9596. #ifdef PRETOKENIZERDEBUG
  9597. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9598. #endif
  9599. llm_tokenizer_spm tokenizer(vocab);
  9600. llama_escape_whitespace(raw_text);
  9601. tokenizer.tokenize(raw_text, output);
  9602. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9603. output.push_back(fragment.token);
  9604. }
  9605. }
  9606. if (add_special && vocab.special_add_eos == 1) {
  9607. GGML_ASSERT(vocab.special_eos_id != -1);
  9608. output.push_back(vocab.special_eos_id);
  9609. }
  9610. } break;
  9611. case LLAMA_VOCAB_TYPE_BPE:
  9612. {
  9613. if (add_special && vocab.special_add_bos == 1) {
  9614. GGML_ASSERT(vocab.special_bos_id != -1);
  9615. output.push_back(vocab.special_bos_id);
  9616. }
  9617. for (const auto & fragment : fragment_buffer) {
  9618. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9619. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9620. #ifdef PRETOKENIZERDEBUG
  9621. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9622. #endif
  9623. llm_tokenizer_bpe tokenizer(vocab);
  9624. tokenizer.tokenize(raw_text, output);
  9625. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9626. output.push_back(fragment.token);
  9627. }
  9628. }
  9629. GGML_ASSERT(vocab.special_add_eos != 1);
  9630. } break;
  9631. case LLAMA_VOCAB_TYPE_WPM:
  9632. {
  9633. if (add_special) {
  9634. GGML_ASSERT(vocab.special_cls_id != -1);
  9635. output.push_back(vocab.special_cls_id);
  9636. }
  9637. for (const auto & fragment : fragment_buffer) {
  9638. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9639. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9640. #ifdef PRETOKENIZERDEBUG
  9641. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9642. #endif
  9643. llm_tokenizer_wpm tokenizer(vocab);
  9644. tokenizer.tokenize(raw_text, output);
  9645. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9646. output.push_back(fragment.token);
  9647. }
  9648. }
  9649. if (add_special) {
  9650. GGML_ASSERT(vocab.special_sep_id != -1);
  9651. output.push_back(vocab.special_sep_id);
  9652. }
  9653. } break;
  9654. case LLAMA_VOCAB_TYPE_NONE:
  9655. GGML_ASSERT(false);
  9656. }
  9657. return output;
  9658. }
  9659. //
  9660. // grammar - internal
  9661. //
  9662. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9663. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9664. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9665. const std::string & src,
  9666. llama_partial_utf8 partial_start) {
  9667. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9668. const char * pos = src.c_str();
  9669. std::vector<uint32_t> code_points;
  9670. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9671. code_points.reserve(src.size() + 1);
  9672. uint32_t value = partial_start.value;
  9673. int n_remain = partial_start.n_remain;
  9674. // continue previous decode, if applicable
  9675. while (*pos != 0 && n_remain > 0) {
  9676. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9677. if ((next_byte >> 6) != 2) {
  9678. // invalid sequence, abort
  9679. code_points.push_back(0);
  9680. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9681. }
  9682. value = (value << 6) + (next_byte & 0x3F);
  9683. ++pos;
  9684. --n_remain;
  9685. }
  9686. if (partial_start.n_remain > 0 && n_remain == 0) {
  9687. code_points.push_back(value);
  9688. }
  9689. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9690. while (*pos != 0) {
  9691. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9692. uint8_t highbits = first_byte >> 4;
  9693. n_remain = lookup[highbits] - 1;
  9694. if (n_remain < 0) {
  9695. // invalid sequence, abort
  9696. code_points.clear();
  9697. code_points.push_back(0);
  9698. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9699. }
  9700. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9701. value = first_byte & mask;
  9702. ++pos;
  9703. while (*pos != 0 && n_remain > 0) {
  9704. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9705. ++pos;
  9706. --n_remain;
  9707. }
  9708. if (n_remain == 0) {
  9709. code_points.push_back(value);
  9710. }
  9711. }
  9712. code_points.push_back(0);
  9713. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9714. }
  9715. // returns true iff pos points to the end of one of the definitions of a rule
  9716. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9717. switch (pos->type) {
  9718. case LLAMA_GRETYPE_END: return true; // NOLINT
  9719. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9720. default: return false;
  9721. }
  9722. }
  9723. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9724. // asserts that pos is pointing to a char range element
  9725. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9726. const llama_grammar_element * pos,
  9727. const uint32_t chr) {
  9728. bool found = false;
  9729. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9730. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9731. do {
  9732. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9733. // inclusive range, e.g. [a-z]
  9734. found = found || (pos->value <= chr && chr <= pos[1].value);
  9735. pos += 2;
  9736. } else {
  9737. // exact char match, e.g. [a] or "a"
  9738. found = found || pos->value == chr;
  9739. pos += 1;
  9740. }
  9741. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9742. return std::make_pair(found == is_positive_char, pos);
  9743. }
  9744. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9745. // range at pos (regular or inverse range)
  9746. // asserts that pos is pointing to a char range element
  9747. static bool llama_grammar_match_partial_char(
  9748. const llama_grammar_element * pos,
  9749. const llama_partial_utf8 partial_utf8) {
  9750. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9751. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9752. uint32_t partial_value = partial_utf8.value;
  9753. int n_remain = partial_utf8.n_remain;
  9754. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9755. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9756. return false;
  9757. }
  9758. // range of possible code points this partial UTF-8 sequence could complete to
  9759. uint32_t low = partial_value << (n_remain * 6);
  9760. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9761. if (low == 0) {
  9762. if (n_remain == 2) {
  9763. low = 1 << 11;
  9764. } else if (n_remain == 3) {
  9765. low = 1 << 16;
  9766. }
  9767. }
  9768. do {
  9769. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9770. // inclusive range, e.g. [a-z]
  9771. if (pos->value <= high && low <= pos[1].value) {
  9772. return is_positive_char;
  9773. }
  9774. pos += 2;
  9775. } else {
  9776. // exact char match, e.g. [a] or "a"
  9777. if (low <= pos->value && pos->value <= high) {
  9778. return is_positive_char;
  9779. }
  9780. pos += 1;
  9781. }
  9782. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9783. return !is_positive_char;
  9784. }
  9785. // transforms a grammar pushdown stack into N possible stacks, all ending
  9786. // at a character range (terminal element)
  9787. static void llama_grammar_advance_stack(
  9788. const std::vector<std::vector<llama_grammar_element>> & rules,
  9789. const std::vector<const llama_grammar_element *> & stack,
  9790. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9791. if (stack.empty()) {
  9792. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  9793. new_stacks.emplace_back(stack);
  9794. }
  9795. return;
  9796. }
  9797. const llama_grammar_element * pos = stack.back();
  9798. switch (pos->type) {
  9799. case LLAMA_GRETYPE_RULE_REF: {
  9800. const size_t rule_id = static_cast<size_t>(pos->value);
  9801. const llama_grammar_element * subpos = rules[rule_id].data();
  9802. do {
  9803. // init new stack without the top (pos)
  9804. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9805. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9806. // if this rule ref is followed by another element, add that to stack
  9807. new_stack.push_back(pos + 1);
  9808. }
  9809. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9810. // if alternate is nonempty, add to stack
  9811. new_stack.push_back(subpos);
  9812. }
  9813. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9814. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9815. // scan to end of alternate def
  9816. subpos++;
  9817. }
  9818. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9819. // there's another alternate def of this rule to process
  9820. subpos++;
  9821. } else {
  9822. break;
  9823. }
  9824. } while (true);
  9825. break;
  9826. }
  9827. case LLAMA_GRETYPE_CHAR:
  9828. case LLAMA_GRETYPE_CHAR_NOT:
  9829. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  9830. // only add the stack if it's not a duplicate of one we already have
  9831. new_stacks.emplace_back(stack);
  9832. }
  9833. break;
  9834. default:
  9835. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9836. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9837. // those
  9838. GGML_ASSERT(false);
  9839. }
  9840. }
  9841. // takes a set of possible pushdown stacks on a grammar, which are required to
  9842. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9843. // produces the N possible stacks if the given char is accepted at those
  9844. // positions
  9845. void llama_grammar_accept(
  9846. const std::vector<std::vector<llama_grammar_element>> & rules,
  9847. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9848. const uint32_t chr,
  9849. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9850. new_stacks.clear();
  9851. for (const auto & stack : stacks) {
  9852. if (stack.empty()) {
  9853. continue;
  9854. }
  9855. auto match = llama_grammar_match_char(stack.back(), chr);
  9856. if (match.first) {
  9857. const llama_grammar_element * pos = match.second;
  9858. // update top of stack to next element, if any
  9859. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9860. if (!llama_grammar_is_end_of_sequence(pos)) {
  9861. new_stack.push_back(pos);
  9862. }
  9863. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9864. }
  9865. }
  9866. }
  9867. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9868. const std::vector<std::vector<llama_grammar_element>> & rules,
  9869. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9870. const std::vector<llama_grammar_candidate> & candidates);
  9871. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9872. const std::vector<std::vector<llama_grammar_element>> & rules,
  9873. const std::vector<const llama_grammar_element *> & stack,
  9874. const std::vector<llama_grammar_candidate> & candidates) {
  9875. std::vector<llama_grammar_candidate> rejects;
  9876. rejects.reserve(candidates.size());
  9877. if (stack.empty()) {
  9878. for (const auto & tok : candidates) {
  9879. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9880. rejects.push_back(tok);
  9881. }
  9882. }
  9883. return rejects;
  9884. }
  9885. const llama_grammar_element * stack_pos = stack.back();
  9886. std::vector<llama_grammar_candidate> next_candidates;
  9887. next_candidates.reserve(candidates.size());
  9888. for (const auto & tok : candidates) {
  9889. if (*tok.code_points == 0) {
  9890. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9891. // that cannot satisfy this position in grammar
  9892. if (tok.partial_utf8.n_remain != 0 &&
  9893. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9894. rejects.push_back(tok);
  9895. }
  9896. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9897. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9898. } else {
  9899. rejects.push_back(tok);
  9900. }
  9901. }
  9902. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9903. // update top of stack to next element, if any
  9904. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9905. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9906. stack_after.push_back(stack_pos_after);
  9907. }
  9908. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9909. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9910. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9911. for (const auto & tok : next_rejects) {
  9912. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9913. }
  9914. return rejects;
  9915. }
  9916. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9917. const std::vector<std::vector<llama_grammar_element>> & rules,
  9918. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9919. const std::vector<llama_grammar_candidate> & candidates) {
  9920. GGML_ASSERT(!stacks.empty()); // REVIEW
  9921. if (candidates.empty()) {
  9922. return std::vector<llama_grammar_candidate>();
  9923. }
  9924. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9925. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9926. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9927. }
  9928. return rejects;
  9929. }
  9930. //
  9931. // grammar - external
  9932. //
  9933. struct llama_grammar * llama_grammar_init(
  9934. const llama_grammar_element ** rules,
  9935. size_t n_rules,
  9936. size_t start_rule_index) {
  9937. const llama_grammar_element * pos;
  9938. // copy rule definitions into vectors
  9939. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9940. for (size_t i = 0; i < n_rules; i++) {
  9941. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9942. vec_rules[i].push_back(*pos);
  9943. }
  9944. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9945. }
  9946. // loop over alternates of start rule to build initial stacks
  9947. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9948. pos = vec_rules[start_rule_index].data();
  9949. do {
  9950. std::vector<const llama_grammar_element *> stack;
  9951. if (!llama_grammar_is_end_of_sequence(pos)) {
  9952. // if alternate is nonempty, add to stack
  9953. stack.push_back(pos);
  9954. }
  9955. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9956. while (!llama_grammar_is_end_of_sequence(pos)) {
  9957. // scan to end of alternate def
  9958. pos++;
  9959. }
  9960. if (pos->type == LLAMA_GRETYPE_ALT) {
  9961. // there's another alternate def of this rule to process
  9962. pos++;
  9963. } else {
  9964. break;
  9965. }
  9966. } while (true);
  9967. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9968. }
  9969. void llama_grammar_free(struct llama_grammar * grammar) {
  9970. delete grammar;
  9971. }
  9972. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9973. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9974. // redirect elements in stacks to point to new rules
  9975. for (size_t is = 0; is < result->stacks.size(); is++) {
  9976. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9977. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9978. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9979. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9980. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9981. }
  9982. }
  9983. }
  9984. }
  9985. }
  9986. return result;
  9987. }
  9988. //
  9989. // sampling
  9990. //
  9991. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9992. if (seed == LLAMA_DEFAULT_SEED) {
  9993. seed = time(NULL);
  9994. }
  9995. ctx->rng.seed(seed);
  9996. }
  9997. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9998. GGML_ASSERT(candidates->size > 0);
  9999. const int64_t t_start_sample_us = ggml_time_us();
  10000. // Sort the logits in descending order
  10001. if (!candidates->sorted) {
  10002. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10003. return a.logit > b.logit;
  10004. });
  10005. candidates->sorted = true;
  10006. }
  10007. float max_l = candidates->data[0].logit;
  10008. float cum_sum = 0.0f;
  10009. for (size_t i = 0; i < candidates->size; ++i) {
  10010. float p = expf(candidates->data[i].logit - max_l);
  10011. candidates->data[i].p = p;
  10012. cum_sum += p;
  10013. }
  10014. for (size_t i = 0; i < candidates->size; ++i) {
  10015. candidates->data[i].p /= cum_sum;
  10016. }
  10017. if (ctx) {
  10018. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10019. }
  10020. }
  10021. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  10022. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  10023. // if (k >= (int32_t)candidates->size) {
  10024. // return;
  10025. // }
  10026. const int64_t t_start_sample_us = ggml_time_us();
  10027. if (k <= 0) {
  10028. k = candidates->size;
  10029. }
  10030. k = std::max(k, (int) min_keep);
  10031. k = std::min(k, (int) candidates->size);
  10032. // Sort scores in descending order
  10033. if (!candidates->sorted) {
  10034. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  10035. return a.logit > b.logit;
  10036. };
  10037. if (k <= 128) {
  10038. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  10039. } else {
  10040. constexpr int nbuckets = 128;
  10041. constexpr float bucket_low = -10.0f;
  10042. constexpr float bucket_high = 10.0f;
  10043. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  10044. constexpr float bucker_inter = -bucket_low * bucket_scale;
  10045. std::vector<int> bucket_idx(candidates->size);
  10046. std::vector<int> histo(nbuckets, 0);
  10047. for (int i = 0; i < (int)candidates->size; ++i) {
  10048. const float val = candidates->data[i].logit;
  10049. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  10050. ib = std::max(0, std::min(nbuckets-1, ib));
  10051. bucket_idx[i] = ib;
  10052. ++histo[ib];
  10053. }
  10054. int nhave = 0;
  10055. int ib = nbuckets - 1;
  10056. for ( ; ib >= 0; --ib) {
  10057. nhave += histo[ib];
  10058. if (nhave >= k) break;
  10059. }
  10060. std::vector<llama_token_data> tmp_tokens(nhave);
  10061. auto ptr = tmp_tokens.data();
  10062. std::vector<llama_token_data*> bucket_ptrs;
  10063. bucket_ptrs.reserve(nbuckets - ib);
  10064. for (int j = nbuckets - 1; j >= ib; --j) {
  10065. bucket_ptrs.push_back(ptr);
  10066. ptr += histo[j];
  10067. }
  10068. for (int i = 0; i < (int)candidates->size; ++i) {
  10069. int j = bucket_idx[i];
  10070. if (j >= ib) {
  10071. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  10072. }
  10073. }
  10074. ptr = tmp_tokens.data();
  10075. int ndone = 0;
  10076. for (int j = nbuckets-1; j > ib; --j) {
  10077. std::sort(ptr, ptr + histo[j], comp);
  10078. ptr += histo[j];
  10079. ndone += histo[j];
  10080. }
  10081. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  10082. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  10083. }
  10084. candidates->sorted = true;
  10085. }
  10086. candidates->size = k;
  10087. if (ctx) {
  10088. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10089. }
  10090. }
  10091. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10092. if (p >= 1.0f) {
  10093. return;
  10094. }
  10095. llama_sample_softmax(ctx, candidates);
  10096. const int64_t t_start_sample_us = ggml_time_us();
  10097. // Compute the cumulative probabilities
  10098. float cum_sum = 0.0f;
  10099. size_t last_idx = candidates->size;
  10100. for (size_t i = 0; i < candidates->size; ++i) {
  10101. cum_sum += candidates->data[i].p;
  10102. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  10103. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  10104. if (cum_sum >= p && i + 1 >= min_keep) {
  10105. last_idx = i + 1;
  10106. break;
  10107. }
  10108. }
  10109. // Resize the output vector to keep only the top-p tokens
  10110. candidates->size = last_idx;
  10111. if (ctx) {
  10112. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10113. }
  10114. }
  10115. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10116. if (p <= 0.0f || !candidates->size) {
  10117. return;
  10118. }
  10119. const int64_t t_start_sample_us = ggml_time_us();
  10120. bool min_p_applied = false;
  10121. // if the candidates aren't sorted, try the unsorted implementation first
  10122. if (!candidates->sorted) {
  10123. std::vector<llama_token_data> filtered_tokens;
  10124. float max_logit = -FLT_MAX;
  10125. for (size_t i = 0; i < candidates->size; ++i) {
  10126. max_logit = std::max(max_logit, candidates->data[i].logit);
  10127. }
  10128. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  10129. for (size_t i = 0; i < candidates->size; ++i) {
  10130. if (candidates->data[i].logit >= min_logit) {
  10131. filtered_tokens.push_back(candidates->data[i]);
  10132. }
  10133. }
  10134. // if we have enough values the operation was a success
  10135. if (filtered_tokens.size() >= min_keep) {
  10136. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  10137. candidates->size = filtered_tokens.size();
  10138. min_p_applied = true;
  10139. }
  10140. }
  10141. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  10142. if (!min_p_applied) {
  10143. // Sort the logits in descending order
  10144. if (!candidates->sorted) {
  10145. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10146. return a.logit > b.logit;
  10147. });
  10148. candidates->sorted = true;
  10149. }
  10150. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  10151. size_t i = 1; // first token always matches
  10152. for (; i < candidates->size; ++i) {
  10153. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  10154. break; // prob too small
  10155. }
  10156. }
  10157. // Resize the output vector to keep only the matching tokens
  10158. candidates->size = i;
  10159. }
  10160. if (ctx) {
  10161. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10162. }
  10163. }
  10164. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  10165. if (z >= 1.0f || candidates->size <= 2) {
  10166. return;
  10167. }
  10168. llama_sample_softmax(nullptr, candidates);
  10169. const int64_t t_start_sample_us = ggml_time_us();
  10170. // Compute the first and second derivatives
  10171. std::vector<float> first_derivatives(candidates->size - 1);
  10172. std::vector<float> second_derivatives(candidates->size - 2);
  10173. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  10174. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  10175. }
  10176. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10177. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  10178. }
  10179. // Calculate absolute value of second derivatives
  10180. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10181. second_derivatives[i] = std::abs(second_derivatives[i]);
  10182. }
  10183. // Normalize the second derivatives
  10184. {
  10185. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  10186. if (second_derivatives_sum > 1e-6f) {
  10187. for (float & value : second_derivatives) {
  10188. value /= second_derivatives_sum;
  10189. }
  10190. } else {
  10191. for (float & value : second_derivatives) {
  10192. value = 1.0f / second_derivatives.size();
  10193. }
  10194. }
  10195. }
  10196. float cum_sum = 0.0f;
  10197. size_t last_idx = candidates->size;
  10198. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10199. cum_sum += second_derivatives[i];
  10200. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  10201. if (cum_sum > z && i >= min_keep) {
  10202. last_idx = i;
  10203. break;
  10204. }
  10205. }
  10206. // Resize the output vector to keep only the tokens above the tail location
  10207. candidates->size = last_idx;
  10208. if (ctx) {
  10209. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10210. }
  10211. }
  10212. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10213. // Reference implementation:
  10214. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  10215. if (p >= 1.0f) {
  10216. return;
  10217. }
  10218. // Compute the softmax of logits and calculate entropy
  10219. llama_sample_softmax(nullptr, candidates);
  10220. const int64_t t_start_sample_us = ggml_time_us();
  10221. float entropy = 0.0f;
  10222. for (size_t i = 0; i < candidates->size; ++i) {
  10223. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  10224. }
  10225. // Compute the absolute difference between negative log probability and entropy for each candidate
  10226. std::vector<float> shifted_scores;
  10227. for (size_t i = 0; i < candidates->size; ++i) {
  10228. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  10229. shifted_scores.push_back(shifted_score);
  10230. }
  10231. // Sort tokens based on the shifted_scores and their corresponding indices
  10232. std::vector<size_t> indices(candidates->size);
  10233. std::iota(indices.begin(), indices.end(), 0);
  10234. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  10235. return shifted_scores[a] < shifted_scores[b];
  10236. });
  10237. // Compute the cumulative probabilities
  10238. float cum_sum = 0.0f;
  10239. size_t last_idx = indices.size();
  10240. for (size_t i = 0; i < indices.size(); ++i) {
  10241. size_t idx = indices[i];
  10242. cum_sum += candidates->data[idx].p;
  10243. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  10244. if (cum_sum > p && i >= min_keep - 1) {
  10245. last_idx = i + 1;
  10246. break;
  10247. }
  10248. }
  10249. // Resize the output vector to keep only the locally typical tokens
  10250. std::vector<llama_token_data> new_candidates;
  10251. for (size_t i = 0; i < last_idx; ++i) {
  10252. size_t idx = indices[i];
  10253. new_candidates.push_back(candidates->data[idx]);
  10254. }
  10255. // Replace the data in candidates with the new_candidates data
  10256. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  10257. candidates->size = new_candidates.size();
  10258. candidates->sorted = false;
  10259. if (ctx) {
  10260. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10261. }
  10262. }
  10263. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  10264. const int64_t t_start_sample_us = ggml_time_us();
  10265. // no need to do anything if there is only one (or zero) candidates
  10266. if(candidates_p->size <= 1) {
  10267. return;
  10268. }
  10269. // Calculate maximum possible entropy
  10270. float max_entropy = -logf(1.0f / candidates_p->size);
  10271. llama_sample_softmax(nullptr, candidates_p);
  10272. // Calculate entropy of the softmax probabilities
  10273. float entropy = 0.0f;
  10274. for (size_t i = 0; i < candidates_p->size; ++i) {
  10275. float prob = candidates_p->data[i].p;
  10276. if (prob > 0.0f) { // Ensure no log(0)
  10277. entropy -= prob * logf(prob);
  10278. }
  10279. }
  10280. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  10281. float normalized_entropy = entropy / max_entropy;
  10282. // Map the normalized entropy to the desired temperature range using the power function
  10283. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  10284. #ifdef DEBUG
  10285. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  10286. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  10287. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  10288. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  10289. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  10290. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  10291. #endif
  10292. // Apply the dynamically calculated temperature scaling
  10293. for (size_t i = 0; i < candidates_p->size; ++i) {
  10294. candidates_p->data[i].logit /= dyn_temp;
  10295. }
  10296. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  10297. double max_l_double = candidates_p->data[0].logit;
  10298. double cum_sum_double = 0.0;
  10299. for (size_t i = 0; i < candidates_p->size; ++i) {
  10300. double p = exp(candidates_p->data[i].logit - max_l_double);
  10301. candidates_p->data[i].p = p; // Store the scaled probability
  10302. cum_sum_double += p;
  10303. }
  10304. for (size_t i = 0; i < candidates_p->size; ++i) {
  10305. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  10306. }
  10307. #ifdef DEBUG
  10308. // Print the updated top 25 probabilities after temperature scaling
  10309. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  10310. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  10311. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  10312. }
  10313. #endif
  10314. if (ctx) {
  10315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10316. }
  10317. }
  10318. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  10319. const int64_t t_start_sample_us = ggml_time_us();
  10320. for (size_t i = 0; i < candidates_p->size; ++i) {
  10321. candidates_p->data[i].logit /= temp;
  10322. }
  10323. if (ctx) {
  10324. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10325. }
  10326. }
  10327. void llama_sample_repetition_penalties(
  10328. struct llama_context * ctx,
  10329. llama_token_data_array * candidates,
  10330. const llama_token * last_tokens,
  10331. size_t penalty_last_n,
  10332. float penalty_repeat,
  10333. float penalty_freq,
  10334. float penalty_present) {
  10335. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  10336. return;
  10337. }
  10338. const int64_t t_start_sample_us = ggml_time_us();
  10339. // Create a frequency map to count occurrences of each token in last_tokens
  10340. std::unordered_map<llama_token, int> token_count;
  10341. for (size_t i = 0; i < penalty_last_n; ++i) {
  10342. token_count[last_tokens[i]]++;
  10343. }
  10344. // Apply frequency and presence penalties to the candidates
  10345. for (size_t i = 0; i < candidates->size; ++i) {
  10346. const auto token_iter = token_count.find(candidates->data[i].id);
  10347. if (token_iter == token_count.end()) {
  10348. continue;
  10349. }
  10350. const int count = token_iter->second;
  10351. // 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.
  10352. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10353. if (candidates->data[i].logit <= 0) {
  10354. candidates->data[i].logit *= penalty_repeat;
  10355. } else {
  10356. candidates->data[i].logit /= penalty_repeat;
  10357. }
  10358. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10359. }
  10360. candidates->sorted = false;
  10361. if (ctx) {
  10362. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10363. }
  10364. }
  10365. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10366. GGML_ASSERT(ctx);
  10367. const int64_t t_start_sample_us = ggml_time_us();
  10368. bool allow_eos = false;
  10369. for (const auto & stack : grammar->stacks) {
  10370. if (stack.empty()) {
  10371. allow_eos = true;
  10372. break;
  10373. }
  10374. }
  10375. const llama_token eos = llama_token_eos(&ctx->model);
  10376. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10377. candidates_decoded.reserve(candidates->size);
  10378. std::vector<llama_grammar_candidate> candidates_grammar;
  10379. candidates_grammar.reserve(candidates->size);
  10380. for (size_t i = 0; i < candidates->size; ++i) {
  10381. const llama_token id = candidates->data[i].id;
  10382. const std::string piece = llama_token_to_piece(ctx, id);
  10383. if (id == eos) {
  10384. if (!allow_eos) {
  10385. candidates->data[i].logit = -INFINITY;
  10386. }
  10387. } else if (piece.empty() || piece[0] == 0) {
  10388. candidates->data[i].logit = -INFINITY;
  10389. } else {
  10390. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10391. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10392. }
  10393. }
  10394. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10395. for (const auto & reject : rejects) {
  10396. candidates->data[reject.index].logit = -INFINITY;
  10397. }
  10398. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10399. }
  10400. static void llama_log_softmax(float * array, size_t size) {
  10401. float max_l = *std::max_element(array, array + size);
  10402. float sum = 0.f;
  10403. for (size_t i = 0; i < size; ++i) {
  10404. float p = expf(array[i] - max_l);
  10405. sum += p;
  10406. array[i] = p;
  10407. }
  10408. for (size_t i = 0; i < size; ++i) {
  10409. array[i] = logf(array[i] / sum);
  10410. }
  10411. }
  10412. void llama_sample_apply_guidance(
  10413. struct llama_context * ctx,
  10414. float * logits,
  10415. float * logits_guidance,
  10416. float scale) {
  10417. GGML_ASSERT(ctx);
  10418. const auto t_start_sample_us = ggml_time_us();
  10419. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10420. llama_log_softmax(logits, n_vocab);
  10421. llama_log_softmax(logits_guidance, n_vocab);
  10422. for (int i = 0; i < n_vocab; ++i) {
  10423. auto & l = logits[i];
  10424. const auto & g = logits_guidance[i];
  10425. l = scale * (l - g) + g;
  10426. }
  10427. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10428. }
  10429. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10430. GGML_ASSERT(ctx);
  10431. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10432. int64_t t_start_sample_us;
  10433. t_start_sample_us = ggml_time_us();
  10434. llama_sample_softmax(nullptr, candidates);
  10435. // Estimate s_hat using the most probable m tokens
  10436. float s_hat = 0.0;
  10437. float sum_ti_bi = 0.0;
  10438. float sum_ti_sq = 0.0;
  10439. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10440. float t_i = logf(float(i + 2) / float(i + 1));
  10441. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10442. sum_ti_bi += t_i * b_i;
  10443. sum_ti_sq += t_i * t_i;
  10444. }
  10445. s_hat = sum_ti_bi / sum_ti_sq;
  10446. // Compute k from the estimated s_hat and target surprise value
  10447. float epsilon_hat = s_hat - 1;
  10448. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10449. // Sample the next word X using top-k sampling
  10450. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10451. if (ctx) {
  10452. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10453. }
  10454. llama_token X = llama_sample_token(ctx, candidates);
  10455. t_start_sample_us = ggml_time_us();
  10456. // Compute error as the difference between observed surprise and target surprise value
  10457. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10458. return candidate.id == X;
  10459. }));
  10460. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10461. float e = observed_surprise - tau;
  10462. // Update mu using the learning rate and error
  10463. *mu = *mu - eta * e;
  10464. if (ctx) {
  10465. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10466. }
  10467. return X;
  10468. }
  10469. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10470. int64_t t_start_sample_us;
  10471. t_start_sample_us = ggml_time_us();
  10472. llama_sample_softmax(ctx, candidates);
  10473. // Truncate the words with surprise values greater than mu
  10474. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10475. return -log2f(candidate.p) > *mu;
  10476. }));
  10477. if (candidates->size == 0) {
  10478. candidates->size = 1;
  10479. }
  10480. if (ctx) {
  10481. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10482. }
  10483. // Normalize the probabilities of the remaining words
  10484. llama_sample_softmax(ctx, candidates);
  10485. // Sample the next word X from the remaining words
  10486. llama_token X = llama_sample_token(ctx, candidates);
  10487. t_start_sample_us = ggml_time_us();
  10488. // Compute error as the difference between observed surprise and target surprise value
  10489. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10490. return candidate.id == X;
  10491. }));
  10492. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10493. float e = observed_surprise - tau;
  10494. // Update mu using the learning rate and error
  10495. *mu = *mu - eta * e;
  10496. if (ctx) {
  10497. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10498. }
  10499. return X;
  10500. }
  10501. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10502. const int64_t t_start_sample_us = ggml_time_us();
  10503. // Find max element
  10504. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10505. return a.logit < b.logit;
  10506. });
  10507. llama_token result = max_iter->id;
  10508. if (ctx) {
  10509. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10510. ctx->n_sample++;
  10511. }
  10512. return result;
  10513. }
  10514. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10515. GGML_ASSERT(ctx);
  10516. const int64_t t_start_sample_us = ggml_time_us();
  10517. llama_sample_softmax(nullptr, candidates);
  10518. std::vector<float> probs;
  10519. probs.reserve(candidates->size);
  10520. for (size_t i = 0; i < candidates->size; ++i) {
  10521. probs.push_back(candidates->data[i].p);
  10522. }
  10523. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10524. auto & rng = ctx->rng;
  10525. int idx = dist(rng);
  10526. llama_token result = candidates->data[idx].id;
  10527. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10528. ctx->n_sample++;
  10529. return result;
  10530. }
  10531. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10532. const int64_t t_start_sample_us = ggml_time_us();
  10533. if (token == llama_token_eos(&ctx->model)) {
  10534. for (const auto & stack : grammar->stacks) {
  10535. if (stack.empty()) {
  10536. return;
  10537. }
  10538. }
  10539. GGML_ASSERT(false);
  10540. }
  10541. const std::string piece = llama_token_to_piece(ctx, token);
  10542. // Note terminating 0 in decoded string
  10543. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10544. const auto & code_points = decoded.first;
  10545. std::vector<std::vector<const llama_grammar_element *>> tmp_new_stacks;
  10546. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10547. llama_grammar_accept(grammar->rules, grammar->stacks, *it, tmp_new_stacks);
  10548. grammar->stacks = tmp_new_stacks;
  10549. }
  10550. grammar->partial_utf8 = decoded.second;
  10551. GGML_ASSERT(!grammar->stacks.empty());
  10552. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10553. }
  10554. //
  10555. // Beam search
  10556. //
  10557. struct llama_beam {
  10558. std::vector<llama_token> tokens;
  10559. float p; // Cumulative beam probability (renormalized relative to all beams)
  10560. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10561. // Sort beams by probability. In case of ties, prefer beams at eob.
  10562. bool operator<(const llama_beam & rhs) const {
  10563. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10564. }
  10565. // Shift off first n tokens and discard them.
  10566. void shift_tokens(const size_t n) {
  10567. if (n) {
  10568. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10569. tokens.resize(tokens.size() - n);
  10570. }
  10571. }
  10572. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10573. };
  10574. // A struct for calculating logit-related info.
  10575. struct llama_logit_info {
  10576. const float * const logits;
  10577. const int n_vocab;
  10578. const float max_l;
  10579. const float normalizer;
  10580. struct sum_exp {
  10581. float max_l;
  10582. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10583. };
  10584. llama_logit_info(llama_context * ctx)
  10585. : logits(llama_get_logits(ctx))
  10586. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10587. , max_l(*std::max_element(logits, logits + n_vocab))
  10588. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10589. { }
  10590. llama_token_data get_token_data(const llama_token token_id) const {
  10591. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10592. return {token_id, logits[token_id], p};
  10593. }
  10594. // Return top k token_data by logit.
  10595. std::vector<llama_token_data> top_k(size_t k) {
  10596. std::vector<llama_token_data> min_heap; // min-heap by logit
  10597. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10598. min_heap.reserve(k_min);
  10599. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10600. min_heap.push_back(get_token_data(token_id));
  10601. }
  10602. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10603. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10604. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10605. if (min_heap.front().logit < logits[token_id]) {
  10606. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10607. min_heap.back().id = token_id;
  10608. min_heap.back().logit = logits[token_id];
  10609. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10610. }
  10611. }
  10612. return min_heap;
  10613. }
  10614. float probability_from_logit(float logit) const {
  10615. return normalizer * std::exp(logit - max_l);
  10616. }
  10617. };
  10618. struct llama_beam_search_data {
  10619. llama_context * ctx;
  10620. size_t n_beams;
  10621. int n_past;
  10622. int n_predict;
  10623. std::vector<llama_beam> beams;
  10624. std::vector<llama_beam> next_beams;
  10625. // Re-calculated on each loop iteration
  10626. size_t common_prefix_length;
  10627. // Used to communicate to/from callback on beams state.
  10628. std::vector<llama_beam_view> beam_views;
  10629. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10630. : ctx(ctx)
  10631. , n_beams(n_beams)
  10632. , n_past(n_past)
  10633. , n_predict(n_predict)
  10634. , beam_views(n_beams) {
  10635. beams.reserve(n_beams);
  10636. next_beams.reserve(n_beams);
  10637. }
  10638. // Collapse beams to a single beam given by index.
  10639. void collapse_beams(const size_t beam_idx) {
  10640. if (0u < beam_idx) {
  10641. std::swap(beams[0], beams[beam_idx]);
  10642. }
  10643. beams.resize(1);
  10644. }
  10645. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10646. // The repetitive patterns below reflect the 2 stages of heaps:
  10647. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10648. // * If the heap is full and a new element is found that should be included, pop the
  10649. // least element to the back(), replace it with the new, then push it into the heap.
  10650. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10651. // Min-heaps use a greater-than comparator.
  10652. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10653. if (beam.eob) {
  10654. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10655. if (next_beams.size() < n_beams) {
  10656. next_beams.push_back(std::move(beam));
  10657. if (next_beams.size() == n_beams) {
  10658. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10659. }
  10660. } else if (next_beams.front().p < beam.p) {
  10661. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10662. next_beams.back() = std::move(beam);
  10663. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10664. }
  10665. } else {
  10666. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10667. if (!beam.tokens.empty()) {
  10668. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10669. }
  10670. llama_logit_info logit_info(ctx);
  10671. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10672. size_t i=0;
  10673. if (next_beams.size() < n_beams) {
  10674. for (; next_beams.size() < n_beams ; ++i) {
  10675. llama_beam next_beam = beam;
  10676. next_beam.tokens.push_back(next_tokens[i].id);
  10677. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10678. next_beams.push_back(std::move(next_beam));
  10679. }
  10680. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10681. } else {
  10682. for (; next_beams.front().p == 0.0f ; ++i) {
  10683. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10684. next_beams.back() = beam;
  10685. next_beams.back().tokens.push_back(next_tokens[i].id);
  10686. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10687. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10688. }
  10689. }
  10690. for (; i < n_beams ; ++i) {
  10691. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10692. if (next_beams.front().p < next_p) {
  10693. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10694. next_beams.back() = beam;
  10695. next_beams.back().tokens.push_back(next_tokens[i].id);
  10696. next_beams.back().p = next_p;
  10697. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10698. }
  10699. }
  10700. }
  10701. }
  10702. // Find common_prefix_length based on beams.
  10703. // Requires beams is not empty.
  10704. size_t find_common_prefix_length() {
  10705. size_t common_prefix_length = beams[0].tokens.size();
  10706. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10707. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10708. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10709. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10710. common_prefix_length = j;
  10711. break;
  10712. }
  10713. }
  10714. }
  10715. return common_prefix_length;
  10716. }
  10717. // Construct beams_state to send back to caller via the callback function.
  10718. // Side effect: set common_prefix_length = find_common_prefix_length();
  10719. llama_beams_state get_beams_state(const bool last_call) {
  10720. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10721. beam_views[i] = beams[i].view();
  10722. }
  10723. common_prefix_length = find_common_prefix_length();
  10724. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10725. }
  10726. // Loop:
  10727. // * while i < n_predict, AND
  10728. // * any of the beams have not yet reached end-of-beam (eob), AND
  10729. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10730. // (since all other beam probabilities can only decrease)
  10731. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10732. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10733. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10734. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10735. !beams[top_beam_index()].eob ; ++i) {
  10736. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10737. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10738. if (common_prefix_length) {
  10739. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10740. n_past += common_prefix_length;
  10741. }
  10742. // Zero-out next_beam probabilities to place them last in following min-heap.
  10743. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10744. for (llama_beam & beam : beams) {
  10745. beam.shift_tokens(common_prefix_length);
  10746. fill_next_beams_by_top_probabilities(beam);
  10747. }
  10748. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10749. beams.swap(next_beams);
  10750. renormalize_beam_probabilities(beams);
  10751. }
  10752. collapse_beams(top_beam_index());
  10753. callback(callback_data, get_beams_state(true));
  10754. }
  10755. // As beams grow, the cumulative probabilities decrease.
  10756. // Renormalize them to avoid floating point underflow.
  10757. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10758. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10759. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10760. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10761. }
  10762. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10763. size_t top_beam_index() {
  10764. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10765. }
  10766. // Copy (p,eob) for each beam which may have been changed by the callback.
  10767. void update_beams_from_beam_views() {
  10768. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10769. beams[i].p = beam_views[i].p;
  10770. beams[i].eob = beam_views[i].eob;
  10771. }
  10772. }
  10773. };
  10774. void llama_beam_search(llama_context * ctx,
  10775. llama_beam_search_callback_fn_t callback, void * callback_data,
  10776. size_t n_beams, int n_past, int n_predict) {
  10777. assert(ctx);
  10778. const int64_t t_start_sample_us = ggml_time_us();
  10779. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10780. beam_search_data.loop(callback, callback_data);
  10781. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10782. ctx->n_sample++;
  10783. }
  10784. //
  10785. // quantization
  10786. //
  10787. struct quantize_state_internal {
  10788. const llama_model & model;
  10789. const llama_model_quantize_params * params;
  10790. int n_attention_wv = 0;
  10791. int n_ffn_down = 0;
  10792. int n_ffn_gate = 0;
  10793. int n_ffn_up = 0;
  10794. int i_attention_wv = 0;
  10795. int i_ffn_down = 0;
  10796. int i_ffn_gate = 0;
  10797. int i_ffn_up = 0;
  10798. int n_k_quantized = 0;
  10799. int n_fallback = 0;
  10800. bool has_imatrix = false;
  10801. // used to figure out if a model shares tok_embd with the output weight
  10802. bool has_output = false;
  10803. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10804. : model(model)
  10805. , params(params)
  10806. {}
  10807. };
  10808. static void llama_tensor_dequantize_internal(
  10809. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10810. const size_t nelements, const int nthread
  10811. ) {
  10812. if (output.size() < nelements) {
  10813. output.resize(nelements);
  10814. }
  10815. float * f32_output = (float *) output.data();
  10816. ggml_type_traits_t qtype;
  10817. if (ggml_is_quantized(tensor->type)) {
  10818. qtype = ggml_internal_get_type_traits(tensor->type);
  10819. if (qtype.to_float == NULL) {
  10820. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10821. }
  10822. } else if (tensor->type != GGML_TYPE_F16) {
  10823. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10824. }
  10825. if (nthread < 2) {
  10826. if (tensor->type == GGML_TYPE_F16) {
  10827. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10828. } else if (ggml_is_quantized(tensor->type)) {
  10829. qtype.to_float(tensor->data, f32_output, nelements);
  10830. } else {
  10831. GGML_ASSERT(false); // unreachable
  10832. }
  10833. return;
  10834. }
  10835. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10836. size_t block_size_bytes = ggml_type_size(tensor->type);
  10837. GGML_ASSERT(nelements % block_size == 0);
  10838. size_t nblocks = nelements / block_size;
  10839. size_t blocks_per_thread = nblocks / nthread;
  10840. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10841. size_t in_buff_offs = 0;
  10842. size_t out_buff_offs = 0;
  10843. for (int tnum = 0; tnum < nthread; tnum++) {
  10844. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10845. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10846. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10847. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10848. if (typ == GGML_TYPE_F16) {
  10849. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10850. } else {
  10851. qtype.to_float(inbuf, outbuf, nels);
  10852. }
  10853. };
  10854. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10855. in_buff_offs += thr_block_bytes;
  10856. out_buff_offs += thr_elems;
  10857. }
  10858. for (auto & w : workers) { w.join(); }
  10859. workers.clear();
  10860. }
  10861. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10862. const std::string name = ggml_get_name(tensor);
  10863. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10864. const llm_arch arch = qs.model.arch;
  10865. const auto tn = LLM_TN(arch);
  10866. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10867. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10868. };
  10869. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10870. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10871. if (n_expert > 1) {
  10872. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10873. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10874. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10875. // tensor name.
  10876. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10877. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10878. }
  10879. if (i_layer < 0 || i_layer >= n_layer) {
  10880. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10881. }
  10882. }
  10883. return std::make_pair(i_layer, n_layer);
  10884. };
  10885. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10886. // with the quantization of the output tensor
  10887. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10888. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10889. new_type = qs.params->output_tensor_type;
  10890. } else {
  10891. int nx = tensor->ne[0];
  10892. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10893. new_type = GGML_TYPE_Q8_0;
  10894. }
  10895. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10896. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  10897. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10898. new_type = GGML_TYPE_Q5_K;
  10899. }
  10900. else if (new_type != GGML_TYPE_Q8_0) {
  10901. new_type = GGML_TYPE_Q6_K;
  10902. }
  10903. }
  10904. } else if (name == "token_embd.weight") {
  10905. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10906. new_type = qs.params->token_embedding_type;
  10907. } else {
  10908. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  10909. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10910. new_type = GGML_TYPE_Q2_K;
  10911. }
  10912. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10913. new_type = GGML_TYPE_IQ3_S;
  10914. }
  10915. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10916. new_type = GGML_TYPE_IQ3_S;
  10917. }
  10918. }
  10919. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10920. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10921. if (name.find("attn_v.weight") != std::string::npos) {
  10922. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10923. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10924. ++qs.i_attention_wv;
  10925. }
  10926. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10927. new_type = GGML_TYPE_Q4_K;
  10928. }
  10929. else if (name.find("ffn_down") != std::string::npos) {
  10930. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10931. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10932. }
  10933. ++qs.i_ffn_down;
  10934. }
  10935. else if (name.find("attn_output.weight") != std::string::npos) {
  10936. if (qs.model.hparams.n_expert == 8) {
  10937. new_type = GGML_TYPE_Q5_K;
  10938. } else {
  10939. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  10940. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10941. }
  10942. }
  10943. } else if (name.find("attn_v.weight") != std::string::npos) {
  10944. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10945. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10946. }
  10947. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10948. new_type = GGML_TYPE_Q4_K;
  10949. }
  10950. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10951. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10952. }
  10953. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10954. new_type = GGML_TYPE_Q4_K;
  10955. }
  10956. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10957. new_type = GGML_TYPE_Q4_K;
  10958. }
  10959. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10960. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10961. }
  10962. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10963. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10964. new_type = GGML_TYPE_Q5_K;
  10965. }
  10966. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10967. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10968. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10969. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10970. (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;
  10971. if (qs.model.type == MODEL_70B) {
  10972. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10973. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10974. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10975. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10976. }
  10977. if (qs.model.hparams.n_expert == 8) {
  10978. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10979. // TODO: explore better strategies
  10980. new_type = GGML_TYPE_Q8_0;
  10981. }
  10982. ++qs.i_attention_wv;
  10983. } else if (name.find("attn_k.weight") != std::string::npos) {
  10984. if (qs.model.hparams.n_expert == 8) {
  10985. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10986. // TODO: explore better strategies
  10987. new_type = GGML_TYPE_Q8_0;
  10988. }
  10989. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10990. new_type = GGML_TYPE_IQ3_XXS;
  10991. }
  10992. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10993. new_type = GGML_TYPE_IQ2_S;
  10994. }
  10995. } else if (name.find("attn_q.weight") != std::string::npos) {
  10996. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10997. new_type = GGML_TYPE_IQ3_XXS;
  10998. }
  10999. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  11000. new_type = GGML_TYPE_IQ2_S;
  11001. }
  11002. } else if (name.find("ffn_down") != std::string::npos) {
  11003. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  11004. int i_layer = info.first, n_layer = info.second;
  11005. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11006. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  11007. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  11008. }
  11009. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  11010. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  11011. }
  11012. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  11013. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  11014. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  11015. : GGML_TYPE_Q3_K;
  11016. }
  11017. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  11018. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  11019. new_type = GGML_TYPE_Q4_K;
  11020. }
  11021. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  11022. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  11023. }
  11024. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  11025. if (arch == LLM_ARCH_FALCON) {
  11026. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  11027. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  11028. } else {
  11029. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  11030. }
  11031. }
  11032. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  11033. new_type = GGML_TYPE_Q5_K;
  11034. }
  11035. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  11036. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  11037. new_type = GGML_TYPE_Q5_K;
  11038. }
  11039. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  11040. && qs.has_imatrix && i_layer < n_layer/8) {
  11041. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  11042. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  11043. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  11044. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  11045. }
  11046. ++qs.i_ffn_down;
  11047. } else if (name.find("attn_output.weight") != std::string::npos) {
  11048. if (arch != LLM_ARCH_FALCON) {
  11049. if (qs.model.hparams.n_expert == 8) {
  11050. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  11051. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  11052. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  11053. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  11054. new_type = GGML_TYPE_Q5_K;
  11055. }
  11056. } else {
  11057. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  11058. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  11059. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  11060. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  11061. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  11062. }
  11063. } else {
  11064. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  11065. }
  11066. }
  11067. else if (name.find("attn_qkv.weight") != std::string::npos) {
  11068. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  11069. new_type = GGML_TYPE_Q4_K;
  11070. }
  11071. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  11072. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  11073. }
  11074. else if (name.find("ffn_gate") != std::string::npos) {
  11075. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  11076. int i_layer = info.first, n_layer = info.second;
  11077. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11078. new_type = GGML_TYPE_IQ3_XXS;
  11079. }
  11080. ++qs.i_ffn_gate;
  11081. }
  11082. else if (name.find("ffn_up") != std::string::npos) {
  11083. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  11084. int i_layer = info.first, n_layer = info.second;
  11085. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11086. new_type = GGML_TYPE_IQ3_XXS;
  11087. }
  11088. ++qs.i_ffn_up;
  11089. }
  11090. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11091. //}
  11092. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  11093. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  11094. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11095. //}
  11096. // This can be used to reduce the size of the Q5_K_S model.
  11097. // The associated PPL increase is fully in line with the size reduction
  11098. //else {
  11099. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  11100. //}
  11101. bool convert_incompatible_tensor = false;
  11102. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  11103. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  11104. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  11105. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  11106. new_type == GGML_TYPE_IQ1_M) {
  11107. int nx = tensor->ne[0];
  11108. int ny = tensor->ne[1];
  11109. if (nx % QK_K != 0) {
  11110. 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));
  11111. convert_incompatible_tensor = true;
  11112. } else {
  11113. ++qs.n_k_quantized;
  11114. }
  11115. }
  11116. if (convert_incompatible_tensor) {
  11117. switch (new_type) {
  11118. case GGML_TYPE_IQ2_XXS:
  11119. case GGML_TYPE_IQ2_XS:
  11120. case GGML_TYPE_IQ2_S:
  11121. case GGML_TYPE_IQ3_XXS:
  11122. case GGML_TYPE_IQ3_S:
  11123. case GGML_TYPE_IQ1_S:
  11124. case GGML_TYPE_IQ1_M:
  11125. case GGML_TYPE_Q2_K:
  11126. case GGML_TYPE_Q3_K:
  11127. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  11128. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  11129. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  11130. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  11131. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  11132. }
  11133. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  11134. ++qs.n_fallback;
  11135. }
  11136. return new_type;
  11137. }
  11138. 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) {
  11139. std::mutex mutex;
  11140. int64_t counter = 0;
  11141. size_t new_size = 0;
  11142. if (nthread < 2) {
  11143. // single-thread
  11144. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  11145. }
  11146. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  11147. nrows, n_per_row, imatrix]() {
  11148. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  11149. size_t local_size = 0;
  11150. while (true) {
  11151. std::unique_lock<std::mutex> lock(mutex);
  11152. int64_t first_row = counter; counter += nrows_per_chunk;
  11153. if (first_row >= nrows) {
  11154. if (local_size > 0) {
  11155. new_size += local_size;
  11156. }
  11157. break;
  11158. }
  11159. lock.unlock();
  11160. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  11161. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  11162. }
  11163. };
  11164. for (int it = 0; it < nthread - 1; ++it) {
  11165. workers.emplace_back(compute);
  11166. }
  11167. compute();
  11168. for (auto & w : workers) { w.join(); }
  11169. workers.clear();
  11170. return new_size;
  11171. }
  11172. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  11173. ggml_type default_type;
  11174. llama_ftype ftype = params->ftype;
  11175. switch (params->ftype) {
  11176. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  11177. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  11178. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  11179. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  11180. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  11181. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  11182. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  11183. // K-quants
  11184. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  11185. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  11186. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  11187. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  11188. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  11189. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  11190. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  11191. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  11192. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  11193. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  11194. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  11195. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  11196. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  11197. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  11198. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  11199. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  11200. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  11201. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  11202. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  11203. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  11204. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  11205. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  11206. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  11207. }
  11208. int nthread = params->nthread;
  11209. if (nthread <= 0) {
  11210. nthread = std::thread::hardware_concurrency();
  11211. }
  11212. // mmap consistently increases speed Linux, and also increases speed on Windows with
  11213. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  11214. #if defined(__linux__) || defined(_WIN32)
  11215. constexpr bool use_mmap = true;
  11216. #else
  11217. constexpr bool use_mmap = false;
  11218. #endif
  11219. llama_model_kv_override * kv_overrides = nullptr;
  11220. if (params->kv_overrides) {
  11221. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  11222. kv_overrides = v->data();
  11223. }
  11224. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  11225. ml.init_mappings(false); // no prefetching
  11226. llama_model model;
  11227. llm_load_arch(ml, model);
  11228. llm_load_hparams(ml, model);
  11229. struct quantize_state_internal qs(model, params);
  11230. if (params->only_copy) {
  11231. ftype = model.ftype;
  11232. }
  11233. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  11234. if (params->imatrix) {
  11235. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  11236. if (imatrix_data) {
  11237. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  11238. qs.has_imatrix = true;
  11239. }
  11240. }
  11241. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  11242. struct gguf_context * ctx_out = gguf_init_empty();
  11243. // copy the KV pairs from the input file
  11244. gguf_set_kv (ctx_out, ml.meta);
  11245. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  11246. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  11247. if (params->kv_overrides) {
  11248. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11249. for (auto & o : overrides) {
  11250. if (o.key[0] == 0) break;
  11251. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11252. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11253. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11254. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11255. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11256. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11257. } else {
  11258. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11259. }
  11260. }
  11261. }
  11262. for (int i = 0; i < ml.n_tensors; ++i) {
  11263. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11264. const std::string name = ggml_get_name(meta);
  11265. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11266. if (name.find("attn_v.weight") != std::string::npos ||
  11267. name.find("attn_qkv.weight") != std::string::npos) {
  11268. ++qs.n_attention_wv;
  11269. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11270. qs.has_output = true;
  11271. }
  11272. }
  11273. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  11274. // sanity checks
  11275. //
  11276. // - qs.n_attention_wv == 0 for Mamba models
  11277. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  11278. //
  11279. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  11280. size_t total_size_org = 0;
  11281. size_t total_size_new = 0;
  11282. std::vector<std::thread> workers;
  11283. workers.reserve(nthread);
  11284. int idx = 0;
  11285. std::vector<no_init<uint8_t>> read_data;
  11286. std::vector<no_init<uint8_t>> work;
  11287. std::vector<no_init<float>> f32_conv_buf;
  11288. // populate the original tensors so we get an initial meta data
  11289. for (int i = 0; i < ml.n_tensors; ++i) {
  11290. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11291. gguf_add_tensor(ctx_out, meta);
  11292. }
  11293. std::ofstream fout(fname_out, std::ios::binary);
  11294. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11295. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11296. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11297. // placeholder for the meta data
  11298. ::zeros(fout, meta_size);
  11299. const auto tn = LLM_TN(model.arch);
  11300. for (int i = 0; i < ml.n_tensors; ++i) {
  11301. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11302. const std::string name = ggml_get_name(tensor);
  11303. if (!ml.use_mmap) {
  11304. if (read_data.size() < ggml_nbytes(tensor)) {
  11305. read_data.resize(ggml_nbytes(tensor));
  11306. }
  11307. tensor->data = read_data.data();
  11308. }
  11309. ml.load_data_for(tensor);
  11310. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11311. ++idx, ml.n_tensors,
  11312. ggml_get_name(tensor),
  11313. llama_format_tensor_shape(tensor).c_str(),
  11314. ggml_type_name(tensor->type));
  11315. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11316. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11317. // quantize only 2D and 3D tensors (experts)
  11318. quantize &= (ggml_n_dims(tensor) >= 2);
  11319. // do not quantize norm tensors
  11320. quantize &= name.find("_norm.weight") == std::string::npos;
  11321. quantize &= params->quantize_output_tensor || name != "output.weight";
  11322. quantize &= !params->only_copy;
  11323. // do not quantize expert gating tensors
  11324. // NOTE: can't use LLM_TN here because the layer number is not known
  11325. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11326. // do not quantize positional embeddings and token types (BERT)
  11327. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11328. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11329. // do not quantize Mamba's small yet 2D weights
  11330. // NOTE: can't use LLM_TN here because the layer number is not known
  11331. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11332. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11333. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11334. enum ggml_type new_type;
  11335. void * new_data;
  11336. size_t new_size;
  11337. if (quantize) {
  11338. new_type = default_type;
  11339. // get more optimal quantization type based on the tensor shape, layer, etc.
  11340. if (!params->pure && ggml_is_quantized(default_type)) {
  11341. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11342. }
  11343. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11344. new_type = params->token_embedding_type;
  11345. }
  11346. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11347. new_type = params->output_tensor_type;
  11348. }
  11349. // If we've decided to quantize to the same type the tensor is already
  11350. // in then there's nothing to do.
  11351. quantize = tensor->type != new_type;
  11352. }
  11353. if (!quantize) {
  11354. new_type = tensor->type;
  11355. new_data = tensor->data;
  11356. new_size = ggml_nbytes(tensor);
  11357. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11358. } else {
  11359. const int64_t nelements = ggml_nelements(tensor);
  11360. const float * imatrix = nullptr;
  11361. if (imatrix_data) {
  11362. auto it = imatrix_data->find(tensor->name);
  11363. if (it == imatrix_data->end()) {
  11364. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11365. } else {
  11366. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  11367. imatrix = it->second.data();
  11368. } else {
  11369. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11370. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  11371. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  11372. // this is a significant error and it may be good idea to abort the process if this happens,
  11373. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  11374. // tok_embd should be ignored in this case, since it always causes this warning
  11375. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  11376. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  11377. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  11378. }
  11379. }
  11380. }
  11381. }
  11382. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11383. new_type == GGML_TYPE_IQ2_XS ||
  11384. new_type == GGML_TYPE_IQ2_S ||
  11385. new_type == GGML_TYPE_IQ1_S ||
  11386. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11387. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11388. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11389. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11390. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11391. LLAMA_LOG_ERROR("============================================================\n\n");
  11392. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11393. }
  11394. float * f32_data;
  11395. if (tensor->type == GGML_TYPE_F32) {
  11396. f32_data = (float *) tensor->data;
  11397. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11398. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11399. } else {
  11400. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11401. f32_data = (float *) f32_conv_buf.data();
  11402. }
  11403. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11404. fflush(stdout);
  11405. if (work.size() < (size_t)nelements * 4) {
  11406. work.resize(nelements * 4); // upper bound on size
  11407. }
  11408. new_data = work.data();
  11409. const int64_t n_per_row = tensor->ne[0];
  11410. const int64_t nrows = tensor->ne[1];
  11411. static const int64_t min_chunk_size = 32 * 512;
  11412. 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);
  11413. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  11414. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  11415. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  11416. // quantize each expert separately since they have different importance matrices
  11417. new_size = 0;
  11418. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  11419. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  11420. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  11421. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  11422. 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);
  11423. }
  11424. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11425. }
  11426. total_size_org += ggml_nbytes(tensor);
  11427. total_size_new += new_size;
  11428. // update the gguf meta data as we go
  11429. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11430. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11431. // write tensor data + padding
  11432. fout.write((const char *) new_data, new_size);
  11433. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11434. }
  11435. // go back to beginning of file and write the updated meta data
  11436. {
  11437. fout.seekp(0);
  11438. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11439. gguf_get_meta_data(ctx_out, data.data());
  11440. fout.write((const char *) data.data(), data.size());
  11441. }
  11442. fout.close();
  11443. gguf_free(ctx_out);
  11444. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11445. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11446. if (qs.n_fallback > 0) {
  11447. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11448. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11449. }
  11450. }
  11451. static int llama_apply_lora_from_file_internal(
  11452. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11453. ) {
  11454. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11455. const int64_t t_start_lora_us = ggml_time_us();
  11456. llama_file fin(path_lora, "rb");
  11457. // verify magic and version
  11458. {
  11459. uint32_t magic = fin.read_u32();
  11460. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11461. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11462. return 1;
  11463. }
  11464. uint32_t format_version = fin.read_u32();
  11465. if (format_version != 1) {
  11466. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11467. return 1;
  11468. }
  11469. }
  11470. int32_t lora_r = fin.read_u32();
  11471. int32_t lora_alpha = fin.read_u32();
  11472. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11473. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11474. // load base model
  11475. std::unique_ptr<llama_model_loader> ml;
  11476. if (path_base_model) {
  11477. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11478. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11479. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11480. }
  11481. struct tensor_meta {
  11482. std::string name;
  11483. ggml_type type;
  11484. int32_t ne[2];
  11485. size_t offset;
  11486. };
  11487. std::map<std::string, tensor_meta> tensor_meta_map;
  11488. // load all tensor meta
  11489. while (true) {
  11490. if (fin.tell() == fin.size) {
  11491. // eof
  11492. break;
  11493. }
  11494. int32_t n_dims;
  11495. int32_t name_len;
  11496. int32_t ftype;
  11497. fin.read_raw(&n_dims, sizeof(n_dims));
  11498. fin.read_raw(&name_len, sizeof(name_len));
  11499. fin.read_raw(&ftype, sizeof(ftype));
  11500. if (n_dims != 1 && n_dims != 2) {
  11501. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11502. return 1;
  11503. }
  11504. int32_t ne[2] = { 1, 1 };
  11505. for (int i = 0; i < n_dims; ++i) {
  11506. fin.read_raw(&ne[i], sizeof(ne[i]));
  11507. }
  11508. std::string name;
  11509. {
  11510. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11511. char buf[GGML_MAX_NAME];
  11512. fin.read_raw(buf, name_len);
  11513. name = std::string(buf, name_len);
  11514. }
  11515. // check for lora suffix
  11516. std::string lora_suffix;
  11517. if (name.length() > 6) {
  11518. lora_suffix = name.substr(name.length() - 6);
  11519. }
  11520. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11521. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11522. return 1;
  11523. }
  11524. // tensor type
  11525. ggml_type wtype;
  11526. switch (ftype) {
  11527. case 0: wtype = GGML_TYPE_F32; break;
  11528. case 1: wtype = GGML_TYPE_F16; break;
  11529. default:
  11530. {
  11531. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11532. __func__, ftype);
  11533. return 1;
  11534. }
  11535. }
  11536. // data offset
  11537. size_t offset = fin.tell();
  11538. offset = (offset + 31) & -32;
  11539. // skip tensor data
  11540. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11541. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11542. }
  11543. bool warned = false;
  11544. int n_tensors = 0;
  11545. // apply
  11546. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11547. if (backend_cpu == nullptr) {
  11548. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11549. return 1;
  11550. }
  11551. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11552. std::vector<no_init<uint8_t>> read_buf;
  11553. for (const auto & it : model.tensors_by_name) {
  11554. const std::string & base_name = it.first;
  11555. ggml_tensor * model_t = it.second;
  11556. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11557. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11558. continue;
  11559. }
  11560. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11561. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11562. ggml_init_params lora_init_params = {
  11563. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11564. /* .mem_buffer */ nullptr,
  11565. /* .no_alloc */ true,
  11566. };
  11567. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11568. if (lora_ctx == nullptr) {
  11569. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11570. ggml_backend_free(backend_cpu);
  11571. return 1;
  11572. }
  11573. // create tensors
  11574. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11575. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11576. ggml_set_name(loraA, metaA.name.c_str());
  11577. ggml_set_name(loraB, metaB.name.c_str());
  11578. ggml_tensor * base_t;
  11579. if (ml) {
  11580. if (!ml->get_tensor_meta(base_name.c_str())) {
  11581. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11582. return 1;
  11583. }
  11584. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11585. } else {
  11586. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11587. }
  11588. ggml_set_name(base_t, base_name.c_str());
  11589. // allocate in backend buffer
  11590. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11591. if (lora_buf == nullptr) {
  11592. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11593. return 1;
  11594. }
  11595. // load tensor data
  11596. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11597. read_buf.resize(ggml_nbytes(tensor));
  11598. fin.seek(tensor_meta.offset, SEEK_SET);
  11599. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11600. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11601. };
  11602. load_tensor(metaA, loraA);
  11603. load_tensor(metaB, loraB);
  11604. // load base model tensor data
  11605. if (ml) {
  11606. ml->load_data_for(base_t);
  11607. } else {
  11608. ggml_backend_tensor_copy(model_t, base_t);
  11609. }
  11610. if (ggml_is_quantized(base_t->type) && !warned) {
  11611. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11612. "use a f16 or f32 base model with --lora-base\n", __func__);
  11613. warned = true;
  11614. }
  11615. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11616. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11617. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11618. ggml_free(lora_ctx);
  11619. ggml_backend_buffer_free(lora_buf);
  11620. ggml_backend_free(backend_cpu);
  11621. return 1;
  11622. }
  11623. auto build_lora_graph = [&]() {
  11624. // w = w + BA*s
  11625. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11626. ggml_set_name(BA, "BA");
  11627. if (scaling != 1.0f) {
  11628. BA = ggml_scale(lora_ctx, BA, scaling);
  11629. ggml_set_name(BA, "BA_scaled");
  11630. }
  11631. ggml_tensor * r;
  11632. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11633. ggml_set_name(r, "r_add");
  11634. if (base_t->type != model_t->type) {
  11635. // convert the result to the model type
  11636. r = ggml_cast(lora_ctx, r, model_t->type);
  11637. ggml_set_name(r, "r_cast");
  11638. }
  11639. return r;
  11640. };
  11641. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11642. ggml_tensor * r = build_lora_graph();
  11643. ggml_build_forward_expand(gf, r);
  11644. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11645. if (graph_buf == nullptr) {
  11646. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11647. ggml_free(lora_ctx);
  11648. ggml_backend_buffer_free(lora_buf);
  11649. ggml_backend_free(backend_cpu);
  11650. return 1;
  11651. }
  11652. ggml_backend_graph_compute(backend_cpu, gf);
  11653. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11654. #if 0
  11655. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11656. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11657. // sched compute
  11658. ggml_build_forward_expand(gf, build_graph());
  11659. ggml_backend_sched_init_measure(sched, gf);
  11660. // create the graph again, since the previous one was destroyed by the measure
  11661. ggml_graph_clear(gf);
  11662. ggml_build_forward_expand(gf, build_graph());
  11663. ggml_backend_sched_graph_compute(sched, gf);
  11664. ggml_backend_sched_free(sched);
  11665. #endif
  11666. ggml_backend_buffer_free(lora_buf);
  11667. ggml_backend_buffer_free(graph_buf);
  11668. ggml_free(lora_ctx);
  11669. n_tensors++;
  11670. if (n_tensors % 4 == 0) {
  11671. LLAMA_LOG_INFO(".");
  11672. }
  11673. }
  11674. ggml_backend_free(backend_cpu);
  11675. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11676. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11677. return 0;
  11678. }
  11679. //
  11680. // interface implementation
  11681. //
  11682. struct llama_model_params llama_model_default_params() {
  11683. struct llama_model_params result = {
  11684. /*.n_gpu_layers =*/ 0,
  11685. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11686. /*.main_gpu =*/ 0,
  11687. /*.tensor_split =*/ nullptr,
  11688. /*.progress_callback =*/ nullptr,
  11689. /*.progress_callback_user_data =*/ nullptr,
  11690. /*.kv_overrides =*/ nullptr,
  11691. /*.vocab_only =*/ false,
  11692. /*.use_mmap =*/ true,
  11693. /*.use_mlock =*/ false,
  11694. };
  11695. #ifdef GGML_USE_METAL
  11696. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11697. result.n_gpu_layers = 999;
  11698. #endif
  11699. return result;
  11700. }
  11701. struct llama_context_params llama_context_default_params() {
  11702. struct llama_context_params result = {
  11703. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11704. /*.n_ctx =*/ 512,
  11705. /*.n_batch =*/ 2048,
  11706. /*.n_ubatch =*/ 512,
  11707. /*.n_seq_max =*/ 1,
  11708. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11709. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11710. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11711. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11712. /*.rope_freq_base =*/ 0.0f,
  11713. /*.rope_freq_scale =*/ 0.0f,
  11714. /*.yarn_ext_factor =*/ -1.0f,
  11715. /*.yarn_attn_factor =*/ 1.0f,
  11716. /*.yarn_beta_fast =*/ 32.0f,
  11717. /*.yarn_beta_slow =*/ 1.0f,
  11718. /*.yarn_orig_ctx =*/ 0,
  11719. /*.defrag_thold =*/ -1.0f,
  11720. /*.cb_eval =*/ nullptr,
  11721. /*.cb_eval_user_data =*/ nullptr,
  11722. /*.type_k =*/ GGML_TYPE_F16,
  11723. /*.type_v =*/ GGML_TYPE_F16,
  11724. /*.logits_all =*/ false,
  11725. /*.embeddings =*/ false,
  11726. /*.offload_kqv =*/ true,
  11727. /*.abort_callback =*/ nullptr,
  11728. /*.abort_callback_data =*/ nullptr,
  11729. };
  11730. return result;
  11731. }
  11732. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11733. struct llama_model_quantize_params result = {
  11734. /*.nthread =*/ 0,
  11735. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11736. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11737. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11738. /*.allow_requantize =*/ false,
  11739. /*.quantize_output_tensor =*/ true,
  11740. /*.only_copy =*/ false,
  11741. /*.pure =*/ false,
  11742. /*.imatrix =*/ nullptr,
  11743. /*.kv_overrides =*/ nullptr,
  11744. };
  11745. return result;
  11746. }
  11747. size_t llama_max_devices(void) {
  11748. #if defined(GGML_USE_METAL)
  11749. return 1;
  11750. #elif defined(GGML_USE_CUDA)
  11751. return GGML_CUDA_MAX_DEVICES;
  11752. #elif defined(GGML_USE_SYCL)
  11753. return GGML_SYCL_MAX_DEVICES;
  11754. #elif defined(GGML_USE_VULKAN)
  11755. return GGML_VK_MAX_DEVICES;
  11756. #else
  11757. return 1;
  11758. #endif
  11759. }
  11760. bool llama_supports_mmap(void) {
  11761. return llama_mmap::SUPPORTED;
  11762. }
  11763. bool llama_supports_mlock(void) {
  11764. return llama_mlock::SUPPORTED;
  11765. }
  11766. bool llama_supports_gpu_offload(void) {
  11767. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11768. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11769. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11770. return true;
  11771. #else
  11772. return false;
  11773. #endif
  11774. }
  11775. void llama_backend_init(void) {
  11776. ggml_time_init();
  11777. // needed to initialize f16 tables
  11778. {
  11779. struct ggml_init_params params = { 0, NULL, false };
  11780. struct ggml_context * ctx = ggml_init(params);
  11781. ggml_free(ctx);
  11782. }
  11783. #ifdef GGML_USE_MPI
  11784. ggml_mpi_backend_init();
  11785. #endif
  11786. }
  11787. void llama_numa_init(enum ggml_numa_strategy numa) {
  11788. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11789. ggml_numa_init(numa);
  11790. }
  11791. }
  11792. void llama_backend_free(void) {
  11793. #ifdef GGML_USE_MPI
  11794. ggml_mpi_backend_free();
  11795. #endif
  11796. ggml_quantize_free();
  11797. }
  11798. int64_t llama_time_us(void) {
  11799. return ggml_time_us();
  11800. }
  11801. struct llama_model * llama_load_model_from_file(
  11802. const char * path_model,
  11803. struct llama_model_params params) {
  11804. ggml_time_init();
  11805. llama_model * model = new llama_model;
  11806. unsigned cur_percentage = 0;
  11807. if (params.progress_callback == NULL) {
  11808. params.progress_callback_user_data = &cur_percentage;
  11809. params.progress_callback = [](float progress, void * ctx) {
  11810. unsigned * cur_percentage_p = (unsigned *) ctx;
  11811. unsigned percentage = (unsigned) (100 * progress);
  11812. while (percentage > *cur_percentage_p) {
  11813. *cur_percentage_p = percentage;
  11814. LLAMA_LOG_INFO(".");
  11815. if (percentage >= 100) {
  11816. LLAMA_LOG_INFO("\n");
  11817. }
  11818. }
  11819. return true;
  11820. };
  11821. }
  11822. int status = llama_model_load(path_model, *model, params);
  11823. GGML_ASSERT(status <= 0);
  11824. if (status < 0) {
  11825. if (status == -1) {
  11826. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11827. } else if (status == -2) {
  11828. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11829. }
  11830. delete model;
  11831. return nullptr;
  11832. }
  11833. return model;
  11834. }
  11835. void llama_free_model(struct llama_model * model) {
  11836. delete model;
  11837. }
  11838. struct llama_context * llama_new_context_with_model(
  11839. struct llama_model * model,
  11840. struct llama_context_params params) {
  11841. if (!model) {
  11842. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11843. return nullptr;
  11844. }
  11845. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11846. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11847. return nullptr;
  11848. }
  11849. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11850. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11851. return nullptr;
  11852. }
  11853. llama_context * ctx = new llama_context(*model);
  11854. const auto & hparams = model->hparams;
  11855. auto & cparams = ctx->cparams;
  11856. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11857. cparams.n_threads = params.n_threads;
  11858. cparams.n_threads_batch = params.n_threads_batch;
  11859. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11860. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11861. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11862. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11863. cparams.defrag_thold = params.defrag_thold;
  11864. cparams.embeddings = params.embeddings;
  11865. cparams.offload_kqv = params.offload_kqv;
  11866. cparams.pooling_type = params.pooling_type;
  11867. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11868. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11869. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11870. // this is necessary due to kv_self.n being padded later during inference
  11871. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11872. // with causal attention, the batch size is limited by the context size
  11873. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11874. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11875. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11876. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11877. hparams.n_ctx_train;
  11878. cparams.cb_eval = params.cb_eval;
  11879. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11880. auto rope_scaling_type = params.rope_scaling_type;
  11881. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11882. rope_scaling_type = hparams.rope_scaling_type_train;
  11883. }
  11884. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11885. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11886. }
  11887. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11888. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11889. }
  11890. cparams.causal_attn = hparams.causal_attn;
  11891. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11892. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11893. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11894. } else {
  11895. cparams.pooling_type = hparams.pooling_type;
  11896. }
  11897. }
  11898. if (params.seed == LLAMA_DEFAULT_SEED) {
  11899. params.seed = time(NULL);
  11900. }
  11901. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11902. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11903. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11904. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11905. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11906. ctx->abort_callback = params.abort_callback;
  11907. ctx->abort_callback_data = params.abort_callback_data;
  11908. ctx->rng = std::mt19937(params.seed);
  11909. ctx->logits_all = params.logits_all;
  11910. uint32_t kv_size = cparams.n_ctx;
  11911. ggml_type type_k = params.type_k;
  11912. ggml_type type_v = params.type_v;
  11913. // Mamba only needs a constant number of KV cache cells per sequence
  11914. if (model->arch == LLM_ARCH_MAMBA) {
  11915. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11916. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11917. // it's probably best to keep as much precision as possible for the states
  11918. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11919. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11920. }
  11921. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11922. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11923. if (!hparams.vocab_only) {
  11924. // initialize backends
  11925. #ifdef GGML_USE_METAL
  11926. if (model->n_gpu_layers > 0) {
  11927. ctx->backend_metal = ggml_backend_metal_init();
  11928. if (ctx->backend_metal == nullptr) {
  11929. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11930. llama_free(ctx);
  11931. return nullptr;
  11932. }
  11933. ctx->backends.push_back(ctx->backend_metal);
  11934. }
  11935. #elif defined(GGML_USE_CUDA)
  11936. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11937. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11938. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11939. if (backend == nullptr) {
  11940. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11941. llama_free(ctx);
  11942. return nullptr;
  11943. }
  11944. ctx->backends.push_back(backend);
  11945. } else {
  11946. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11947. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11948. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11949. if (backend == nullptr) {
  11950. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11951. llama_free(ctx);
  11952. return nullptr;
  11953. }
  11954. ctx->backends.push_back(backend);
  11955. }
  11956. }
  11957. #elif defined(GGML_USE_VULKAN)
  11958. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11959. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  11960. llama_free(ctx);
  11961. return nullptr;
  11962. }
  11963. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  11964. ggml_backend_t backend = ggml_backend_vk_init(0);
  11965. if (backend == nullptr) {
  11966. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  11967. llama_free(ctx);
  11968. return nullptr;
  11969. }
  11970. ctx->backends.push_back(backend);
  11971. } else {
  11972. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11973. ggml_backend_t backend = ggml_backend_vk_init(device);
  11974. if (backend == nullptr) {
  11975. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11976. llama_free(ctx);
  11977. return nullptr;
  11978. }
  11979. ctx->backends.push_back(backend);
  11980. }
  11981. }
  11982. #elif defined(GGML_USE_SYCL)
  11983. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11984. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11985. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11986. if (backend == nullptr) {
  11987. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11988. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11989. llama_free(ctx);
  11990. return nullptr;
  11991. }
  11992. ctx->backends.push_back(backend);
  11993. } else {
  11994. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11995. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11996. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11997. if (backend == nullptr) {
  11998. int id_list[GGML_SYCL_MAX_DEVICES];
  11999. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  12000. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  12001. llama_free(ctx);
  12002. return nullptr;
  12003. }
  12004. ctx->backends.push_back(backend);
  12005. }
  12006. }
  12007. #elif defined(GGML_USE_KOMPUTE)
  12008. if (model->n_gpu_layers > 0) {
  12009. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  12010. if (backend == nullptr) {
  12011. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  12012. llama_free(ctx);
  12013. return nullptr;
  12014. }
  12015. ctx->backends.push_back(backend);
  12016. }
  12017. #endif
  12018. ctx->backend_cpu = ggml_backend_cpu_init();
  12019. if (ctx->backend_cpu == nullptr) {
  12020. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  12021. llama_free(ctx);
  12022. return nullptr;
  12023. }
  12024. ctx->backends.push_back(ctx->backend_cpu);
  12025. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  12026. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  12027. llama_free(ctx);
  12028. return nullptr;
  12029. }
  12030. {
  12031. size_t memory_size_k = 0;
  12032. size_t memory_size_v = 0;
  12033. for (auto & k : ctx->kv_self.k_l) {
  12034. memory_size_k += ggml_nbytes(k);
  12035. }
  12036. for (auto & v : ctx->kv_self.v_l) {
  12037. memory_size_v += ggml_nbytes(v);
  12038. }
  12039. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  12040. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  12041. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  12042. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  12043. }
  12044. // graph outputs buffer
  12045. {
  12046. // resized during inference when a batch uses more outputs
  12047. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  12048. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  12049. llama_free(ctx);
  12050. return nullptr;
  12051. }
  12052. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  12053. ggml_backend_buffer_name(ctx->buf_output),
  12054. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  12055. }
  12056. // scheduler and compute buffers
  12057. {
  12058. // buffer types used for the compute buffer of each backend
  12059. std::vector<ggml_backend_buffer_type_t> backend_buft;
  12060. for (auto * backend : ctx->backends) {
  12061. if (ggml_backend_is_cpu(backend)) {
  12062. // use host buffers for the CPU backend compute buffer
  12063. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  12064. } else {
  12065. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  12066. }
  12067. }
  12068. // buffer used to store the computation graph and the tensor meta data
  12069. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  12070. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  12071. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  12072. #ifndef GGML_USE_CUDA
  12073. // pipeline parallelism requires support for async compute and events
  12074. // currently this is only implemented in the CUDA backend
  12075. pipeline_parallel = false;
  12076. #endif
  12077. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  12078. if (pipeline_parallel) {
  12079. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  12080. }
  12081. // build worst-case graph
  12082. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  12083. int n_past = cparams.n_ctx - n_tokens;
  12084. 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
  12085. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12086. // initialize scheduler with the worst-case graph
  12087. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  12088. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12089. llama_free(ctx);
  12090. return nullptr;
  12091. }
  12092. for (size_t i = 0; i < ctx->backends.size(); i++) {
  12093. ggml_backend_t backend = ctx->backends[i];
  12094. ggml_backend_buffer_type_t buft = backend_buft[i];
  12095. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  12096. if (size > 1) {
  12097. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  12098. ggml_backend_buft_name(buft),
  12099. size / 1024.0 / 1024.0);
  12100. }
  12101. }
  12102. // note: the number of splits during measure is higher than during inference due to the kv shift
  12103. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  12104. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  12105. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  12106. }
  12107. }
  12108. #ifdef GGML_USE_MPI
  12109. ctx->ctx_mpi = ggml_mpi_init();
  12110. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  12111. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  12112. // TODO: needs fix after #3228
  12113. GGML_ASSERT(false && "not implemented");
  12114. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  12115. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  12116. llama_backend_free();
  12117. exit(1);
  12118. }
  12119. #endif
  12120. return ctx;
  12121. }
  12122. void llama_free(struct llama_context * ctx) {
  12123. delete ctx;
  12124. }
  12125. const llama_model * llama_get_model(const struct llama_context * ctx) {
  12126. return &ctx->model;
  12127. }
  12128. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  12129. return ctx->cparams.n_ctx;
  12130. }
  12131. uint32_t llama_n_batch(const struct llama_context * ctx) {
  12132. return ctx->cparams.n_batch;
  12133. }
  12134. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  12135. return ctx->cparams.n_ubatch;
  12136. }
  12137. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  12138. return ctx->kv_self.size;
  12139. }
  12140. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  12141. return model->vocab.type;
  12142. }
  12143. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  12144. switch (model->arch) {
  12145. // these models do not use RoPE
  12146. case LLM_ARCH_GPT2:
  12147. case LLM_ARCH_GPTJ:
  12148. case LLM_ARCH_GPTNEOX:
  12149. case LLM_ARCH_MPT:
  12150. case LLM_ARCH_REFACT:
  12151. case LLM_ARCH_BLOOM:
  12152. case LLM_ARCH_MAMBA:
  12153. return LLAMA_ROPE_TYPE_NONE;
  12154. // use what we call a normal RoPE, operating on pairs of consecutive head values
  12155. case LLM_ARCH_LLAMA:
  12156. case LLM_ARCH_BAICHUAN:
  12157. case LLM_ARCH_STARCODER:
  12158. case LLM_ARCH_PLAMO:
  12159. case LLM_ARCH_CODESHELL:
  12160. case LLM_ARCH_ORION:
  12161. case LLM_ARCH_INTERNLM2:
  12162. case LLM_ARCH_MINICPM:
  12163. case LLM_ARCH_XVERSE:
  12164. case LLM_ARCH_COMMAND_R:
  12165. return LLAMA_ROPE_TYPE_NORM;
  12166. // the pairs of head values are offset by n_rot/2
  12167. case LLM_ARCH_FALCON:
  12168. case LLM_ARCH_GROK:
  12169. case LLM_ARCH_PERSIMMON:
  12170. case LLM_ARCH_BERT:
  12171. case LLM_ARCH_NOMIC_BERT:
  12172. case LLM_ARCH_STABLELM:
  12173. case LLM_ARCH_QWEN:
  12174. case LLM_ARCH_QWEN2:
  12175. case LLM_ARCH_PHI2:
  12176. case LLM_ARCH_GEMMA:
  12177. case LLM_ARCH_STARCODER2:
  12178. return LLAMA_ROPE_TYPE_NEOX;
  12179. // all model arches should be listed explicitly here
  12180. case LLM_ARCH_UNKNOWN:
  12181. GGML_ASSERT(false && "unknown architecture");
  12182. break;
  12183. }
  12184. return LLAMA_ROPE_TYPE_NONE;
  12185. }
  12186. int32_t llama_n_vocab(const struct llama_model * model) {
  12187. return model->hparams.n_vocab;
  12188. }
  12189. int32_t llama_n_ctx_train(const struct llama_model * model) {
  12190. return model->hparams.n_ctx_train;
  12191. }
  12192. int32_t llama_n_embd(const struct llama_model * model) {
  12193. return model->hparams.n_embd;
  12194. }
  12195. int32_t llama_n_layer(const struct llama_model * model) {
  12196. return model->hparams.n_layer;
  12197. }
  12198. float llama_rope_freq_scale_train(const struct llama_model * model) {
  12199. return model->hparams.rope_freq_scale_train;
  12200. }
  12201. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  12202. const auto & it = model->gguf_kv.find(key);
  12203. if (it == model->gguf_kv.end()) {
  12204. if (buf_size > 0) {
  12205. buf[0] = '\0';
  12206. }
  12207. return -1;
  12208. }
  12209. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12210. }
  12211. int32_t llama_model_meta_count(const struct llama_model * model) {
  12212. return (int)model->gguf_kv.size();
  12213. }
  12214. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  12215. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12216. if (buf_size > 0) {
  12217. buf[0] = '\0';
  12218. }
  12219. return -1;
  12220. }
  12221. auto it = model->gguf_kv.begin();
  12222. std::advance(it, i);
  12223. return snprintf(buf, buf_size, "%s", it->first.c_str());
  12224. }
  12225. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  12226. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12227. if (buf_size > 0) {
  12228. buf[0] = '\0';
  12229. }
  12230. return -1;
  12231. }
  12232. auto it = model->gguf_kv.begin();
  12233. std::advance(it, i);
  12234. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12235. }
  12236. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  12237. return snprintf(buf, buf_size, "%s %s %s",
  12238. llama_model_arch_name(model->arch),
  12239. llama_model_type_name(model->type),
  12240. llama_model_ftype_name(model->ftype).c_str());
  12241. }
  12242. uint64_t llama_model_size(const struct llama_model * model) {
  12243. uint64_t size = 0;
  12244. for (const auto & it : model->tensors_by_name) {
  12245. size += ggml_nbytes(it.second);
  12246. }
  12247. return size;
  12248. }
  12249. uint64_t llama_model_n_params(const struct llama_model * model) {
  12250. uint64_t nparams = 0;
  12251. for (const auto & it : model->tensors_by_name) {
  12252. nparams += ggml_nelements(it.second);
  12253. }
  12254. return nparams;
  12255. }
  12256. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12257. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12258. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12259. return it.first == name;
  12260. });
  12261. if (it == model->tensors_by_name.end()) {
  12262. return nullptr;
  12263. }
  12264. return it->second;
  12265. }
  12266. uint32_t llama_model_quantize(
  12267. const char * fname_inp,
  12268. const char * fname_out,
  12269. const llama_model_quantize_params * params) {
  12270. try {
  12271. llama_model_quantize_internal(fname_inp, fname_out, params);
  12272. return 0;
  12273. } catch (const std::exception & err) {
  12274. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12275. return 1;
  12276. }
  12277. }
  12278. 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) {
  12279. try {
  12280. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12281. } catch (const std::exception & err) {
  12282. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12283. return 1;
  12284. }
  12285. }
  12286. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12287. GGML_ASSERT(cvec.tensors.empty());
  12288. GGML_ASSERT(cvec.ctxs.empty());
  12289. GGML_ASSERT(cvec.bufs.empty());
  12290. // count layer buffer types
  12291. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12292. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12293. buft_layer_count[model.buft_layer[i].buft]++;
  12294. }
  12295. // allocate contexts
  12296. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12297. for (auto & it : buft_layer_count) {
  12298. int n_layers = it.second;
  12299. struct ggml_init_params params = {
  12300. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12301. /*.mem_buffer =*/ NULL,
  12302. /*.no_alloc =*/ true,
  12303. };
  12304. ggml_context * ctx = ggml_init(params);
  12305. if (!ctx) {
  12306. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12307. return 1;
  12308. }
  12309. ctx_map[it.first] = ctx;
  12310. }
  12311. // make tensors
  12312. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12313. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12314. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12315. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12316. cvec.tensors.push_back(tensor);
  12317. }
  12318. // allocate tensors / buffers and zero
  12319. for (auto it : ctx_map) {
  12320. ggml_backend_buffer_type_t buft = it.first;
  12321. ggml_context * ctx = it.second;
  12322. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12323. if (!buf) {
  12324. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12325. return false;
  12326. }
  12327. ggml_backend_buffer_clear(buf, 0);
  12328. cvec.ctxs.push_back(ctx);
  12329. cvec.bufs.push_back(buf);
  12330. }
  12331. return true;
  12332. }
  12333. 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) {
  12334. const llama_model & model = lctx->model;
  12335. llama_control_vector & cvec = lctx->cvec;
  12336. if (data == nullptr) {
  12337. // disable the current control vector (but leave allocated for later)
  12338. cvec.layer_start = -1;
  12339. cvec.layer_end = -1;
  12340. return 0;
  12341. }
  12342. if (n_embd != (int) model.hparams.n_embd) {
  12343. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12344. return 1;
  12345. }
  12346. if (cvec.tensors.empty()) {
  12347. if (!llama_control_vector_init(cvec, model)) {
  12348. return 1;
  12349. }
  12350. }
  12351. cvec.layer_start = il_start;
  12352. cvec.layer_end = il_end;
  12353. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12354. assert(cvec.tensors[il] != nullptr);
  12355. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12356. if (off + n_embd <= len) {
  12357. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12358. }
  12359. }
  12360. return 0;
  12361. }
  12362. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12363. struct llama_kv_cache_view result = {
  12364. /*.n_cells = */ 0,
  12365. /*.n_seq_max = */ n_seq_max,
  12366. /*.token_count = */ 0,
  12367. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12368. /*.max_contiguous = */ 0,
  12369. /*.max_contiguous_idx = */ -1,
  12370. /*.cells = */ nullptr,
  12371. /*.cells_sequences = */ nullptr,
  12372. };
  12373. return result;
  12374. }
  12375. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12376. if (view->cells != nullptr) {
  12377. free(view->cells);
  12378. view->cells = nullptr;
  12379. }
  12380. if (view->cells_sequences != nullptr) {
  12381. free(view->cells_sequences);
  12382. view->cells_sequences = nullptr;
  12383. }
  12384. }
  12385. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12386. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12387. view->n_cells = int32_t(ctx->kv_self.size);
  12388. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12389. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12390. view->cells = (struct llama_kv_cache_view_cell *)p;
  12391. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12392. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12393. view->cells_sequences = (llama_seq_id *)p;
  12394. }
  12395. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12396. llama_kv_cache_view_cell * c_curr = view->cells;
  12397. llama_seq_id * cs_curr = view->cells_sequences;
  12398. int32_t used_cells = 0;
  12399. int32_t token_count = 0;
  12400. int32_t curr_contig_idx = -1;
  12401. uint32_t max_contig = 0;
  12402. int32_t max_contig_idx = -1;
  12403. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12404. const size_t curr_size = kv_cells[i].seq_id.size();
  12405. token_count += curr_size;
  12406. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12407. if (curr_size > 0) {
  12408. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12409. max_contig = i - curr_contig_idx;
  12410. max_contig_idx = curr_contig_idx;
  12411. }
  12412. curr_contig_idx = -1;
  12413. } else if (curr_contig_idx < 0) {
  12414. curr_contig_idx = i;
  12415. }
  12416. int seq_idx = 0;
  12417. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12418. if (seq_idx >= view->n_seq_max) {
  12419. break;
  12420. }
  12421. cs_curr[seq_idx] = it;
  12422. seq_idx++;
  12423. }
  12424. if (seq_idx != 0) {
  12425. used_cells++;
  12426. }
  12427. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12428. cs_curr[seq_idx] = -1;
  12429. }
  12430. }
  12431. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12432. max_contig_idx = curr_contig_idx;
  12433. max_contig = kv_cells.size() - curr_contig_idx;
  12434. }
  12435. view->max_contiguous = max_contig;
  12436. view->max_contiguous_idx = max_contig_idx;
  12437. view->token_count = token_count;
  12438. view->used_cells = used_cells;
  12439. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12440. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12441. __func__, ctx->kv_self.used, used_cells);
  12442. }
  12443. }
  12444. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12445. int result = 0;
  12446. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12447. result += ctx->kv_self.cells[i].seq_id.size();
  12448. }
  12449. return result;
  12450. }
  12451. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12452. return ctx->kv_self.used;
  12453. }
  12454. void llama_kv_cache_clear(struct llama_context * ctx) {
  12455. llama_kv_cache_clear(ctx->kv_self);
  12456. }
  12457. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12458. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12459. }
  12460. 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) {
  12461. if (seq_id_src == seq_id_dst) {
  12462. return;
  12463. }
  12464. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12465. }
  12466. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12467. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12468. }
  12469. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12470. if (delta == 0) {
  12471. return;
  12472. }
  12473. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12474. }
  12475. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12476. if (d == 1) {
  12477. return;
  12478. }
  12479. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12480. }
  12481. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12482. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12483. }
  12484. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12485. llama_kv_cache_defrag(ctx->kv_self);
  12486. }
  12487. void llama_kv_cache_update(struct llama_context * ctx) {
  12488. llama_kv_cache_update_internal(*ctx);
  12489. }
  12490. // deprecated
  12491. size_t llama_get_state_size(const struct llama_context * ctx) {
  12492. return llama_state_get_size(ctx);
  12493. }
  12494. // deprecated
  12495. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12496. return llama_state_get_data(ctx, dst);
  12497. }
  12498. // deprecated
  12499. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12500. return llama_state_set_data(ctx, src);
  12501. }
  12502. // deprecated
  12503. 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) {
  12504. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12505. }
  12506. // deprecated
  12507. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12508. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  12509. }
  12510. // Returns the *maximum* size of the state
  12511. size_t llama_state_get_size(const struct llama_context * ctx) {
  12512. const auto & cparams = ctx->cparams;
  12513. const auto & hparams = ctx->model.hparams;
  12514. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12515. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12516. const size_t s_rng_size = sizeof(size_t);
  12517. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12518. const size_t s_n_outputs = sizeof(size_t);
  12519. // assume worst case for outputs although only currently set ones are serialized
  12520. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12521. const size_t s_logits_size = sizeof(size_t);
  12522. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12523. const size_t s_embedding_size = sizeof(size_t);
  12524. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12525. const size_t s_kv_buf_size = sizeof(size_t);
  12526. const size_t s_kv_head = sizeof(uint32_t);
  12527. const size_t s_kv_size = sizeof(uint32_t);
  12528. const size_t s_kv_used = sizeof(uint32_t);
  12529. const size_t s_kv = ctx->kv_self.total_size();
  12530. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12531. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12532. const size_t s_total = (
  12533. + s_rng_size
  12534. + s_rng
  12535. + s_n_outputs
  12536. + s_output_pos
  12537. + s_logits_size
  12538. + s_logits
  12539. + s_embedding_size
  12540. + s_embedding
  12541. + s_kv_buf_size
  12542. + s_kv_head
  12543. + s_kv_size
  12544. + s_kv_used
  12545. + s_kv
  12546. + s_kv_cells
  12547. );
  12548. return s_total;
  12549. }
  12550. // llama_context_data
  12551. struct llama_data_context {
  12552. virtual void write(const void * src, size_t size) = 0;
  12553. virtual size_t get_size_written() = 0;
  12554. virtual ~llama_data_context() = default;
  12555. };
  12556. struct llama_data_buffer_context : llama_data_context {
  12557. uint8_t * ptr;
  12558. size_t size_written = 0;
  12559. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12560. void write(const void * src, size_t size) override {
  12561. memcpy(ptr, src, size);
  12562. ptr += size;
  12563. size_written += size;
  12564. }
  12565. size_t get_size_written() override {
  12566. return size_written;
  12567. }
  12568. };
  12569. struct llama_data_file_context : llama_data_context {
  12570. llama_file * file;
  12571. size_t size_written = 0;
  12572. llama_data_file_context(llama_file * f) : file(f) {}
  12573. void write(const void * src, size_t size) override {
  12574. file->write_raw(src, size);
  12575. size_written += size;
  12576. }
  12577. size_t get_size_written() override {
  12578. return size_written;
  12579. }
  12580. };
  12581. /** copy state data into either a buffer or file depending on the passed in context
  12582. *
  12583. * file context:
  12584. * llama_file file("/path", "wb");
  12585. * llama_data_file_context data_ctx(&file);
  12586. * llama_state_get_data(ctx, &data_ctx);
  12587. *
  12588. * buffer context:
  12589. * std::vector<uint8_t> buf(max_size, 0);
  12590. * llama_data_buffer_context data_ctx(&buf.data());
  12591. * llama_state_get_data(ctx, &data_ctx);
  12592. *
  12593. */
  12594. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12595. // copy rng
  12596. {
  12597. std::ostringstream rng_ss;
  12598. rng_ss << ctx->rng;
  12599. const std::string & rng_str = rng_ss.str();
  12600. const size_t rng_size = rng_str.size();
  12601. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12602. data_ctx->write(&rng_size, sizeof(rng_size));
  12603. data_ctx->write(rng_str.data(), rng_size);
  12604. }
  12605. // copy outputs
  12606. {
  12607. // Can't use ctx->n_outputs because it's not for the
  12608. // entire last batch when n_ubatch is smaller than n_batch
  12609. size_t n_outputs = 0;
  12610. // copy output ids
  12611. {
  12612. std::vector<int32_t> output_pos;
  12613. const size_t n_batch = ctx->cparams.n_batch;
  12614. const auto & output_ids = ctx->output_ids;
  12615. output_pos.resize(ctx->output_size);
  12616. // build a more compact representation of the output ids
  12617. for (size_t i = 0; i < n_batch; ++i) {
  12618. // map an output id to a position in the batch
  12619. int32_t pos = output_ids[i];
  12620. if (pos >= 0) {
  12621. if ((size_t) pos >= n_outputs) {
  12622. n_outputs = pos + 1;
  12623. }
  12624. GGML_ASSERT((size_t) pos < ctx->output_size);
  12625. output_pos[pos] = i;
  12626. }
  12627. }
  12628. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12629. if (n_outputs) {
  12630. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12631. }
  12632. }
  12633. // copy logits
  12634. {
  12635. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12636. data_ctx->write(&logits_size, sizeof(logits_size));
  12637. if (logits_size) {
  12638. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12639. }
  12640. }
  12641. // copy embeddings
  12642. {
  12643. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12644. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12645. if (embeddings_size) {
  12646. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12647. }
  12648. }
  12649. }
  12650. // copy kv cache
  12651. {
  12652. const auto & kv_self = ctx->kv_self;
  12653. const auto & hparams = ctx->model.hparams;
  12654. const uint32_t n_layer = hparams.n_layer;
  12655. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12656. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12657. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12658. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12659. const uint32_t kv_size = kv_self.size;
  12660. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12661. const uint32_t kv_used = kv_self.used;
  12662. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12663. data_ctx->write(&kv_head, sizeof(kv_head));
  12664. data_ctx->write(&kv_size, sizeof(kv_size));
  12665. data_ctx->write(&kv_used, sizeof(kv_used));
  12666. if (kv_buf_size) {
  12667. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12668. std::vector<uint8_t> tmp_buf;
  12669. for (int il = 0; il < (int) n_layer; ++il) {
  12670. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12671. tmp_buf.resize(k_size);
  12672. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12673. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12674. if (kv_self.recurrent) {
  12675. // v is contiguous for recurrent models
  12676. // TODO: use other tensors for state models than k and v
  12677. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12678. tmp_buf.resize(v_size);
  12679. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12680. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12681. continue;
  12682. }
  12683. // v is not contiguous, copy row by row
  12684. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12685. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12686. tmp_buf.resize(v_row_size);
  12687. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12688. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12689. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12690. }
  12691. }
  12692. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12693. }
  12694. for (uint32_t i = 0; i < kv_head; ++i) {
  12695. const auto & cell = kv_self.cells[i];
  12696. const llama_pos pos = cell.pos;
  12697. const size_t seq_id_size = cell.seq_id.size();
  12698. data_ctx->write(&pos, sizeof(pos));
  12699. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12700. for (auto seq_id : cell.seq_id) {
  12701. data_ctx->write(&seq_id, sizeof(seq_id));
  12702. }
  12703. }
  12704. }
  12705. }
  12706. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  12707. llama_data_buffer_context data_ctx(dst);
  12708. llama_state_get_data_internal(ctx, &data_ctx);
  12709. return data_ctx.get_size_written();
  12710. }
  12711. // Sets the state reading from the specified source address
  12712. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  12713. const uint8_t * inp = src;
  12714. // set rng
  12715. {
  12716. size_t rng_size;
  12717. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12718. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12719. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12720. std::istringstream rng_ss(rng_str);
  12721. rng_ss >> ctx->rng;
  12722. GGML_ASSERT(!rng_ss.fail());
  12723. }
  12724. // set output ids
  12725. {
  12726. size_t n_outputs;
  12727. std::vector<int32_t> output_pos;
  12728. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12729. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12730. if (n_outputs) {
  12731. output_pos.resize(n_outputs);
  12732. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12733. inp += n_outputs * sizeof(int32_t);
  12734. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12735. int32_t id = output_pos[i];
  12736. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12737. ctx->output_ids[id] = i;
  12738. }
  12739. }
  12740. }
  12741. // set logits
  12742. {
  12743. size_t logits_size;
  12744. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12745. GGML_ASSERT(ctx->logits_size >= logits_size);
  12746. if (logits_size) {
  12747. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12748. inp += logits_size * sizeof(float);
  12749. }
  12750. }
  12751. // set embeddings
  12752. {
  12753. size_t embeddings_size;
  12754. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12755. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12756. if (embeddings_size) {
  12757. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12758. inp += embeddings_size * sizeof(float);
  12759. }
  12760. }
  12761. // set kv cache
  12762. {
  12763. const auto & kv_self = ctx->kv_self;
  12764. const auto & hparams = ctx->model.hparams;
  12765. const uint32_t n_layer = hparams.n_layer;
  12766. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12767. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12768. size_t kv_buf_size;
  12769. uint32_t kv_head;
  12770. uint32_t kv_size;
  12771. uint32_t kv_used;
  12772. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12773. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12774. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12775. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12776. if (kv_self.size != kv_size) {
  12777. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12778. GGML_ASSERT(kv_self.size >= kv_head);
  12779. 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",
  12780. __func__, kv_head, kv_size, kv_self.size);
  12781. }
  12782. if (kv_buf_size) {
  12783. const size_t pre_kv_buf_size = inp - src;
  12784. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12785. for (int il = 0; il < (int) n_layer; ++il) {
  12786. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12787. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12788. inp += k_size;
  12789. if (kv_self.recurrent) {
  12790. // v is contiguous for recurrent models
  12791. // TODO: use other tensors for state models than k and v
  12792. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12793. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12794. inp += v_size;
  12795. continue;
  12796. }
  12797. // v is not contiguous, copy row by row
  12798. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12799. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12800. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12801. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12802. inp += v_row_size;
  12803. }
  12804. }
  12805. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12806. }
  12807. llama_kv_cache_clear(ctx);
  12808. ctx->kv_self.head = kv_head;
  12809. ctx->kv_self.used = kv_used;
  12810. for (uint32_t i = 0; i < kv_head; ++i) {
  12811. llama_pos pos;
  12812. size_t seq_id_size;
  12813. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12814. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12815. ctx->kv_self.cells[i].pos = pos;
  12816. llama_seq_id seq_id;
  12817. for (size_t j = 0; j < seq_id_size; ++j) {
  12818. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12819. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12820. }
  12821. }
  12822. }
  12823. const size_t nread = inp - src;
  12824. const size_t max_size = llama_state_get_size(ctx);
  12825. GGML_ASSERT(nread <= max_size);
  12826. return nread;
  12827. }
  12828. 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) {
  12829. llama_file file(path_session, "rb");
  12830. // sanity checks
  12831. {
  12832. const uint32_t magic = file.read_u32();
  12833. const uint32_t version = file.read_u32();
  12834. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12835. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12836. return false;
  12837. }
  12838. llama_hparams session_hparams;
  12839. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12840. if (session_hparams != ctx->model.hparams) {
  12841. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12842. return false;
  12843. }
  12844. }
  12845. // load the prompt
  12846. {
  12847. const uint32_t n_token_count = file.read_u32();
  12848. if (n_token_count > n_token_capacity) {
  12849. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12850. return false;
  12851. }
  12852. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12853. *n_token_count_out = n_token_count;
  12854. }
  12855. // restore the context state
  12856. {
  12857. const size_t n_state_size_cur = file.size - file.tell();
  12858. const size_t n_state_size_max = llama_state_get_size(ctx);
  12859. if (n_state_size_cur > n_state_size_max) {
  12860. 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);
  12861. return false;
  12862. }
  12863. std::vector<uint8_t> state_data(n_state_size_max);
  12864. file.read_raw(state_data.data(), n_state_size_cur);
  12865. llama_state_set_data(ctx, state_data.data());
  12866. }
  12867. return true;
  12868. }
  12869. 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) {
  12870. try {
  12871. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12872. } catch (const std::exception & err) {
  12873. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12874. return false;
  12875. }
  12876. }
  12877. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12878. llama_file file(path_session, "wb");
  12879. file.write_u32(LLAMA_SESSION_MAGIC);
  12880. file.write_u32(LLAMA_SESSION_VERSION);
  12881. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12882. // save the prompt
  12883. file.write_u32((uint32_t) n_token_count);
  12884. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12885. // save the context state using stream saving
  12886. llama_data_file_context data_ctx(&file);
  12887. llama_state_get_data_internal(ctx, &data_ctx);
  12888. return true;
  12889. }
  12890. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12891. try {
  12892. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  12893. } catch (const std::exception & err) {
  12894. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  12895. return false;
  12896. }
  12897. }
  12898. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  12899. // save the size of size_t as a uint32_t for safety check
  12900. const size_t size_t_size_size = sizeof(uint32_t);
  12901. // other values
  12902. const size_t s_cell_count_size = sizeof(uint32_t);
  12903. const size_t s_layer_count_size = sizeof(uint32_t);
  12904. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  12905. size_t s_cell_count = 0;
  12906. size_t s_cell_data_size = 0;
  12907. const auto & kv_self = ctx->kv_self;
  12908. const auto & hparams = ctx->model.hparams;
  12909. const uint32_t n_layer = hparams.n_layer;
  12910. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12911. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12912. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12913. const auto & cell = kv_self.cells[i];
  12914. if (cell.seq_id.count(seq_id) > 0) {
  12915. ++s_cell_count;
  12916. s_cell_data_size += sizeof(llama_pos);
  12917. }
  12918. }
  12919. for (int il = 0; il < (int)n_layer; ++il) {
  12920. // types of keys and values
  12921. s_cell_data_size += sizeof(int32_t) * 2;
  12922. // k_size_row and v_size_el values of layer
  12923. s_cell_data_size += sizeof(size_t) * 2;
  12924. // keys
  12925. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12926. s_cell_data_size += k_size_row * s_cell_count;
  12927. // values (transposed)
  12928. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12929. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  12930. }
  12931. const size_t s_total = (
  12932. size_t_size_size +
  12933. s_cell_count_size +
  12934. s_layer_count_size +
  12935. n_embd_v_gqa_size +
  12936. s_cell_data_size
  12937. );
  12938. return s_total;
  12939. }
  12940. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  12941. const auto & kv_self = ctx->kv_self;
  12942. GGML_ASSERT(!kv_self.recurrent); // not implemented
  12943. // Save the size of size_t as a uint32_t for safety check
  12944. const uint32_t size_t_size = sizeof(size_t);
  12945. data_ctx.write(&size_t_size, sizeof(size_t_size));
  12946. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  12947. uint32_t cell_count = 0;
  12948. // Count the number of cells with the specified seq_id
  12949. // Find all the ranges of cells with this seq id
  12950. {
  12951. uint32_t cell_range_begin = kv_self.size;
  12952. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12953. const auto & cell = kv_self.cells[i];
  12954. if (cell.has_seq_id(seq_id)) {
  12955. ++cell_count;
  12956. if (cell_range_begin == kv_self.size) {
  12957. cell_range_begin = i;
  12958. }
  12959. }
  12960. else {
  12961. if (cell_range_begin != kv_self.size) {
  12962. cell_ranges.push_back({ cell_range_begin, i });
  12963. cell_range_begin = kv_self.size;
  12964. }
  12965. }
  12966. }
  12967. if (cell_range_begin != kv_self.size) {
  12968. cell_ranges.push_back({ cell_range_begin, kv_self.size });
  12969. }
  12970. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  12971. uint32_t cell_count_check = 0;
  12972. for (const auto & range : cell_ranges) {
  12973. cell_count_check += range.second - range.first;
  12974. }
  12975. GGML_ASSERT(cell_count == cell_count_check);
  12976. }
  12977. // Write the cell count
  12978. data_ctx.write(&cell_count, sizeof(cell_count));
  12979. const auto & hparams = ctx->model.hparams;
  12980. const uint32_t n_layer = hparams.n_layer;
  12981. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12982. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12983. // Write the layer count
  12984. data_ctx.write(&n_layer, sizeof(n_layer));
  12985. // Write n_embd_v_gqa
  12986. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  12987. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  12988. for (const auto & range : cell_ranges) {
  12989. for (uint32_t i = range.first; i < range.second; ++i) {
  12990. const auto & cell = kv_self.cells[i];
  12991. data_ctx.write(&cell.pos, sizeof(cell.pos));
  12992. }
  12993. }
  12994. // Iterate and write all the keys first, each row is a cell
  12995. // Get whole range at a time
  12996. std::vector<uint8_t> tmp_buf;
  12997. for (int il = 0; il < (int)n_layer; ++il) {
  12998. // Write key type
  12999. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13000. data_ctx.write(&k_type_i, sizeof(k_type_i));
  13001. // Write row size of key
  13002. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13003. data_ctx.write(&k_size_row, sizeof(k_size_row));
  13004. // Read each range of cells of k_size length each into tmp_buf and write out
  13005. for (const auto & range : cell_ranges) {
  13006. const size_t range_size = range.second - range.first;
  13007. tmp_buf.resize(range_size * k_size_row);
  13008. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  13009. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13010. }
  13011. }
  13012. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  13013. const uint32_t kv_size = kv_self.size;
  13014. for (int il = 0; il < (int)n_layer; ++il) {
  13015. // Write value type
  13016. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13017. data_ctx.write(&v_type_i, sizeof(v_type_i));
  13018. // Write element size
  13019. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13020. data_ctx.write(&v_size_el, sizeof(v_size_el));
  13021. // For each row, we get the element values of each cell
  13022. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13023. // Read each range of cells of v_size_el length each into tmp_buf and write out
  13024. for (const auto & range : cell_ranges) {
  13025. const size_t range_size = range.second - range.first;
  13026. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  13027. tmp_buf.resize(range_size * v_size_el);
  13028. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  13029. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13030. }
  13031. }
  13032. }
  13033. return data_ctx.get_size_written();
  13034. }
  13035. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  13036. llama_data_buffer_context data_ctx(dst);
  13037. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13038. }
  13039. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  13040. auto & kv_self = ctx->kv_self;
  13041. GGML_ASSERT(!kv_self.recurrent); // not implemented
  13042. // Wipe the slot
  13043. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13044. const uint8_t * inp = src;
  13045. // Read size of size_t
  13046. uint32_t size_t_size;
  13047. memcpy(&size_t_size, inp, sizeof(size_t_size));
  13048. inp += sizeof(size_t_size);
  13049. if (size_t_size != sizeof(size_t)) {
  13050. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  13051. return 0;
  13052. }
  13053. // Read the cell count
  13054. uint32_t cell_count;
  13055. memcpy(&cell_count, inp, sizeof(cell_count));
  13056. inp += sizeof(cell_count);
  13057. // Read the layer count
  13058. uint32_t n_layer_ref;
  13059. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  13060. inp += sizeof(n_layer_ref);
  13061. // Read n_embd_v_gqa
  13062. uint32_t n_embd_v_gqa_ref;
  13063. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  13064. inp += sizeof(n_embd_v_gqa_ref);
  13065. // Sanity check model compatibility
  13066. const auto & hparams = ctx->model.hparams;
  13067. const uint32_t n_layer = hparams.n_layer;
  13068. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13069. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13070. if (n_layer != n_layer_ref) {
  13071. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  13072. return 0;
  13073. }
  13074. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  13075. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  13076. return 0;
  13077. }
  13078. // Allocate the new cells for the slot
  13079. if (cell_count) {
  13080. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  13081. batch.n_tokens = cell_count;
  13082. for (uint32_t i = 0; i < cell_count; ++i) {
  13083. llama_pos pos;
  13084. memcpy(&pos, inp, sizeof(pos));
  13085. inp += sizeof(pos);
  13086. batch.pos[i] = pos;
  13087. batch.n_seq_id[i] = 1;
  13088. batch.seq_id[i][0] = dest_seq_id;
  13089. }
  13090. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  13091. llama_batch_free(batch);
  13092. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  13093. return 0;
  13094. }
  13095. // 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)
  13096. // Assume that this is one contiguous block of cells
  13097. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  13098. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  13099. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  13100. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  13101. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  13102. // Cleanup
  13103. llama_batch_free(batch);
  13104. }
  13105. const uint32_t kv_size = kv_self.size;
  13106. const uint32_t kv_head = kv_self.head;
  13107. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  13108. for (int il = 0; il < (int)n_layer; ++il) {
  13109. // Read type of key
  13110. int32_t k_type_i_ref;
  13111. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  13112. inp += sizeof(k_type_i_ref);
  13113. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13114. if (k_type_i != k_type_i_ref) {
  13115. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13116. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  13117. return 0;
  13118. }
  13119. // Read row size of key
  13120. size_t k_size_row_ref;
  13121. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  13122. inp += sizeof(k_size_row_ref);
  13123. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13124. if (k_size_row != k_size_row_ref) {
  13125. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13126. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  13127. return 0;
  13128. }
  13129. if (cell_count) {
  13130. // Read and set the keys for the whole cell range
  13131. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  13132. inp += cell_count * k_size_row;
  13133. }
  13134. }
  13135. // For each layer, read the values for each cell (transposed)
  13136. for (int il = 0; il < (int)n_layer; ++il) {
  13137. // Read type of value
  13138. int32_t v_type_i_ref;
  13139. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  13140. inp += sizeof(v_type_i_ref);
  13141. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13142. if (v_type_i != v_type_i_ref) {
  13143. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13144. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  13145. return 0;
  13146. }
  13147. // Read element size of value
  13148. size_t v_size_el_ref;
  13149. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  13150. inp += sizeof(v_size_el_ref);
  13151. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13152. if (v_size_el != v_size_el_ref) {
  13153. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13154. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  13155. return 0;
  13156. }
  13157. if (cell_count) {
  13158. // For each row in the transposed matrix, read the values for the whole cell range
  13159. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13160. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  13161. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  13162. inp += cell_count * v_size_el;
  13163. }
  13164. }
  13165. }
  13166. const size_t nread = inp - src;
  13167. return nread;
  13168. }
  13169. 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) {
  13170. llama_file file(filepath, "wb");
  13171. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  13172. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  13173. // save the prompt
  13174. file.write_u32((uint32_t)n_token_count);
  13175. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  13176. // save the context state using stream saving
  13177. llama_data_file_context data_ctx(&file);
  13178. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13179. const size_t res = file.tell();
  13180. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  13181. return res;
  13182. }
  13183. 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) {
  13184. llama_file file(filepath, "rb");
  13185. // version checks
  13186. {
  13187. const uint32_t magic = file.read_u32();
  13188. const uint32_t version = file.read_u32();
  13189. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  13190. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  13191. return 0;
  13192. }
  13193. }
  13194. // load the prompt
  13195. {
  13196. const uint32_t n_token_count = file.read_u32();
  13197. if (n_token_count > n_token_capacity) {
  13198. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  13199. return 0;
  13200. }
  13201. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  13202. *n_token_count_out = n_token_count;
  13203. }
  13204. // restore the context state
  13205. {
  13206. const size_t state_size = file.size - file.tell();
  13207. std::vector<uint8_t> state_data(state_size);
  13208. file.read_raw(state_data.data(), state_size);
  13209. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  13210. if (!nread) {
  13211. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  13212. return 0;
  13213. }
  13214. GGML_ASSERT(nread <= state_size);
  13215. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  13216. }
  13217. return file.tell();
  13218. }
  13219. 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) {
  13220. try {
  13221. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  13222. } catch (const std::exception & err) {
  13223. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  13224. return 0;
  13225. }
  13226. }
  13227. 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) {
  13228. try {
  13229. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  13230. } catch (const std::exception & err) {
  13231. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  13232. return 0;
  13233. }
  13234. }
  13235. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  13236. ctx->cparams.n_threads = n_threads;
  13237. ctx->cparams.n_threads_batch = n_threads_batch;
  13238. }
  13239. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  13240. ctx->abort_callback = abort_callback;
  13241. ctx->abort_callback_data = abort_callback_data;
  13242. }
  13243. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  13244. ctx->cparams.causal_attn = causal_attn;
  13245. }
  13246. struct llama_batch llama_batch_get_one(
  13247. llama_token * tokens,
  13248. int32_t n_tokens,
  13249. llama_pos pos_0,
  13250. llama_seq_id seq_id) {
  13251. return {
  13252. /*n_tokens =*/ n_tokens,
  13253. /*tokens =*/ tokens,
  13254. /*embd =*/ nullptr,
  13255. /*pos =*/ nullptr,
  13256. /*n_seq_id =*/ nullptr,
  13257. /*seq_id =*/ nullptr,
  13258. /*logits =*/ nullptr,
  13259. /*all_pos_0 =*/ pos_0,
  13260. /*all_pos_1 =*/ 1,
  13261. /*all_seq_id =*/ seq_id,
  13262. };
  13263. }
  13264. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  13265. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  13266. if (embd) {
  13267. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  13268. } else {
  13269. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  13270. }
  13271. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  13272. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  13273. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  13274. for (int i = 0; i < n_tokens_alloc; ++i) {
  13275. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  13276. }
  13277. batch.seq_id[n_tokens_alloc] = nullptr;
  13278. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  13279. return batch;
  13280. }
  13281. void llama_batch_free(struct llama_batch batch) {
  13282. if (batch.token) free(batch.token);
  13283. if (batch.embd) free(batch.embd);
  13284. if (batch.pos) free(batch.pos);
  13285. if (batch.n_seq_id) free(batch.n_seq_id);
  13286. if (batch.seq_id) {
  13287. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  13288. free(batch.seq_id[i]);
  13289. }
  13290. free(batch.seq_id);
  13291. }
  13292. if (batch.logits) free(batch.logits);
  13293. }
  13294. int32_t llama_decode(
  13295. struct llama_context * ctx,
  13296. struct llama_batch batch) {
  13297. const int ret = llama_decode_internal(*ctx, batch);
  13298. if (ret < 0) {
  13299. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  13300. }
  13301. return ret;
  13302. }
  13303. void llama_synchronize(struct llama_context * ctx) {
  13304. ggml_backend_sched_synchronize(ctx->sched);
  13305. // FIXME: if multiple single tokens are evaluated without a synchronization,
  13306. // the stats will be added to the prompt evaluation stats
  13307. // this should only happen when using batch size 1 to evaluate a batch
  13308. // add the evaluation to the stats
  13309. if (ctx->n_queued_tokens == 1) {
  13310. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13311. ctx->n_eval++;
  13312. } else if (ctx->n_queued_tokens > 1) {
  13313. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13314. ctx->n_p_eval += ctx->n_queued_tokens;
  13315. }
  13316. // get a more accurate load time, upon first eval
  13317. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  13318. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  13319. ctx->has_evaluated_once = true;
  13320. }
  13321. ctx->n_queued_tokens = 0;
  13322. ctx->t_compute_start_us = 0;
  13323. }
  13324. float * llama_get_logits(struct llama_context * ctx) {
  13325. llama_synchronize(ctx);
  13326. return ctx->logits;
  13327. }
  13328. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  13329. int32_t j = -1;
  13330. llama_synchronize(ctx);
  13331. try {
  13332. if (ctx->logits == nullptr) {
  13333. throw std::runtime_error("no logits");
  13334. }
  13335. if (i < 0) {
  13336. j = ctx->n_outputs + i;
  13337. if (j < 0) {
  13338. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13339. }
  13340. } else if ((size_t) i >= ctx->output_ids.size()) {
  13341. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13342. } else {
  13343. j = ctx->output_ids[i];
  13344. }
  13345. if (j < 0) {
  13346. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13347. }
  13348. if (j >= ctx->n_outputs) {
  13349. // This should not happen
  13350. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13351. }
  13352. return ctx->logits + j*ctx->model.hparams.n_vocab;
  13353. } catch (const std::exception & err) {
  13354. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  13355. #ifndef NDEBUG
  13356. GGML_ASSERT(false);
  13357. #endif
  13358. return nullptr;
  13359. }
  13360. }
  13361. float * llama_get_embeddings(struct llama_context * ctx) {
  13362. llama_synchronize(ctx);
  13363. return ctx->embd;
  13364. }
  13365. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  13366. int32_t j = -1;
  13367. llama_synchronize(ctx);
  13368. try {
  13369. if (ctx->embd == nullptr) {
  13370. throw std::runtime_error("no embeddings");
  13371. }
  13372. if (i < 0) {
  13373. j = ctx->n_outputs + i;
  13374. if (j < 0) {
  13375. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13376. }
  13377. } else if ((size_t) i >= ctx->output_ids.size()) {
  13378. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13379. } else {
  13380. j = ctx->output_ids[i];
  13381. }
  13382. if (j < 0) {
  13383. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13384. }
  13385. if (j >= ctx->n_outputs) {
  13386. // This should not happen
  13387. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13388. }
  13389. return ctx->embd + j*ctx->model.hparams.n_embd;
  13390. } catch (const std::exception & err) {
  13391. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  13392. #ifndef NDEBUG
  13393. GGML_ASSERT(false);
  13394. #endif
  13395. return nullptr;
  13396. }
  13397. }
  13398. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  13399. llama_synchronize(ctx);
  13400. auto it = ctx->embd_seq.find(seq_id);
  13401. if (it == ctx->embd_seq.end()) {
  13402. return nullptr;
  13403. }
  13404. return it->second.data();
  13405. }
  13406. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  13407. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13408. return model->vocab.id_to_token[token].text.c_str();
  13409. }
  13410. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  13411. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13412. return model->vocab.id_to_token[token].score;
  13413. }
  13414. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  13415. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13416. return model->vocab.id_to_token[token].type;
  13417. }
  13418. llama_token llama_token_bos(const struct llama_model * model) {
  13419. return model->vocab.special_bos_id;
  13420. }
  13421. llama_token llama_token_eos(const struct llama_model * model) {
  13422. return model->vocab.special_eos_id;
  13423. }
  13424. llama_token llama_token_cls(const struct llama_model * model) {
  13425. return model->vocab.special_cls_id;
  13426. }
  13427. llama_token llama_token_sep(const struct llama_model * model) {
  13428. return model->vocab.special_sep_id;
  13429. }
  13430. llama_token llama_token_nl(const struct llama_model * model) {
  13431. return model->vocab.linefeed_id;
  13432. }
  13433. int32_t llama_add_bos_token(const struct llama_model * model) {
  13434. return model->vocab.special_add_bos;
  13435. }
  13436. int32_t llama_add_eos_token(const struct llama_model * model) {
  13437. return model->vocab.special_add_eos;
  13438. }
  13439. llama_token llama_token_prefix(const struct llama_model * model) {
  13440. return model->vocab.special_prefix_id;
  13441. }
  13442. llama_token llama_token_middle(const struct llama_model * model) {
  13443. return model->vocab.special_middle_id;
  13444. }
  13445. llama_token llama_token_suffix(const struct llama_model * model) {
  13446. return model->vocab.special_suffix_id;
  13447. }
  13448. llama_token llama_token_eot(const struct llama_model * model) {
  13449. return model->vocab.special_eot_id;
  13450. }
  13451. int32_t llama_tokenize(
  13452. const struct llama_model * model,
  13453. const char * text,
  13454. int32_t text_len,
  13455. llama_token * tokens,
  13456. int32_t n_tokens_max,
  13457. bool add_special,
  13458. bool parse_special) {
  13459. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_special, parse_special);
  13460. if (n_tokens_max < (int) res.size()) {
  13461. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  13462. return -((int) res.size());
  13463. }
  13464. for (size_t i = 0; i < res.size(); i++) {
  13465. tokens[i] = res[i];
  13466. }
  13467. return res.size();
  13468. }
  13469. static std::string llama_decode_text(const std::string & text) {
  13470. std::string decoded_text;
  13471. auto unicode_sequences = unicode_cpts_from_utf8(text);
  13472. for (auto & unicode_sequence : unicode_sequences) {
  13473. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  13474. }
  13475. return decoded_text;
  13476. }
  13477. // does not write null-terminator to buf
  13478. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  13479. if (0 <= token && token < llama_n_vocab(model)) {
  13480. switch (llama_vocab_get_type(model->vocab)) {
  13481. case LLAMA_VOCAB_TYPE_WPM:
  13482. case LLAMA_VOCAB_TYPE_SPM: {
  13483. // NOTE: we accept all unsupported token types,
  13484. // suppressing them like CONTROL tokens.
  13485. if (llama_is_normal_token(model->vocab, token)) {
  13486. std::string result = model->vocab.id_to_token[token].text;
  13487. llama_unescape_whitespace(result);
  13488. if (length < (int) result.length()) {
  13489. return -(int) result.length();
  13490. }
  13491. memcpy(buf, result.c_str(), result.length());
  13492. return result.length();
  13493. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13494. std::string result = model->vocab.id_to_token[token].text;
  13495. if (length < (int) result.length()) {
  13496. return -(int) result.length();
  13497. }
  13498. memcpy(buf, result.c_str(), result.length());
  13499. return result.length();
  13500. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  13501. if (length < 3) {
  13502. return -3;
  13503. }
  13504. memcpy(buf, "\xe2\x96\x85", 3);
  13505. return 3;
  13506. } else if (llama_is_control_token(model->vocab, token)) {
  13507. ;
  13508. } else if (llama_is_byte_token(model->vocab, token)) {
  13509. if (length < 1) {
  13510. return -1;
  13511. }
  13512. buf[0] = llama_token_to_byte(model->vocab, token);
  13513. return 1;
  13514. }
  13515. break;
  13516. }
  13517. case LLAMA_VOCAB_TYPE_BPE: {
  13518. // NOTE: we accept all unsupported token types,
  13519. // suppressing them like CONTROL tokens.
  13520. if (llama_is_normal_token(model->vocab, token)) {
  13521. std::string result = model->vocab.id_to_token[token].text;
  13522. result = llama_decode_text(result);
  13523. if (length < (int) result.length()) {
  13524. return -(int) result.length();
  13525. }
  13526. memcpy(buf, result.c_str(), result.length());
  13527. return result.length();
  13528. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13529. std::string result = model->vocab.id_to_token[token].text;
  13530. if (length < (int) result.length()) {
  13531. return -(int) result.length();
  13532. }
  13533. memcpy(buf, result.c_str(), result.length());
  13534. return result.length();
  13535. } else if (llama_is_control_token(model->vocab, token)) {
  13536. ;
  13537. }
  13538. break;
  13539. }
  13540. default:
  13541. GGML_ASSERT(false);
  13542. }
  13543. }
  13544. return 0;
  13545. }
  13546. // trim whitespace from the beginning and end of a string
  13547. static std::string trim(const std::string & str) {
  13548. size_t start = 0;
  13549. size_t end = str.size();
  13550. while (start < end && isspace(str[start])) {
  13551. start += 1;
  13552. }
  13553. while (end > start && isspace(str[end - 1])) {
  13554. end -= 1;
  13555. }
  13556. return str.substr(start, end - start);
  13557. }
  13558. // Simple version of "llama_apply_chat_template" that only works with strings
  13559. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  13560. static int32_t llama_chat_apply_template_internal(
  13561. const std::string & tmpl,
  13562. const std::vector<const llama_chat_message *> & chat,
  13563. std::string & dest, bool add_ass) {
  13564. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  13565. std::stringstream ss;
  13566. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  13567. // chatml template
  13568. for (auto message : chat) {
  13569. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  13570. }
  13571. if (add_ass) {
  13572. ss << "<|im_start|>assistant\n";
  13573. }
  13574. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  13575. // llama2 template and its variants
  13576. // [variant] support system message
  13577. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  13578. // [variant] space before + after response
  13579. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  13580. // [variant] add BOS inside history
  13581. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  13582. // [variant] trim spaces from the input message
  13583. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  13584. // construct the prompt
  13585. bool is_inside_turn = true; // skip BOS at the beginning
  13586. ss << "[INST] ";
  13587. for (auto message : chat) {
  13588. std::string content = strip_message ? trim(message->content) : message->content;
  13589. std::string role(message->role);
  13590. if (!is_inside_turn) {
  13591. is_inside_turn = true;
  13592. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  13593. }
  13594. if (role == "system") {
  13595. if (support_system_message) {
  13596. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  13597. } else {
  13598. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  13599. ss << content << "\n";
  13600. }
  13601. } else if (role == "user") {
  13602. ss << content << " [/INST]";
  13603. } else {
  13604. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  13605. is_inside_turn = false;
  13606. }
  13607. }
  13608. // llama2 templates seem to not care about "add_generation_prompt"
  13609. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  13610. // zephyr template
  13611. for (auto message : chat) {
  13612. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  13613. }
  13614. if (add_ass) {
  13615. ss << "<|assistant|>\n";
  13616. }
  13617. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  13618. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  13619. for (auto message : chat) {
  13620. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  13621. ss << bos << message->role << "\n" << message->content << "</s>\n";
  13622. }
  13623. if (add_ass) {
  13624. ss << "<s>assistant\n";
  13625. }
  13626. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13627. // google/gemma-7b-it
  13628. std::string system_prompt = "";
  13629. for (auto message : chat) {
  13630. std::string role(message->role);
  13631. if (role == "system") {
  13632. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13633. system_prompt = trim(message->content);
  13634. continue;
  13635. }
  13636. // in gemma, "assistant" is "model"
  13637. role = role == "assistant" ? "model" : message->role;
  13638. ss << "<start_of_turn>" << role << "\n";
  13639. if (!system_prompt.empty() && role != "model") {
  13640. ss << system_prompt << "\n\n";
  13641. system_prompt = "";
  13642. }
  13643. ss << trim(message->content) << "<end_of_turn>\n";
  13644. }
  13645. if (add_ass) {
  13646. ss << "<start_of_turn>model\n";
  13647. }
  13648. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13649. // OrionStarAI/Orion-14B-Chat
  13650. std::string system_prompt = "";
  13651. for (auto message : chat) {
  13652. std::string role(message->role);
  13653. if (role == "system") {
  13654. // there is no system message support, we will merge it with user prompt
  13655. system_prompt = message->content;
  13656. continue;
  13657. } else if (role == "user") {
  13658. ss << "Human: ";
  13659. if (!system_prompt.empty()) {
  13660. ss << system_prompt << "\n\n";
  13661. system_prompt = "";
  13662. }
  13663. ss << message->content << "\n\nAssistant: </s>";
  13664. } else {
  13665. ss << message->content << "</s>";
  13666. }
  13667. }
  13668. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  13669. // openchat/openchat-3.5-0106,
  13670. for (auto message : chat) {
  13671. std::string role(message->role);
  13672. if (role == "system") {
  13673. ss << message->content << "<|end_of_turn|>";
  13674. } else {
  13675. role[0] = toupper(role[0]);
  13676. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  13677. }
  13678. }
  13679. if (add_ass) {
  13680. ss << "GPT4 Correct Assistant:";
  13681. }
  13682. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  13683. // eachadea/vicuna-13b-1.1 (and Orca variant)
  13684. for (auto message : chat) {
  13685. std::string role(message->role);
  13686. if (role == "system") {
  13687. // Orca-Vicuna variant uses a system prefix
  13688. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  13689. ss << "SYSTEM: " << message->content << "\n";
  13690. } else {
  13691. ss << message->content << "\n\n";
  13692. }
  13693. } else if (role == "user") {
  13694. ss << "USER: " << message->content << "\n";
  13695. } else if (role == "assistant") {
  13696. ss << "ASSISTANT: " << message->content << "</s>\n";
  13697. }
  13698. }
  13699. if (add_ass) {
  13700. ss << "ASSISTANT:";
  13701. }
  13702. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  13703. // deepseek-ai/deepseek-coder-33b-instruct
  13704. for (auto message : chat) {
  13705. std::string role(message->role);
  13706. if (role == "system") {
  13707. ss << message->content;
  13708. } else if (role == "user") {
  13709. ss << "### Instruction:\n" << message->content << "\n";
  13710. } else if (role == "assistant") {
  13711. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  13712. }
  13713. }
  13714. if (add_ass) {
  13715. ss << "### Response:\n";
  13716. }
  13717. } else {
  13718. // template not supported
  13719. return -1;
  13720. }
  13721. dest = ss.str();
  13722. return dest.size();
  13723. }
  13724. LLAMA_API int32_t llama_chat_apply_template(
  13725. const struct llama_model * model,
  13726. const char * tmpl,
  13727. const struct llama_chat_message * chat,
  13728. size_t n_msg,
  13729. bool add_ass,
  13730. char * buf,
  13731. int32_t length) {
  13732. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13733. if (tmpl == nullptr) {
  13734. GGML_ASSERT(model != nullptr);
  13735. // load template from model
  13736. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13737. std::string template_key = "tokenizer.chat_template";
  13738. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13739. if (res < 0) {
  13740. // worst case: there is no information about template, we will use chatml by default
  13741. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13742. } else {
  13743. curr_tmpl = std::string(model_template.data(), model_template.size());
  13744. }
  13745. }
  13746. // format the chat to string
  13747. std::vector<const llama_chat_message *> chat_vec;
  13748. chat_vec.resize(n_msg);
  13749. for (size_t i = 0; i < n_msg; i++) {
  13750. chat_vec[i] = &chat[i];
  13751. }
  13752. std::string formatted_chat;
  13753. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13754. if (res < 0) {
  13755. return res;
  13756. }
  13757. if (buf && length > 0) {
  13758. strncpy(buf, formatted_chat.c_str(), length);
  13759. }
  13760. return res;
  13761. }
  13762. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13763. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13764. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13765. return strlen(split_path);
  13766. }
  13767. return 0;
  13768. }
  13769. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13770. std::string str_split_path(split_path);
  13771. char postfix[32];
  13772. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13773. std::string str_postfix(postfix);
  13774. // check if dest ends with postfix
  13775. int size_prefix = str_split_path.size() - str_postfix.size();
  13776. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13777. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13778. return size_prefix;
  13779. }
  13780. return 0;
  13781. }
  13782. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13783. struct llama_timings result = {
  13784. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13785. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13786. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13787. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13788. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13789. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13790. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13791. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13792. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13793. };
  13794. return result;
  13795. }
  13796. void llama_print_timings(struct llama_context * ctx) {
  13797. const llama_timings timings = llama_get_timings(ctx);
  13798. LLAMA_LOG_INFO("\n");
  13799. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13800. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13801. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13802. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13803. __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);
  13804. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13805. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13806. 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));
  13807. }
  13808. void llama_reset_timings(struct llama_context * ctx) {
  13809. ctx->t_start_us = ggml_time_us();
  13810. ctx->t_sample_us = ctx->n_sample = 0;
  13811. ctx->t_eval_us = ctx->n_eval = 0;
  13812. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13813. }
  13814. const char * llama_print_system_info(void) {
  13815. static std::string s;
  13816. s = "";
  13817. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13818. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13819. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13820. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13821. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13822. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13823. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13824. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13825. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13826. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13827. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13828. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13829. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13830. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13831. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13832. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13833. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13834. return s.c_str();
  13835. }
  13836. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13837. fprintf(stream, "\n");
  13838. fprintf(stream, "###########\n");
  13839. fprintf(stream, "# Timings #\n");
  13840. fprintf(stream, "###########\n");
  13841. fprintf(stream, "\n");
  13842. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13843. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13844. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13845. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13846. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13847. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13848. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13849. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13850. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13851. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13852. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13853. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13854. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13855. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13856. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13857. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13858. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13859. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13860. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13861. }
  13862. // For internal test use
  13863. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13864. struct llama_context * ctx
  13865. ) {
  13866. return ctx->model.tensors_by_name;
  13867. }
  13868. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13869. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13870. g_state.log_callback_user_data = user_data;
  13871. #ifdef GGML_USE_METAL
  13872. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13873. #endif
  13874. }
  13875. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13876. va_list args_copy;
  13877. va_copy(args_copy, args);
  13878. char buffer[128];
  13879. int len = vsnprintf(buffer, 128, format, args);
  13880. if (len < 128) {
  13881. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13882. } else {
  13883. char* buffer2 = new char[len+1];
  13884. vsnprintf(buffer2, len+1, format, args_copy);
  13885. buffer2[len] = 0;
  13886. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13887. delete[] buffer2;
  13888. }
  13889. va_end(args_copy);
  13890. }
  13891. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13892. va_list args;
  13893. va_start(args, format);
  13894. llama_log_internal_v(level, format, args);
  13895. va_end(args);
  13896. }
  13897. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13898. (void) level;
  13899. (void) user_data;
  13900. fputs(text, stderr);
  13901. fflush(stderr);
  13902. }